【发布时间】:2018-02-20 06:46:36
【问题描述】:
我是 Python 的新手,我正在尝试从 Zed Shaw 的书中做一个练习。我试图为我的问题找到答案并自行调试代码,但没有成功。
我收到“分配前引用的局部变量”错误,但仅在之后 循环其中一个分支。例如。当我在输入中选择非整数字符 (chosen_car = int(input("> "))) 时,该函数应该从头开始并允许我选择正确的值。但是当我之后选择正确的数字时,我得到一个错误。在 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!")
【问题讨论】:
-
在像您这样的问题中,清楚地了解程序结构很重要。请格式化您的代码。我们需要知道哪些语句在函数中,哪些不在。
-
所以常客不推荐 Zed 的书。请参阅here 以获得更好的介绍列表。
-
不要在 Python 中循环使用的地方使用递归。
-
感谢您的提示,我已对代码进行了格式化以使其更清晰。书单也很有用,我一定会用到的。
标签: python python-3.x