python - Python - 为未指定的输入创建通用函数
问题描述
如果用户键入除 1-5 以外的任何内容,我希望能够让该程序打印出类似“对不起,我无法识别该输入”的答案。
import time
rating=input()
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
if rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
if rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
if rating =='4':
time.sleep(.5)
print('Im offended.')
if rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
解决方案
使用if
,如果输入是除 1, 2, 3, 4, 5 以外的任何值,elif
代码中的 将打印您想要显示的消息。下面的代码也将阻止检查所有其他数字,因为. 在您的代码中,您正在检查 5 个 if 语句中的所有数字。else
else
elif
import time
rating=input()
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
elif rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
elif rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
elif rating =='4':
time.sleep(.5)
print('Im offended.')
elif rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
else:
print ('Sorry I dont recognize that input')
再次询问用户,直到输入正确的数字(根据您在下面的评论)
while rating:
if rating == '1':
time.sleep(.5)
print('Well, you mustve just had a bad day.')
break
elif rating =='2':
time.sleep(.5)
print('Second to last means I wasnt even the best at losing...')
break
elif rating =='3':
time.sleep(.5)
print('Atleast thats almost passing.')
break
elif rating =='4':
time.sleep(.5)
print('Im offended.')
break
elif rating =='5':
time.sleep(.5)
print('Well yeah, obviously.')
break
else:
print ('Sorry I dont recognize that input. Enter the rating again.')
rating=input()
continue
输出(第二种情况)
6
Sorry I dont recognize that input. Enter the rating again.
6
Sorry I dont recognize that input. Enter the rating again.
5
Well yeah, obviously.
推荐阅读
- swift - 错误:
:3:1: 错误:使用未解析的标识符 - tensorflow - 无法获得卷积算法错误〜ubuntu 20.04上的tensorflow-gpu
- c - 单击 GtkButton 时出现分段错误
- python - Python unittest正确设置全局变量
- amazon-web-services - 使用 AWS 服务器迁移服务完成服务器迁移后,原始使用的虚拟机可以做什么?
- php - 在 laravel 中处理每日表格
- r - as.Date.numeric(value) 中的错误:必须提供“原点”
- reactjs - 通过单击 ReactJs 中的按钮来切换背景颜色应用程序
- ios - 当应用请求相机权限时添加断点
- modelica - 如何在 Dymola 中找到函数调用错误?