如何接受int和float类型的输入?

2024-06-24 05:00:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个货币兑换器。如何让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")

这两个不起作用。


Tags: andtofrominputifabfloatamount
3条回答

我真的希望我没有完全误解这个问题,但我来了。

看起来您只是想确保传入的值可以像浮点数一样操作,而不管输入是3还是4.79例如,正确吗?如果是这样的话,那么在对输入进行操作之前,只需将其转换为一个浮点数。这是您修改后的代码:

def aud_brl(amount, From, to):
    ER = 0.42108 
    if From.strip() == 'aud' and to.strip() == 'brl': 
        result = amount/ER 
    elif From.strip() == 'brl' and to.strip() == 'aud': 
        result = amount*ER 

    print(result)

def question(): 
    amount = float(input("Amount: "))
    From = input("From: ") 
    to = input("To: ")

    if (From == 'aud' or From == 'brl') and (to == 'aud' or to == 'brl'): 
        aud_brl(amount, From, to)

question()

(为了整洁,我也做了一些改动,希望您不要介意<;3)

使用内置的isinstance函数

if isinstance(num, (int, float)):
    #do stuff

此外,应该避免对变量名使用保留关键字。关键字from是Python中的保留关键字

最后,我注意到另一个错误:

if From == 'aud' or 'brl'

应该是

if From == 'aud' or From == 'brl'

最后,要清理if语句,理论上可以使用列表(如果将来有更多的货币,这可能会更好)。

currencies = ['aud', 'brl']     #other currencies possible
if From in currencies and to in currencies:
    #do conversion

这就是检查给定字符串并接受intfloat(也可以转换为nb将是intfloat)的方法:

number = input("Enter a number: ")

nb = None
for cast in (int, float):
    try:
        nb = cast(number)
        print(cast)
        break
    except ValueError:
        pass

但是在您的例子中,仅仅使用float可能会起到作用(因为整数的字符串表示也可以转换为float:float('3') -> 3.0):

number = input("Enter a number: ")

nb = None
try:
    nb = float(number)
except ValueError:
    pass

如果nbNone,则您得到的某些内容无法转换为float

相关问题 更多 >