Problem
Let's say I wanted to make a function to convert my string to lowercase. My program would look a little like this:
Here I am trying to get the new comment, cmt, but when I run the program it yells at me with:# Returns a string in lowercasedef 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 functionprint ("Comment run through function to make it lowercase:")print (cmt)
Boo! I can't access the local variable inside the Make_Lowercase function.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
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