If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?
Answer from CambridgeCro on Stack OverflowIf your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?
You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.
number = input()
if '.' in number:
number = float(number)
else:
number = int(float(number))
Int or float of an input function in Python - Stack Overflow
How to accept only integer or float inputs?
I don't understand why you don't just use floats?
while True:
try:
time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continueBy typing an integer value, it'll just turn it into a float anyway.
More on reddit.comHow to make python accept both int and float input???
python 3.x - How to check if input is float or int? - Stack Overflow
What is the maximum value of an int in Python?
Can I use floats as dictionary keys in Python?
Why does 0.1 + 0.2 not equal 0.3 in Python?
input returns a string:
>>> x = input()
5.0
>>> x
'5.0'
If this string contains a representation of a number and you want to use it as a number, you need to call an appropriate function to parse the string and determine what number it represents:
>>> float(x)
5.0
However if the string doesn't represent a number, or if it doesn't represent a number of the type you're trying to convert it to, you will get an error:
>>> int(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
(Technically 5.0 is an integer, but typically we think of '5.0' as representing not the number 5.0 itself but as representing some unknown number which would round to 5.0, i.e. some number between 4.95 and 5.05. Hence the failure to convert to an integer.)
And of course if the string doesn't represent a number at all, all of this is right out.
>>> float('banana')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'banana'
EDIT: 0x5453 raises a good point in the comments, which is that prior to python 3 the language would do these string-to-number conversions implicitly in some cases, which may be what you're remembering.
The function input() gets text from the user as a string, the float() function is used to convert strings to float values. In the inputs you specified any value containing a comma will cause float() to throw an error since float() does not know what to do with the comma. The function does know how to convert numbers containing decimals though so those numbers will be fine. If you wanted to take input that contains commas you would have to sanitize your input like so:
float(input("How much money do you own, in dollars?\n").replace(',','')) # 50,000
My current code accepts integers that are greater than 0, which is what I want, but I also want to accept floats/decimals as well. How would I do this? Here is my current code:
while True:
try:
time = int(input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
if time > 0:
givenTime[2] = time
breakIndentation is off here for some reason, but believe me when I say that the indentation in the actual code is correct..
Can I just do time = int or float(input("How much time has elapsed since your last stop (in hours)?")) or would this be wrong? Any help would be appreciated.
edit: nope,
time = int or float(input("How much time has elapsed since your last stop (in hours)?"))
doesn't work.
I don't understand why you don't just use floats?
while True:
try:
time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
By typing an integer value, it'll just turn it into a float anyway.
here's something I wrote a few months ago for a similar question. Figure out how to modify it to do what you want:
def input_type(msg, type_converter):
while True:
s = input(msg)
try :
return type_converter(s)
except ValueError as e:
print(e)
def input_lessthan(msg, maximum, type_converter=int):
while True:
n = input_type(msg, type_converter)
if n <= maximum:
return n
print("Please enter a number less than {}".format(maximum))
print(input_lessthan("hours worked> ", 168, float))
TLDR: Convert your input using ast.literal_eval first.
The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed.
>>> number = input()
3
>>> number, type(number)
('3', <class 'str'>)
The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python's basic data types. It automatically parses int and float literals to the correct type.
>>> import ast
>>> number = ast.literal_eval(input())
3
>>> number, type(number)
(3, <class 'int'>)
In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:
import ast
number = ast.literal_eval(input("Please input your number...... \n"))
if type(number) is float:
print("Entered number is float and it's hexadecimal number is:", float.hex(number))
elif type(number) is int:
print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number))
else:
print("you entered an invalid type")
Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try-except to respond to this case:
import ast
try:
number = ast.literal_eval(input("Please input your number...... \n"))
except Exception as err:
print("Your input cannot be parsed:", err)
else:
if type(number) is float:
print("Entered number is float and it's hexadecimal number is:", float.hex(number))
elif type(number) is int:
print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number))
else:
print("you entered an invalid type")
input returns a string, you are trying to check whether it looks like a float or an integer:
number = input("Enter your number? ")
try:
number = int(number)
print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number))
except ValueError:
try:
number = float(number)
print("Entered number is float and it's hexadecimal number is:", float.hex(number))
except ValueError:
print("You entered an invalid number")
It has nothing about utility, it has to do with what are the possible range of values you're program should/needs to accept.
If it needs to accept both integers and floats as inputs, then you should convert to float since floats can represent the integers.
But if you're program requires that the input be specifically an integer, then you should be casting to int.
EDIT:
In your example, you should always be using float, since money has a decimal value.
If you were asking "How many bananas did you buy?" You'd want to convert to int since those values are going to be 0, 1, 2, 3, 4, .... And then when you ask "How much did you pay for these bananas?" You'd want to convert to float since those inputs can range from 3.15, .77, 1, 1.00, ... etc.
- So that you can work with numbers. You can't very well multiply
'3'by'2'in Python. - So that you can work with floating-point numbers. Some things in life can come in bits and pieces, like kilograms, seconds, or grade point averages.
- If your program needs to work with the numbers between consecutive integers, you should probably use
float. - If you use strings in your program, you may want them to be numbers, regardless of where the strings came from.
- You'll need to evaluate this on a case-by-case basis.
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()
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
Hello, please can someone explain to me when to use the float and int functions?
I mean should I use float when I am strictly dealing with decimal numbers, or when I want to convert whole numbers to decimal numbers?
pythonlearner
I think that the simplest way to handle this is to check if the input string is numeric first:
https://www.tutorialspoint.com/python/string_isnumeric.htm
if input.isnumeric():
print int(input)
else:
try
print float(input)
except ValueError:
# Do nothing
However if you can avoid exceptions completely the code would be better - exception handling can be quite expensive.
This answer to testing for an integer explains why exception handling can be expensive: https://stackoverflow.com/a/9859202/8358096
To avoid the second exception being hit regularly you could use the isalpha function mentioned below.
if input.isnumeric():
print int(input)
else:
if not input.isalpha():
try
print float(input)
except ValueError:
# Do nothing
You should use str.isalpha
The only time this breaks in cases like input = 'a2'.
inputs = ['aa','22','2.45']
for input in inputs:
if not input.isalpha():
try:
print int(input)
except ValueError:
print float(input)