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