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

21,287

Solution 1

I'm really hoping I'm not completely misunderstanding the question but here I go.

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

(I made a few changes as well for the sake of neatness, I hope you don't mind <3)

Solution 2

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.

Share:
21,287
Katrina
Author by

Katrina

Updated on July 09, 2022

Comments

  • Katrina
    Katrina 11 months

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

    Simple example of how I did it:

    number = input("Enter a number: ")
    
    if number == int:
        print("integer")
    if number == float:
        print("float")
    

    These two don't work.