On Tue, Sep 10, 2013 at 01:49:11PM -0400, novo shot wrote:

> When I declare a variable to be equal as the fucntion
> (result=theFunction("this either")) is Python also executing the
> function?

No, you have misunderstood. Equals in programming languages is not the 
same as equals in mathematics. Some languages, like Pascal, use := 
instead of = in order to avoid that misunderstanding.

In mathematics, "y = 3*x - 1" declares that y is equal to the equation 
on the right, no matter what value x happens to have.

But in programming, instead it *evaluates* the equation on the right, 
using the current value of x, and *assigns* the result to y.

So in your example above, result=theFunction("this either"), Python 
evaluates the function call theFunction("this either"), collects 
whatever result is returned (but not what is printed!), and assigns that 
to the variable "result".

Since theFunction prints some things, they will be printed but not 
assigned to anything. Only whatever is returned, using the "return" 
statement, will be assigned to variable "result".

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

It might help you to start with a simpler example:

def print_test():
    print "Hello World!"  # use print("...") in Python 3


This function takes no arguments, and always prints the same thing. It 
returns nothing. (To be precise, it returns the special object None, but 
don't worry about that.)

py> print_test()  # Round brackets calls the function
Hello World!
py> result = print_test()
Hello World!
py> result
py> 


So this demonstrates that printing values just prints them. You cannot 
access the printed result programatically. It just gets printed to the 
screen and that's it.


def return_test():
    return "And now for something completely different!"


This function uses return instead of print. Here it is in use:

py> return_test()
'And now for something completely different!'
py> result = return_test()
py> result
'And now for something completely different!'
py> result.upper()
'AND NOW FOR SOMETHING COMPLETELY DIFFERENT!'


So as you can see, using return is *much* more flexible. You can capture 
the result of the function, hold of printing it until you want, or 
process it further, pass it on to other functions, or so forth.


Finally, let's combine the two:


def test_both():
    print "This is immediately printed."
    return "And this is returned."



By now you hopefully should be able to predict what calling this 
function will do, but just in case you can't:


py> result = test_both()
This is immediately printed.
py> result
'And this is returned.'
py> result.upper()
'AND THIS IS RETURNED.'



-- 
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to