-2

I've just started python 3 practically yesterday and came across this error which I have no idea how to fix, could someone please help. Thanks! edit: its not the indentation, sorry the code here may have ended up with the wrong indentation when i pasted it here and had to do the 4 spacing.

q1 = input("Is it currently raining? ")
if q1 == "Yes":
    print("You should take the bus.")
elif q1 == "No":
    q2=int(input('How far in km do you need to travel? '))

if q2 > 10:
    print("You should take the bus.")
elif q2 >= 2 and q2 <= 10:
    print("You should ride your bike.")
elif q2 == 1:
    print("You should walk.")

Error:

Traceback (most recent call last):
  File "program.py", line 8, in <module>
    if q2 > 10:
NameError: name 'q2' is not defined

1 Answers1

2

Your indentation means that q2 is being checked even if q1 == "Yes", try:

q1 = input("Is it currently raining? ")
if q1.lower() in ("yes", "y"): # more flexible input
    print("You should take the bus.")
elif q1 == "No":
    q2 = int(input('How far in km do you need to travel? ')) 
    if q2 > 10: # inside elif block
        print("You should take the bus.")
    elif q2 >= 2: # already know it's 10 or under
        print("You should ride your bike.")
    elif q2 == 1:
        print("You should walk.")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437