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

后端 未结 4 1490
广开言路
广开言路 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:15

    this is how you could check the given string and accept int or float (and also cast to it; nb will be an int or a float):

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

    but in your case just using float might do the trick (as also string representations of integers can be converted to floats: float('3') -> 3.0):

    number = input("Enter a number: ")
    
    nb = None
    try:
        nb = float(number)
    except ValueError:
        pass
    

    if nb is None you got something that could not be converted to a float.

提交回复
热议问题