I'm a newbie in Python and I'm trying to do an excersise from Zed Shaw's book. I've tried to find an answer for my question and debug the code on my own but with no success.
I'm getting "local variable referenced before assignement" error but only after looping one of the branches. E.g. when I choose non-integer character in my input (chosen_car = int(input("> "))) the function should start from the beginning and allow me to choose a correct value. But when I choose the correct number after that I get an error. In a shell it look like this:
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
Here's the code. I'll be very helpful for your help.
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!")