全局名称未定义错误

时间:2013-12-21 15:09:21

标签: python global

我的代码:

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()

我当然得到:

NameError: global name 'gradschoolmultiplier' is not defined

我不够聪明,不能为别人理解这个问题的答案。有人会用简单的方式解释答案吗?谢谢!

2 个答案:

答案 0 :(得分:2)

确实正如@Dan所说,范围问题。

或者您可以使用global变量。

我对您的代码提出了一些其他建议:

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()

您应该合并一些if语句,以使其更简单。

哦,我们有同样的想法@jonrsharpe

@Nils建议的快速改进

答案 1 :(得分:1)

gradschoolmultiplier不在main()的范围内,只存在于start()

您可以将其传递给main。

将对main的调用更改为main(gradschoolmultiplier)

def main()更改为def main(gradschoolmultiplier):

Information on python scoping