【问题标题】:Receiving error, 'timesUsrPlayed" is not defined Pylance(reportUndefinedVariable)'接收错误,“timesUsrPlayed”未定义 Pylance(reportUndefinedVariable)'
【发布时间】:2021-09-11 10:28:50
【问题描述】:

我在函数之外定义了“timesUsrPlayed”变量,因此它不会重置它。当我将 1 添加到变量时,我在函数“randomPartOfGame”中调用 var '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()

【问题讨论】:

    标签: python


    【解决方案1】:

    我更改了您的代码,在您的 recursion 函数的第一个添加 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()
    

    【讨论】:

    • 啊,谢谢,我还意识到我在回忆“randomPartOfGame”后添加了部分,所以它在添加之前重新启动。
    【解决方案2】:

    您必须在 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")
        
    

    【讨论】:

      猜你喜欢
      • 2022-12-08
      • 2015-10-19
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2020-04-21
      • 2022-12-11
      相关资源
      最近更新 更多