接收错误,'timesUsrPlayed'未定义Pylance(reportUndefinedVariable)'

2024-09-29 22:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我在函数外部定义了'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()

Tags: thetoimportyougetosdefrandom
2条回答

我更改代码,首先添加global timesUsrPlayed函数(有关在recursion函数中需要global变量的更多详细信息,请阅读此link

然后print(f"{n} and {p}")print(f"yay you did, it took you {timesUsrPlayed} times to get a double")

试试这个:

import os
import random
import time


# a funcion to clear the console
clear = lambda: os.system('cls')

# counts the plays
timesUsrPlayed = 0

def randomPartOfGame():    
    global timesUsrPlayed
    n = random.randint(0,6)
    p = random.randint(0,6)
    print(f"{n} and {p}")

    if n != p:
        print("im sorry try again")
        randomPartOfGame()
        timesUsrPlayed += 1
    elif n == p:
        print(f"yay you did, it took you {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()

您必须在timesUsrPlayed之前使用global关键字来访问全局范围变量,这就是您缺少的示例

  if n != p:
        global timesUsrPlayed
         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")
    

相关问题 更多 >

    热门问题