我是Python的新手,我试图从Zed Shaw的书中做一个例外。我试图找到我的问题的答案,并自己调试代码,但没有成功。
我得到"在分配之前引用的局部变量"错误但仅在之后 循环其中一个分支。例如。当我在输入中选择非整数字符时(selected_car = int(输入(">"))),该函数应该从头开始,并允许我选择正确的值。但是当我选择正确的数字后,我得到一个错误。在shell中它看起来像这样:
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!")
答案 0 :(得分:1)
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
,程序将继续从用户那里获得输入。
我没有检查过代码,但我想这应该可行。
答案 1 :(得分:0)
通过在try语句之前将其设置为None来初始化selected_car。您将获得异常,因为当您到达第17行时,该变量尚未初始化。
答案 2 :(得分:0)
这是你的问题:
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:
如果进入除外,则不会定义所选择的汽车。我建议你在try之外定义它,或者把整个东西放在while循环中,而不是用choose_a_car()
递归。
答案 3 :(得分:0)
你可以这样做:
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()