首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过Python中的the ()函数为不能转换为整数的字符串提供无效消息?

如何通过Python中的the ()函数为不能转换为整数的字符串提供无效消息?
EN

Stack Overflow用户
提问于 2017-01-04 03:00:57
回答 2查看 43关注 0票数 1

我试图编写一个程序,根据用户对“您的身高是多少?”这个问题的响应,向他/她发出响应。

我遇到了第4-7行的问题,在第4-7行中,我试图要求用户输入一个有效的提示符(即,阻止接收不能转换为整数的字符串)。

我的密码在这里:

代码语言:javascript
运行
复制
#ask for user's height, and convert reply into an integer
height = int(input("What is your height?"))

#check if user's input can be converted to an integer
if type(height) != int:
    print("Please enter a valid number")
    height = int(input("What is your height?")

#give user a response, based on user's height
if height > 180: 
    print("Your height, " + str(height) + ", is above average")
elif height > 155: 
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")

任何帮助/建议都是非常感谢的!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-01-04 03:05:51

处理异常并重复,直到得到一个有效的数字:

代码语言:javascript
运行
复制
while True:
    try:
        height = int(input("What is your height? "))
        break
    except ValueError:
        print("Please enter a valid number")

if height > 180: 
    print("Your height, " + str(height) + ", is above average")
elif height > 155: 
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")

示例会话:

代码语言:javascript
运行
复制
What is your height?: abc
Please enter a valid number
What is your height?: xyz
Please enter a valid number
What is your height?: 180
Your height, 180, is average
票数 4
EN

Stack Overflow用户

发布于 2017-01-04 03:08:26

如果用户输入一个无效的数字,那么您的程序将在第1行上立即崩溃,并带有值错误

我建议的是在输入周围设置一个try/语句。

代码语言:javascript
运行
复制
height = 0
while True: # Will keep looping until correct input is given
    try:
        height = int(input("What is your height?"))
        break
    except ValueError:
        print("Please enter a valid number")

#give user a response, based on user's height
if height > 180: 
    print("Your height, " + str(height) + ", is above average")
elif height > 155: 
    print("Your height, " + str(height) + ", is average")
else:
    print("Your height, " + str(height) + ", is below average")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41455570

复制
相关文章

相似问题

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