ここでの問題は、Python で Currency1 が文字列に含まれているかどうかを確認できず、そうでない場合はエラーがあることを出力しますが、Currency1 が文字列に含まれている場合は、次に進み、ユーザーに Currency2 を入力してから確認するように依頼します。もう一度。
2 に答える
1
使用できますtry-except
:
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
于 2013-03-23T20:11:50.190 に答える
1
あなたは実際にしようとしていました:
if type(Currency1) in (float, int):
...
しかし、isinstance
ここではより良いです:
if isinstance(Currency1,(float,int)):
...
またはさらに良いことに、numbers.Number
abstract-base クラスを使用できます。
import numbers
if isinstance(Currency1,numbers.Number):
...Currency1 = str(raw_input(...))
が文字列であることを保証しますがCurrency1
(整数や浮動小数点数ではありません)。実際、raw_input
それを保証し、str
ここの余分なものは冗長です:-)。
文字列を数値に変換できるかどうかをチェックする関数が必要な場合は、試してみて確認するのが最も簡単な方法だと思います。
def is_float_or_int(s):
try:
float(s)
return True
except ValueError:
return False
于 2013-03-23T19:57:48.127 に答える