Reputation: 21
My code:
import sys
import time
import random
def main():
print('***TEST**** Grad School Multiplier=',gradschoolmultiplier,'***TEST***')
x=gradschoolmultiplier*50000
print('Your salary in dollars, $',x)
def start():
gradschool=input('Do you intend to go to Graduate School? ')
print('')
time.sleep(2)
if gradschool=='yes':print('That is a fantastic if expensive decision.')
elif gradschool=='Yes':print('That is a fantastic if expensive decision.')
elif gradschool=='Y':print('That is a fantastic if expensive decision.')
elif gradschool=='y':print('That is a fantastic if expensive decision.')
elif gradschool=='YES':print('That is a fantastic if expensive decision.')
else:print('No? Well, then it\'s off to work to pay back those student loans.')
print('')
if gradschool=='yes':g1=3
elif gradschool=='Yes':g1=3
elif gradschool=='Y':g1=3
elif gradschool=='y':g1=3
elif gradschool=='YES':g1=3
else:g1=1
g=random.randrange(1, 3)
if g==1:gradschoolmultiplier=1
else:gradschoolmultiplier=g1*g/2
time.sleep(2)
main()
start()
And of course I get:
NameError: global name 'gradschoolmultiplier' is not defined
I am not smart enough to understand the answers to this question for others. Would someone be so kind as to explain the answer in simpletons' terms? Thanks!
Upvotes: 1
Views: 16096
Reputation: 2508
Indeed as @Dan says, the scoping problem.
Or you can use global
variables.
Some of my other suggestions on your code:
import sys
import time
import random
def print_salary():
print('***TEST**** Grad School Multiplier=',gradschoolmultiplier,'***TEST***')
x = gradschoolmultiplier*50000
print('Your salary in dollars, $',x)
def main():
gradschool=input('Do you intend to go to Graduate School? ')
print('')
time.sleep(2)
if gradschool.lower() in {'yes', 'y'}:
print('That is a fantastic if expensive decision.')
g1 = 3
else:
print('No? Well, then it\'s off to work to pay back those student loans.')
g1 = 1
print('')
g = random.randrange(1, 3)
global gradschoolmultiplier
if g == 1:
gradschoolmultiplier = 1
else:
gradschoolmultiplier = g1 * g / 2
time.sleep(2)
print_salary()
if __name__ == '__main__':
main()
You should combine some the if
statements to make it simpler.
Oh, we share the same thoughts @jonrsharpe
Quick improvement as suggested by @Nils
Upvotes: 2
Reputation: 2872
gradschoolmultiplier
is not in the scope of main()
, it only exists in start()
.
You can pass it into main.
change the call to main to be main(gradschoolmultiplier)
change def main()
to def main(gradschoolmultiplier):
Upvotes: 1