How to accept the input of both int and float types?

后端 未结 4 1482
广开言路
广开言路 2021-01-21 09:18

I am making a currency converter. How do I get python to accept both integer and float?

This is how I did it:

def aud_brl(amount,From,to):
    ER = 0.421         


        
4条回答
  •  礼貌的吻别
    2021-01-21 10:02

    amount==int doesn't make sense. input gives us a string. int (and float) is a function. A string never equals a function.

    In [42]: x=input('test')
    test12.23
    In [43]: x
    Out[43]: '12.23'
    In [44]: int(x)
    ....
    ValueError: invalid literal for int() with base 10: '12.23'
    In [45]: float(x)
    Out[45]: 12.23
    

    float('12.23') returns a float object. int('12.23') produces an error, because it isn't a valid integer string format.

    If the user might give either '12' or '12.23', it is safer to use float(x) to convert it to a number. The result will be a float. For many calculations you don't need to worry whether it is a float or integer. The math is the same.

    You can convert between int and floats if needed:

    In [45]: float(x)
    Out[45]: 12.23
    In [46]: float(12)
    Out[46]: 12.0
    In [47]: int(12.23)
    Out[47]: 12
    In [48]: round(12.23)
    Out[48]: 12
    

    You can also do instance tests

    In [51]: isinstance(12,float)
    Out[51]: False
    In [52]: isinstance(12.23,float)
    Out[52]: True
    In [53]: isinstance(12.23,int)
    Out[53]: False
    In [54]: isinstance(12,int)
    Out[54]: True
    

    But you probably don't need to do any those.

提交回复
热议问题