我在做一个货币兑换器。如何让python同时接受整数和浮点数?
我就是这样做的:
def aud_brl(amount,From,to):
ER = 0.42108
if amount == int:
if From.strip() == 'aud' and to.strip() == 'brl':
ab = int(amount)/ER
print(ab)
elif From.strip() == 'brl' and to.strip() == 'aud':
ba = int(amount)*ER
print(ba)
if amount == float:
if From.strip() == 'aud' and to.strip() == 'brl':
ab = float(amount)/ER
print(ab)
elif From.strip() == 'brl' and to.strip() == 'aud':
ba = float(amount)*ER
print(ba)
def question():
amount = input("Amount: ")
From = input("From: ")
to = input("To: ")
if From == 'aud' or 'brl' and to == 'aud' or 'brl':
aud_brl(amount,From,to)
question()
我做这件事的简单例子:
number = input("Enter a number: ")
if number == int:
print("integer")
if number == float:
print("float")
这两个不起作用。
我真的希望我没有完全误解这个问题,但我来了。
看起来您只是想确保传入的值可以像浮点数一样操作,而不管输入是
3
还是4.79
例如,正确吗?如果是这样的话,那么在对输入进行操作之前,只需将其转换为一个浮点数。这是您修改后的代码:(为了整洁,我也做了一些改动,希望您不要介意<;3)
使用内置的isinstance函数
此外,应该避免对变量名使用保留关键字。关键字
from
是Python中的保留关键字最后,我注意到另一个错误:
应该是
最后,要清理if语句,理论上可以使用列表(如果将来有更多的货币,这可能会更好)。
这就是检查给定字符串并接受
int
或float
(也可以转换为nb
将是int
或float
)的方法:但是在您的例子中,仅仅使用float可能会起到作用(因为整数的字符串表示也可以转换为float:
float('3') -> 3.0
):如果
nb
是None
,则您得到的某些内容无法转换为float
。相关问题 更多 >
编程相关推荐