gpt4 book ai didi

python - 全局名称未定义错误

转载 作者:行者123 更新时间:2023-11-30 23:30:17 26 4
gpt4 key购买 nike

我的代码:

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

我不够聪明,无法为其他人理解这个问题的答案。有人能用简单的语言解释一下答案吗?谢谢!

最佳答案

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

或者您可以使用全局变量。

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

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 的建议进行快速改进

关于python - 全局名称未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20720338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com