Katrina
Katrina

Reputation: 109

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.

Upvotes: 5

Views: 39110

Answers (7)

shubham bhardwaj
shubham bhardwaj

Reputation: 1

# let's choose a random number
# from input, its type is string by default
number = input() 

try:
    
    x==int(number)      # check whether it is an int or float
    
except:
    
    x=float(number)

Upvotes: 0

catsock
catsock

Reputation: 1851

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

Upvotes: 6

Paul Omogie
Paul Omogie

Reputation: 1

I think you should just use float(input() function. And if a float or an int is entered, the interpreter will print the right values, unless a non float or non int is entered. E.g look at this simple function and you will see that both float and integers are taken:

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
print(f"The sum is: {num1 + num2 + num3}")

or this example:

while True: try: num = float(input("Enter number one: ")) break # Exit the loop if input is valid except ValueError: print("Please enter a valid number (integer or float).")

Now you can use the num variable which will be a float

print("You entered:", num)

Upvotes: -1

user17825338
user17825338

Reputation: 1

These seem to work well.

def getInt():
        """
                input returns a str,
                coerce return to required type 
        """
    x = str()
    while type(x) != int:
        try:
            return int(input('enter an integer: '))
        except ValueError: continue


def getFloat():
        """
                input returns a str,
                coerce return to required type 
        """
    x = str()
    while type(x) != float:
        try:
            return float(input('enter a float: '))
        except ValueError: continue

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46921

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.

Upvotes: 4

hpaulj
hpaulj

Reputation: 231655

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.

Upvotes: 1

Abid Hasan
Abid Hasan

Reputation: 658

Use the isinstance function, which is built in

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

Also, you should refrain from using reserved keywords for variable names. The keyword from is a reserved keyword in Python

Finally, there is one other error I noticed:

if From == 'aud' or 'brl'

Should be

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

Lastly, to clean up the if statements you could theoretically use the list (if you have more currencies in the future, this might be better.

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

Upvotes: 4

Related Questions