虽然我输入了一个数值,但它仍然给我一个错误。我不知道为什么会发生这种情况..帮助别人吗?
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:')
答案 0 :(得分: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")
答案 1 :(得分: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:')
答案 2 :(得分:1)
您不应该使用try语句,我认为您不应该使用isalpha()。 isnumeric()测试数字有效性。 isalpha()将为“%# - @”之类的字符串返回false。
while True:
s = input("Enter amount: ")
if s.isnumeric():
break
print("There was a problem. Enter a number.")