Saturday 16 May 2015

Returning A Value From A Function To Be Used Outside The Function in Python 3

Functions are really useful for doing stuff for you in a program. But the hardest thing for me to work out was how to use what ever they did in the rest of my program.

Problem
Let's say I wanted to make a function to convert my string to lowercase. My program would look a little like this:

# Returns a string in lowercase
def Make_Lowercase(cmt):
cmt = cmt.lower()
comment = "My name is SCOTT."
print ("Commment without lowercase formatting:")
print (comment)
print("")
 
#Replace the old variable with the lowercase one created in the function
print ("Comment run through function to make it lowercase:")
print (cmt)
 Here I am trying to get the new comment, cmt, but when I run the program it yells at me with:
Traceback (most recent call last):
  File "C:/Users/Im/Batman/Python3/ReturnFunction.py", line 13, in <module>
    print(cmt)
NameError: name 'cmt' is not defined
Boo! I can't access the local variable inside the Make_Lowercase function.

Solution
To fix this, we need to return the variable inside the function and place the result back into the original (or a new variable. Up to you.) variable.

Here is an example:

Now we can use the results from the function outside of the function and in the rest of the program. Yay!


No comments:

Post a Comment