-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 に答える