pythonpython-3.xfloating-pointintegeruser-input

How to accept both integer and float values as input?


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.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()

This is another example of how I did it:

number = input("Enter a number: ")

if number == int:
    print("integer")
if number == float:
    print("float")

But those two ways don't work.


Solution

  • It looks like you just want to make sure the value passed in can be operated upon like a float, regardless of whether the input is 3 or 4.79 for example, correct? If that's the case, then just cast the input as a float before operating on it.

    Here's your modified code:

    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()