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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
###Using a variable in a function from outside the function### | |
###Returning a value from a function to be used outside the function.### | |
# Returns a string in lowercase | |
def Make_Lowercase(cmt): | |
cmt = cmt.lower() | |
return cmt | |
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 | |
comment = Make_Lowercase(comment) | |
print ("Comment run through function to make it lowercase:") | |
print (comment) |
No comments:
Post a Comment