赋值前引用的python UnboundLocalError局部变量'Opportunits'

2024-04-28 05:38:21 发布

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

下面的代码在执行时显示了错误,在执行Looper()之前,我不是在第二行中执行了辅助吗?但是,当我在Looper()的第一行中添加chances=5时,它就起作用了

import random

chances = 5
def Looper():
    if chances != 0:
        if real_answer == user_answer:
            print("Gotcha")
            exit()
        elif real_answer < user_answer:
            chances -= 1
            print("Too large")
        else:
            chances -= 1
            print("Too small")
real_answer = random.randint(1, 1000)
user_answer = int(input("This is a guessing game, please guess a         number from 1 to 1000. You have 5 chances"))

Looper()

Tags: 代码answerimportifdef错误exitrandom
1条回答
网友
1楼 · 发布于 2024-04-28 05:38:21

除了希望chances成为Looper的参数(例如def looper(chances=5):)之外,还可以在函数内部使用global chances来获取外部变量的引用

更好:

def looper(chances=5):
    if chances != 0:
        ...

也有可能,但是是全局状态

CHANCES = 5
def looper():
    global CHANCES
    if CHANCES != 0:
        ...

完整故事:

import random

def looper(real_answer, chances=5):
    for _ in range(chances):
        user_answer = int(input("This is a guessing game, please guess a number from 1 to 1000. You have %i chances" % (chances, )))
        if real_answer == user_answer:
            return True
        elif real_answer < user_answer:
            print("Too large")
        else:
            print("Too small")

if __name__ == '__main__':
    real_answer = random.randint(1, 1000)    
    if looper(real_answer):
        print("Gotcha")

相关问题 更多 >