def get_currency(msg):
curr = input(msg)
try:
float(curr)
print('You must enter text. Numerical values are not accepted at this stage')
return get_currency(msg) #ask for input again
except:
return curr #valid input, return the currency name
curr1=get_currency('Please enter the currency you would like to convert:')
curr2=get_currency('Please enter the currency you would like to convert into:')
ExRate = float(input('Please enter the exchange rate in the order of, 1 '+curr1+' = '+curr2))
Amount = float(input('Please enter the amount you would like to convert:'))
print (Amount*ExRate)
输出:
$ python3 foo.py
Please enter the currency you would like to convert:123
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert:rupee
Please enter the currency you would like to convert into:100
You must enter text. Numerical values are not accepted at this stage
Please enter the currency you would like to convert into:dollar
Please enter the exchange rate in the order of, 1 rupee = dollar 50
Please enter the amount you would like to convert: 10
500.0
您可以使用
try-except
:输出:
你实际上是想:
但是
isinstance
在这里更好:或者更好,您可以使用
numbers.Number
抽象基类:尽管。。。
Currency1 = str(raw_input(...))
将保证Currency1
是字符串(不是整数或浮点)。实际上,raw_input
提供了这个保证,这里多余的str
只是多余的:-)。你知道吗如果您想让函数检查字符串是否可以转换为数字,那么我认为最简单的方法就是尝试一下,看看:
相关问题 更多 >
编程相关推荐