提问人:Kwaku Ibrahim Tweneboah Asiedu 提问时间:7/20/2023 更新时间:7/20/2023 访问量:54
如何修复 python 中 while 循环中的值错误
How to fix Value error in a while loop in python
问:
我写了一个小程序,里面有一个while循环语句。所有行都运行良好,除了最后一行代码,它应该会破坏循环。每当 Python 尝试解释它时,它总是显示错误。我尝试以多种方式更改改写代码,但无济于事。你能帮帮我吗? 这是程序:
prompt = "\nWhat is your age?"
prompt += "\n(Please enter 'quit' when you are finished.) "
while True:
age = input(prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age >= 3 and age <= 12:
print("Your ticket costs $10.")
elif age > 12:
print("Your ticket costs $15.")
elif age == 'quit':
break
当我运行它时,它会显示以下内容:
What is your age? (Please enter 'quit' when you are finished.) 7 Your ticket costs $10. What is your age? (Please enter 'quit' when you are finished.) 8 Your ticket costs $10. What is your age? (Please enter 'quit' when you are finished.) 1 Your ticket is free. What is your age? (Please enter 'quit' when you are finished.) quit Traceback (most recent call last): File "C:\Users\ibrah\OneDrive\Desktop\python_work\chapter_7\movie_tickets.py", line 7, in <module> age = int(age) ^^^^^^^^ ValueError: invalid literal for int() with base 10: 'quit'
我尝试将该值转换为该行中的值,这将错误转换为字符串,但它仍然不起作用。
答:
3赞
Josh Clark
7/20/2023
#1
您正在尝试转换为 ,这会提高 .相反,您可以尝试在通话前检查是否:"quit"
int
ValueError
age
"quit"
int
prompt = "\nWhat is your age?"
prompt += "\n(Please enter 'quit' when you are finished.) "
while True:
age = input(prompt) # Get input
if age == "quit": # Check if "quit" was input
break
age = int(age) # If not, convert to int
if age < 3: # ...
print("Your ticket is free.")
elif age >= 3 and age <= 12:
print("Your ticket costs $10.")
elif age > 12:
print("Your ticket costs $15.")
你也可以把你的第二个改成(我们已经知道是)和你的最后一个改成.elif
<= 12
>= 3
elif
else
0赞
Sudipto Bhattacharya
7/20/2023
#2
您必须检查“prompt”变量是否为整数。 使用以下代码进行检查 if ((type(prompt)==int) ||(prompt.is_integer())): 做你的定价人员 还: 检查是否输入退出
评论
0赞
Kwaku Ibrahim Tweneboah Asiedu
7/21/2023
非常感谢。它现在运行良好。
评论
int("quit")
age