[Tutor] Question about Functions

Prasad, Ramit ramit.prasad at jpmorgan.com.dmarc.invalid
Tue Sep 10 22:33:06 CEST 2013


novo shot wrote:
> Dear tutors:
> 
> The following is an example I found in the Raspberry Pi for Dummies book:
> 
> #function test
> 
> def theFunction(message):
>     print "I don't get ", message
>     return "ARRRGH!"
> 
> theFunction("this")
> 
> result=theFunction("this either")
> print "reply is: ", result
> 
> ---------------------------------------------
> The result of this code looks like this:
> 
> I don't get  this
> I don't get  this either
> reply is:  ARRRGH!
> 
> ----------------------------------------------
> Here's what I don't understand:
> 
> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the
> function?

Yes, when you do function() it calls the function.
In this case it is calling theFunction with the
string arguments 'this' and 'this either', respectively.

> The way I see it, I only called for the function once before printing
> ARRRGH!! Then after that I declared a variable and then I print.
> 
> This is how I expected the result to look like:
> 
> I don't get this
> reply is: I don't get this either
> ARRRGH!


You do not get this output because you do not return the 
string with the `message`, you print it immediately and 
return "ARRRGH!". "ARRRGH!" then gets bound to the name 
`result` which you then print.

If you want the result you specify you should return 

"reply is: " + result # where result must be a string

Not sure how to expect to get "ARRRGH!" unless you return that 
too. You can return multiple objects but you typically need to 
attach it to an object. Lists and tuples are frequently used to 
return multiple objects. Some examples are below.

# tuple
return a,b,c
# list (in-line)
return [ a, b, c]
# list (created and all objects added earlier)
list_object = []
for x in xrange(4):
    list_object.append( x ) #just an example
return list_object

# as attribute (use when you need to pass state / data handling)
obj = Class()
obj.attribute = [a,b,c]
return obj


> 
> -----------------------------------------
> 
> Can you help me understand? I can't move forward until I understand
> how Python solves this code.

I recommend going through some beginner Python tutorials first
to get a grasp of how Python works before you start on a book
for Raspberry Pi.

> 
> Thanks in advance
> Optional


~Ramit



This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list