我想在用户被要求再次输入内容之前弹出错误

时间:2013-04-17 18:13:02

标签: python python-3.x function

在上面的代码中,当我按任何其他键时,我想在返回user_input之前弹出一条错误消息。请帮助别人?

2 个答案:

答案 0 :(得分:2)

检查while循环结束时它是否有效:

currencies = ['pound', 'euro', 'dollar', 'yen', '$', '£', '¥','€']

def get_currency(msg):
    while True:
        user_input = input(msg).lower()

        if user_input not in currencies:
            print('Invalid currency')
        else:
            return user_input

答案 1 :(得分:2)

# -*- coding: utf-8 -*-
valid = ['pound', 'euro', 'dollar', 'yen', '$', '£', '¥','€']
msg="Enter currency: "
def get_currency(msg):

    input_valid = input(msg).lower()

    while input_valid not in valid:       #run this loop until the input is not valid
        print ("Invalid Input, Try again")  #the error message
        input_valid = input(msg).lower()

    return input_valid

print (get_currency(msg))

<强>输出:

~$ python3 so.py
Enter currency: foo
Invalid Input, Try again
Enter currency: bar
Invalid Input, Try again
Enter currency: pound
pound