Python 为什么我使用'exec()`的代码会抛出错误?
我在做一些事情,问你想做什么,然后去做。但是当我调用另一个文件时,它不会读取整个文件 这是调用另一个脚本的代码Python 为什么我使用'exec()`的代码会抛出错误?,python,python-3.x,Python,Python 3.x,我在做一些事情,问你想做什么,然后去做。但是当我调用另一个文件时,它不会读取整个文件 这是调用另一个脚本的代码 if math == "yes": exec(open("calculator.py").read());''' 这是被调用的脚本 ''' else: print('You have not typed a valid operator, please run the program again.') # Add again() function
if math == "yes":
exec(open("calculator.py").read());'''
这是被调用的脚本
'''
else:
print('You have not typed a valid
operator, please run the program again.')
# Add again() function to calculate() function
again()
def again():
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
这就是错误所在
Traceback (most recent call last):
File "C:\Users\cahen\Desktop\chat bot.py", line
17, in <module>
main()
File "C:\Users\cahen\Desktop\chat bot.py", line
14, in main
exec(open("calculator.py").read());
File "<string>", line 47, in <module>
File "<string>", line 32, in calculate
NameError: name 'again' is not defined
如果我自己运行calculator.py,它就可以正常工作。就在我从另一个脚本调用它时,它出现了问题。很明显,在定义它之前,您尝试再次调用该函数:
'''
else:
print('You have not typed a valid
operator, please run the program again.')
# Add again() function to calculate() function
again() # <----------------- CALLED HERE
def again(): # <----------------- DEFINED HERE
calc_again = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if calc_again.upper() == 'Y':
calculate()
elif calc_again.upper() == 'N':
print('See you later.')
else:
again()
calculate()
从即时错误中后退一步,为什么要这样运行calculator.py?为什么不从中导入函数并调用它们呢?我知道在定义函数之前我会再次调用函数。这个程序本身运行得很好,只是当我称之为它遇到了没有定义的问题。@Chris我不知道你的意思。我也不知道你想在这里完成什么。