Python Functions And Variables Trouble
I have created this code so far... def print_slow(str): for letter in str: sys.stdout.write(letter) sys.stdout.flush() time.sleep(0.005) def menu():
Solution 1:
You're setting a local variable sentence
inside function option1
. This variable is not visible in option2
since it lives inside option1
only and will be cleaned up once option1
is finished.
If you want to share the variable, you need to define it as global
at least in option1
:
def option1():
print_slow("Enter sentence")
global sentence
sentence = str(input(": "))
print(" ")
menu()
Note, however, that using global variables is usually a sign of bad code quality. In your case, it would make more sense to have option1
return sentence
to main
, and pass it from main
to option2
.
Solution 2:
Your issue is in assigning a value to sentence
. Since you are assigning it in a function, when you leave that function's scope, you lose the value. Try using global
:
sentence = ''defoption1():
global sentence # <-- this maintains its value in global scope
print_slow("Enter sentence")
sentence = str(input(": "))
print(" ")
menu()
defoption2():
global sentence # <-- and hereifnot sentence:
print_slow("Please enter a sentence first!")
time.sleep(0.5)
print(" ")
else:
sentenceUppercase = sentence.upper()
Or you could pass it back and forth with parameters.
Post a Comment for "Python Functions And Variables Trouble"