Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-UnboundLocalError:在循环中赋值之前引用的局部变量_Python_Python 3.x - Fatal编程技术网

Python-UnboundLocalError:在循环中赋值之前引用的局部变量

Python-UnboundLocalError:在循环中赋值之前引用的局部变量,python,python-3.x,Python,Python 3.x,我是Python方面的新手,我想做一个Zed Shaw书中的练习。我试图为我的问题找到答案,并自己调试代码,但没有成功 我得到“赋值前引用的局部变量”错误,但只有在 绕着一根树枝转。例如,当我在输入中选择非整数字符(选择的_car=int(输入(“>”)时),函数应从头开始,并允许我选择正确的值。但是当我选择了正确的数字之后,我得到了一个错误。在外壳中,它看起来像这样: You're about to start a race. You should buy a car before you s

我是Python方面的新手,我想做一个Zed Shaw书中的练习。我试图为我的问题找到答案,并自己调试代码,但没有成功

我得到“赋值前引用的局部变量”错误,但只有在 绕着一根树枝转。例如,当我在输入中选择非整数字符(选择的_car=int(输入(“>”)时),函数应从头开始,并允许我选择正确的值。但是当我选择了正确的数字之后,我得到了一个错误。在外壳中,它看起来像这样:

You're about to start a race.
You should buy a car before you start.
Let's see how much you have in your pocket.
> Check your poocket (hit enter to proceed)
Oh, you have 1 thousands. Let's see what you can buy with it
> Ok
Choose your car:
    1. Race Car 4k
    2. Sedan 2k
    3. Pickup 1k
> w
Don't waste my time, choose a correct number.
Choose your car:
    1. Race Car 4k
    2. Sedan 2k
    3. Pickup 1k
> 3
Congratulations, you bought a Pickup
Traceback (most recent call last):
  File "ex36.py", line 35, in <module>
    choose_a_car()
  File "ex36.py", line 17, in choose_a_car
    if chosen_car >= 0 and chosen_car <= 3:
UnboundLocalError: local variable 'chosen_car' referenced before assignment
from random import randint


def get_number(msg, minimum, maximum):
    while True:
        try:
            num = int(input(msg))
        except ValueError:
            print("Don't waste my time, choose a correct number.")
        else:
            if num >= minimum and num <= maximum:
                return num


def choose_a_car():

    # the list of cars [cost, name]
    cars = [[4, "Hidden Super Car"], [4, "Race Car"], [2, "Sedan"], [1, "Pickup"]]

    print(f"Choose your car:\n\t1. {cars[1][1]} {cars[1][0]}k \n\t2. {cars[2][1]} {cars[2][0]}k \n\t3. {cars[3][1]} {cars[3][0]}k")

    chosen_car = get_number('> ', minimum=1, maximum=3)

    if cars[chosen_car][0] <= money:
        print(f"Congratulations, you bought a {cars[chosen_car][1]}")
    else:
        print("Unfortunately, you don't have enough money to buy this car")


print("You're about to start a race.")
print("You should buy a car before you start.")
print("Let's see how much you have in your pocket.")
input("> Check your pocket (hit enter to proceed)")
money = int(randint(1,4))
print(f"Oh, you have {money} thousands. Let's see what you can buy with it")
input("> Ok")
choose_a_car()
您即将开始一场比赛。
你应该在开车前买辆车。
让我们看看你口袋里有多少钱。
>检查您的poocket(按enter键继续)
哦,你有一千。让我们看看你能用它买什么
>嗯
选择您的汽车:
1.赛车4k
2.轿车2k
3.皮卡1k
>w
不要浪费我的时间,选择一个正确的数字。
选择您的汽车:
1.赛车4k
2.轿车2k
3.皮卡1k
> 3
恭喜你,你买了一辆皮卡
回溯(最近一次呼叫最后一次):
文件“ex36.py”,第35行,在
选择车()
文件“ex36.py”,第17行,在choose_a_car中

如果选择了\u car>=0,并且选择了\u car=0,并且选择了\u car则在try语句之前,通过将其设置为无来初始化选择的\u car。您将获得异常,因为当您到达第17行时,该变量尚未初始化

这是您的问题:

try:
    chosen_car = int(input("> "))
except ValueError:
    print("Don't waste my time, choose a correct number.")
    choose_a_car()

if chosen_car >= 0 and chosen_car <= 3:
试试看:
所选车=int(输入(“>”)
除值错误外:
打印(“不要浪费我的时间,选择一个正确的数字。”)
选择车()
如果选择了车>=0且选择了车
此代码段使用递归。因此,如果用户输入了无效的输入,程序将进入除
之外的
块并再次调用该函数。如果用户在第二次调用中输入了正确的号码,则第二次调用将成功终止,您将返回到第一次函数调用。但是,在第一次调用中,由于输入无效,没有定义所选的车。因此,程序会因错误而崩溃。您可以尝试使用如下标志,而不是递归:

myFlag = True
while( myFlag):
    try:
        chosen_car = int(input("> "))
        myFlag = False
    except ValueError:
        print("Don't waste my time, choose a correct number.")
通过这样做,如果程序在
selected\u car=int(input(“>”)
行中崩溃,
myFlag
未设置为
False
,程序将继续从用户获取输入


我还没有检查代码,但我想应该可以。您可以这样做:

You're about to start a race.
You should buy a car before you start.
Let's see how much you have in your pocket.
> Check your poocket (hit enter to proceed)
Oh, you have 1 thousands. Let's see what you can buy with it
> Ok
Choose your car:
    1. Race Car 4k
    2. Sedan 2k
    3. Pickup 1k
> w
Don't waste my time, choose a correct number.
Choose your car:
    1. Race Car 4k
    2. Sedan 2k
    3. Pickup 1k
> 3
Congratulations, you bought a Pickup
Traceback (most recent call last):
  File "ex36.py", line 35, in <module>
    choose_a_car()
  File "ex36.py", line 17, in choose_a_car
    if chosen_car >= 0 and chosen_car <= 3:
UnboundLocalError: local variable 'chosen_car' referenced before assignment
from random import randint


def get_number(msg, minimum, maximum):
    while True:
        try:
            num = int(input(msg))
        except ValueError:
            print("Don't waste my time, choose a correct number.")
        else:
            if num >= minimum and num <= maximum:
                return num


def choose_a_car():

    # the list of cars [cost, name]
    cars = [[4, "Hidden Super Car"], [4, "Race Car"], [2, "Sedan"], [1, "Pickup"]]

    print(f"Choose your car:\n\t1. {cars[1][1]} {cars[1][0]}k \n\t2. {cars[2][1]} {cars[2][0]}k \n\t3. {cars[3][1]} {cars[3][0]}k")

    chosen_car = get_number('> ', minimum=1, maximum=3)

    if cars[chosen_car][0] <= money:
        print(f"Congratulations, you bought a {cars[chosen_car][1]}")
    else:
        print("Unfortunately, you don't have enough money to buy this car")


print("You're about to start a race.")
print("You should buy a car before you start.")
print("Let's see how much you have in your pocket.")
input("> Check your pocket (hit enter to proceed)")
money = int(randint(1,4))
print(f"Oh, you have {money} thousands. Let's see what you can buy with it")
input("> Ok")
choose_a_car()
来自随机导入randint
def get_编号(消息、最小值、最大值):
尽管如此:
尝试:
num=int(输入(msg))
除值错误外:
打印(“不要浪费我的时间,选择一个正确的数字。”)
其他:

如果num>=最小值,并且num现在引发TypeError,尽管它对我不起作用。现在,我在第19行得到一个新错误:TypeError:“>=”在“NoneType”和“int”的实例之间不受支持。我不知道这是为什么。当程序到达这一行时,新的值被分配给所选的_car变量,然后将其转换为整数。新的值不会被分配。阅读有关范围的内容。在像你这样的问题中,清楚地理解程序结构是很重要的。请格式化您的代码。我们需要知道哪些语句在函数中,哪些不在函数中。所以常客不推荐Zed的书。请参阅以获得更好的介绍列表。不要在Python中使用循环的地方使用递归。感谢您的提示,我已经格式化了代码以使其更清晰。一本书的目录也很有用,我肯定会用到其中的一些。它很有效——非常感谢。这也有助于更好地理解这个问题。我认为在输入无效输入后,第二个调用中的函数从一开始就开始了,python不会“记住”第一个调用。从你所说的,我知道事实恰恰相反-输入正确的值后,程序再次开始进行第一次调用。第一个解决方案对我不起作用。我在第19行遇到了一个新错误:TypeError:“>=”在“NoneType”和“int”的实例之间不受支持。我不知道为什么我会得到它,因为当程序到达第19行时,新的值应该分配给所选的车变量。是的,第一个解决方案不起作用。只有第二个解决方案(由您接受的答案实现)是正确的。我不知道我是否理解为什么第一个不起作用。是因为Python在获得正确的值后再次重复第一次调用,并且记住了原始输入吗?它不记得原始输入,因为它进入了except。对于第二个解决方案,所选的汽车将是您定义为在try之外的任何值,在这种情况下,它是零。由于它无法将
None
0
进行比较,因此它会抛出一个错误。感谢您为该问题提供了新的视角。