我在函数外部定义了'timesUsrPlayed'变量,因此它不会重置它。当我向变量中添加1时,在调用函数“randomPartOfGame”中的变量“timesUsrPlayed”的时间下会出现黄色的摆动线。当我将鼠标悬停在这些行上时,会显示“timesUsrPlayed”未定义Pylance(reportUndefinedVariable)”。我真的希望我说得很清楚:
import os
import random
# a funcion to clear the console
clear = lambda: os.system('cls')
# counts the plays
timesUsrPlayed = 0
def randomPartOfGame():
n = random.randint(0,6)
p = random.randint(0,6)
print(str(n) + " and " + str(p))
if n != p:
print("im sorry try again")
randomPartOfGame()
timesUsrPlayed += 1
elif n == p:
print("yay you did, it took you "+ str(timesUsrPlayed) +" times to get a double")
def mainGameFunction():
print('game starting...')
time.sleep(2)
clear()
print('welcome you need to get a double in dice (is means get the same number)')
randomPartOfGame()
我更改代码,首先添加
global timesUsrPlayed
函数(有关在recursion
函数中需要global
变量的更多详细信息,请阅读此link然后
print(f"{n} and {p}")
和print(f"yay you did, it took you {timesUsrPlayed} times to get a double")
试试这个:
您必须在timesUsrPlayed之前使用global关键字来访问全局范围变量,这就是您缺少的示例
相关问题 更多 >
编程相关推荐