-1

虽然我输入了一个数值,但它仍然给我一个错误。我不知道为什么会这样..帮助别人?

def is_string(s):
    rate = input(s)
    try:
        str.isalpha(rate)
        print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ')
        return is_string(s)  #ask for input again
   except:
        return rate
ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2)

def is_string2(msg):
    amount = input(msg)
    try:
        str.isalpha(amount)
        print('There was an error. Please try again. Make sure you use numerical values. ')
        return is_string2(msg)  #ask for input again
    except:
        return amount
Amount = is_string2('Please enter the amount you would like to convert:')
4

3 回答 3

4

你在寻找这样的东西吗?

def get_int(prompt, error_msg):
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print(error_msg)


rate = get_int(
    'Please enter the exchange rate in the order of, 1 {} = {}'
        .format(Currency1, Currency2),
    error_msg="Rate must be an integer")
amount = get_int(
    'Please enter the amount you would like to convert:',
    error_msg="Amount must be an integer")
于 2013-03-23T22:57:50.567 回答
2

我不确定你为什么要使用异常,什么时候应该使用 if 语句:

def is_string(s):
    rate = input(s)
    if str.isalpha(rate):
        print('There was an error. Please try again. Make sure you use numerical values and alpabetical. ')
        return is_string(s)  #ask for input again
    else:
        return rate
ExRate = is_string('Please enter the exchange rate in the order of, 1 '+Currency1+' = '+Currency2)

def is_string2(msg):
    amount = input(msg)
    if str.isalpha(amount):
        print('There was an error. Please try again. Make sure you use numerical values. ')
        return is_string2(msg)  #ask for input again
    else:
        return amount
Amount = is_string2('Please enter the amount you would like to convert:')
于 2013-03-23T22:54:36.130 回答
1

您不应该使用 try 语句,而且我认为您不应该使用 isalpha()。isnumeric() 测试数字有效性。isalpha() 将为“%#-@”之类的字符串返回 false。

while True:
    s = input("Enter amount: ")
    if s.isnumeric():
        break
    print("There was a problem. Enter a number.")
于 2013-03-23T23:04:11.623 回答