简体   繁体   English

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

[英]Python - Creating generic functions for unspecified input

I would like to be able to have this program print out an answer that says something like 'Sorry I dont recognize that input' if the user types anything other than 1-5. 如果用户键入的不是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.')

Make use of if , elif and else where if the input is anything except 1, 2, 3, 4, 5, the else in the code will print the message you want to be displayed. 使用ifelif以及else ,如果输入的内容不是1,2,3,4,5,则代码中的else将打印您要显示的消息。 The code below also will prevent checking all the other numbers because of the elif . 下面的代码也将由于elif阻止检查所有其他数字。 In your code, you were checking all the numbers in 5 if statements. 在您的代码中,您正在检查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')

Asking the user again until the correct number is entered (based on your comment below) 再次询问用户,直到输入正确的号码为止 (根据下面的评论)

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

Output (second case) 输出(第二种情况)

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM