首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python while _ValueError

Python while _ValueError
EN

Stack Overflow用户
提问于 2021-11-09 18:44:41
回答 1查看 31关注 0票数 0

在这个程序中,如果用户输入字符串输入,程序将不会运行,用户将得到一个错误。我如何开发我的程序来告诉用户输入错误?你能帮我解决这个问题吗?

代码语言:javascript
复制
summation = 0
while True:
    user_input = input("Enter your input \n")
    if user_input == "done":
        break
    else:
        summation = summation + float(user_input)
        print("End \n", "SUMMATION = ", summation)

"conention.py/while.py"
Enter your input 
Hi
Traceback (most recent call last):
File "c:\Users\ASUS\Desktop\python\name conention.py\while.py", line 7, 
in <module> summation = summation + float(user_input)
ValueError: could not convert string to float: 'Hi'

PS C:\Users\ASUS\Desktop\python> 
EN

回答 1

Stack Overflow用户

发布于 2021-11-09 18:58:13

你运行float("Hi"),这就产生了问题。

您应该使用try/except来捕获错误并执行某些操作或跳过它。

例如。

代码语言:javascript
复制
summation = 0

while True:
    user_input = input("Enter your input \n")
    
    if user_input.lower() == "done":
        break
    
    try:
        summation = summation + float(user_input)
        print("End \n", "SUMMATION = ", summation)
    except ValueError:
        print('It is not float value:', user_input)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69903471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档