我是 Python 的新手,我正在尝试从 Zed Shaw 的书中做一个练习。我试图为我的问题找到答案并自行调试代码,但没有成功。
我收到“分配之前引用的局部变量”错误,但仅在循环其中一个分支之后。例如,当我在输入中选择非整数字符 (chosen_car = int(input("> "))) 时,该函数应该从头开始并允许我选择正确的值。但是当我在那之后选择正确的数字时,我得到一个错误。在外壳中它看起来像这样:
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
from sys import exit
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")
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:
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")
choose_a_car()
else:
print("There is no such a car")
choose_a_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 poocket (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()
print("Let's start a race!")
print("1! \n2! \n3! \nSTART!")
try:
chosen_car = int(input("> "))
except ValueError:
print("Don't waste my time, choose a correct number.")
choose_a_car()
此代码段使用递归。因此,如果用户输入无效的输入,程序将进入except
块并再次调用该函数。如果用户在第二次调用中输入了正确的数字,则第二次调用成功终止,您将返回到第一个函数调用。但是,在第一次调用中,chosen_car
由于输入无效而未定义。因此程序因错误而崩溃。除了递归,您可以尝试使用如下标志:
myFlag = True
while( myFlag):
try:
chosen_car = int(input("> "))
myFlag = False
except ValueError:
print("Don't waste my time, choose a correct number.")
通过这样做,如果程序在线崩溃chosen_car = int(input("> "))
,myFlag
则不会设置为False
并且程序继续从用户那里获取输入。
我没有检查代码,但我想应该可以。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句