Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

FlightType=input("Which flight would you like to fly? Type '2 Seater', '4   Seater', or 'Historic'.")
# No validation included for the input

FlightLen=input("Would you like to book the '30' minutes flight or the '60'")
# No validation included for the input

if (FlightLen==30):
    MaxSlots=(600/FlightLen)

elif (FlightLen==60):
    MaxSlots=(600//FlightLen)

print (MaxSlots)

When I run the code, why does the following error message appear?

NameError: name 'MaxSlots' is not defined

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

input() is always returned as a string and thus never equal to an integer.

The function then reads a line from input, converts it to a string (stripping a trailing newline)

See the documentation

Your if or elif is never true since an integer is not a string in the Python world (if you used an else it would always return that) so you never define the new variable (since it is never run). What you need to do is to convert each input() to an integer. This can be done using int() function:

FlightLen=int(input("Would you like to book the '30' minutes flight or the '60'"))

Here FlightLen has been converted to an integer once an input value has been given.


You do not need the () in the if elif statements if you are using Python 3 either:

if FlightLen==30:
elif FlightLen==60:

If you are using Python 2 print does not take an ()


You might also want to add an else to make sure FlightLen is always defined, ensuring you do not get this error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...