Python-为未指定的输入创建通用函数

时间:2018-10-04 16:49:12

标签: 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.')

1 个答案:

答案 0 :(得分:2)

使用ifelifelse,如果输入除了1、2、3、4、5外,则代码中的else打印您要显示的消息。由于elif,下面的代码还将防止检查所有其他数字。在您的代码中,您正在检查5 if语句中的所有数字。

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.