[英]Why my code using `exec()` is throwing an error?
我正在做一些詢問你想做什么然后去做的事情。 但是當我調用另一個文件時,它不會讀取整個文件。
這是調用另一個腳本的代碼
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,它工作正常。只是當我從另一個混亂的腳本調用它時。
很明顯,您嘗試在定義之前調用again
函數:
'''
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.