5

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Katrina
  • 111
  • 2
  • 2
  • 10
  • 1
    I changed your title and headings to lowercase. Please refrain from shouting at us :) – gyre Apr 22 '17 at 20:14
  • `if type(number) is int` But that will always be false, since `number` will always be a string. – juanpa.arrivillaga Apr 22 '17 at 20:21
  • @juanpa.arrivillaga no it is not. He's using `input` to read from user, `type(numer)` is `str`. – GIZ Apr 22 '17 at 20:23
  • 2
    Just so you know, the line `if From == 'aud' or 'brl' and to == 'aud' or 'brl'` will always evaluate to `True`, since `'brl'` is truthy in both conditions. If you're looking to see whether `From` is `'aud'` or `'brl'`, you need something like this: `if From == 'aud' or From == 'brl' ...` – blacksite Apr 22 '17 at 20:49

6 Answers6

5

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)

Spooky
  • 1,752
  • 21
  • 37
3

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
Abid Hasan
  • 648
  • 4
  • 10
  • `isinstance(num, (int, float))` can be done directly... and it looks as if OPs input starts with strings. – hiro protagonist Apr 22 '17 at 20:28
  • @hiroprotagonist The true Pythonic solution here, of course, would be duck typing and catching an error if a non int/float is passed! – Abid Hasan Apr 22 '17 at 20:33
  • How would I be able to convert it, if the currencies are not specified in the if statement? – Katrina Apr 22 '17 at 22:09
  • @KGarcia you would have to restructure your code significantly for that, which is beyond the scope of this comment, but if you are planning on having multiple currencies being converted, the way you have laid out your function is quite inefficient – Abid Hasan Apr 22 '17 at 22:35
3

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • Why did the other guy said, "The true Pythonic solution here, of course, would be duck typing and catching an error if a non int/float is passed!"? Can you please explain? I'm new in programming. – Katrina Apr 22 '17 at 22:42
  • this has nothing to do with duck-typing. i just try to convert a string to a float in a manner that will never crash. one of the python philosophies is [EAFP](https://docs.python.org/3/glossary.html#term-eafp) as opposed to [LBYL](https://docs.python.org/3/glossary.html#term-lbyl). so python coders wil often `try` something instead of checking things first. (e.g. if you wanted to convert a `str` to an `int` you could check first if the string consists of digits only; that is not a pythonic thing to do). – hiro protagonist Apr 23 '17 at 06:06
0

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

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
johnbchron
  • 28
  • 6
  • Please use the code blocks when writing/sharing code. – Mo. Atairu Jan 03 '22 at 21:25
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 03 '22 at 21:26
0

number = input() # lets choose a random number #from input it type is string bydefault

try:

x==int(number)      #check wheather it is an int or float

x=int(number)

except :

x=float(number)