Python为未指定inpu创建泛型函数

2024-09-27 17:53:05 发布

您现在位置: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.')

Tags: 答案用户import程序youinputiftime
1条回答
网友
1楼 · 发布于 2024-09-27 17:53:05

利用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.

相关问题 更多 >

    热门问题