嗨,我目前正在学习python,只是尝试了一些东西
# Import module
import random
random.seed()
# (Random) values and calculation
firstValue = random.randint(1,10)
secondValue = random.randint(1,10)
sol = firstValue + secondValue
# Define function called in try section of while-loop
def getUserInput():
print("--- Please solve:", firstValue, "+", secondValue, "---")
playerSol = input()
playerSolInt = int(playerSol)
counter = 0
falseAnswer = True
while falseAnswer:
counter += 1
try:
getUserInput()
except:
print("--- You did not enter a number. ---")
continue
if sol == playerSolInt:
print("--- Correct answer! ---")
falseAnswer = False
else:
print("--- False answer! ---")
print("--- You tried", counter, "times in total. ---")
print("*** Program has stopped ***")
getUserInput()的函数内容主要是在try中调用函数的地方:。。。现在,当我定义函数时,它告诉我playerSolInt没有定义。在IDE中,以及在终端中调用函数时,它会在异常中解析。在程序开始时用0初始化变量不会改变任何内容
那么,这是怎么回事?这可能是一件简单的事情,因为缺乏知识,我无法动脑
先谢谢大家😬
看看这个关于Python Scoping的教程
您的
playerSolInt
变量在函数外部不可用,因此需要从函数返回它并在外部赋值变量
playerSolInt
是函数getUserInput
的局部变量。你需要让它全球化。以下代码工作:相关问题 更多 >
编程相关推荐