Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

Variable not defined (Python)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...