简体   繁体   中英

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.

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. The code below also will prevent checking all the other numbers because of the elif . In your code, you were checking all the numbers in 5 if statements.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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