如何添加用户输入的值,显示总计和qui

2024-09-27 00:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加用户输入的值,在输入q退出后显示总数。我想在退出程序之前显示该值,但我总是遇到此错误

Exception has occurred: Value Error invalid literal for integer () with base 10: 'q'"

while True: 
    seatvalue = int(input("please enter seat value (eg.30), 'q' to quit ")) 
    if seatvalue == 'q': 
        print [(seatvalue) + (seatvalue)] 
        print ("bye") 
        break

Tags: 用户程序forvalue错误exceptionerrorinteger
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:05

问题是:

int(input("please enter seat value (eg.30), 'q' to quit ")

该行尝试将“q”转换为int,只需在转换为int之前检查是否为int,就可以通过“isnumeric”函数实现这一点

value=0
while True: 
    given_value = input("please enter seat value (eg.30), 'q' to quit ")
    if given_value == 'q': 
        print(value)
        print("bye")
        break 
    if given_value.isnumeric():
        value += int(given_value)

请注意,此代码将省略所有不是数字或“q”的内容

相关问题 更多 >

    热门问题