We were coding something awhile ago and we came across a small problem. We wanted to try to convert float numbers to integers
Here is the code:
x = int(input(())
print x
We tried the code and put 5.5. It evaluated to a ValueError. Logically, it is sound in logic. But if we try the following code:
x = int(float(input(())) OR x = int(5.5), it evaluates to a value of 5.
Why does this happen?
In the first case, you are calling int("5.5"), because input() returns a string. that's a ValueError because 5.5 is not an int, and the designers of python decided not to do any implicit casting.
In the second case, you care calling float("5.5"), which is 5.5 because "5.5" can be converted to a float as you asked, and then int(5.5), which is the result of converting a float to an int (python uses truncation for this; you can call round() instead if that's not what you want).
The third case is just the same as the second step of the second case.
Its because of input() takes the value as a string data type. When you are taking "5" then converting into int() works but converting string input "5.5" to int() will give error as this is not supported by python. In such a case, you have to first convert it to float() and then int() to get an integer value.
I think x = int(5.5) didn't lead to any value error. First problem is, yeah, you cannot directly compare it an input result with int or float. To make sure it let's do this little experiment:
>>> x = input()
>>? 20
>>> print(type(x))
>>> <class 'str'>
From this experiment, you see that even you enter "any numerical" to input, it will return your input as string. And let's check what's going on with int(input()) operation:
x = int(input())
5.5
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.5'
This problem happen when you try to 'directly' convert a float to integer. Python cannot convert literally float to int directly. There's another trick to help this, by assign float as the number original datatype. This is happen when and let's see if we add float as another parser :
x = int(float(input()))
5.5
print(type(x))
<class 'int'>
The solution is simple, just directly parse your input as int, then compare it:
x = int(float(input()))
if x == 5 or x == int(5.5):
#do something
Hope it will help you. Good Luck!
Related
Here is my program :
r = float(input())
for i in range (1,6):
L = r-i
k = L//2
if isinstance(k, int):
print(L, r-L)
else :
print("IDK !")
When i plug in 17/6 this is the error that i get:
Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: could not convert string to float: '17/6'
Thanks for helping me !
First off, you need to reformat your code so that it's readable for other people. But to answer your question, it's because "17/6" comes in as a string value. Converting a string to a float will convert actual numbers into a float. Numbers in Python are represented as decimals, not fractions, so 17/6 is "17 divided by 6" and not "17 over six". You would need to find a way to parse that as an operation to produce a float instead of trying to convert it directly to a float.
EDIT: To clarify, I understand that the fraction 17/6 and the results of dividing 17/6 are mathematically equivalent. That does not mean that python treats them as equivalen representation because fractions are not a native data type. If you print 17/6, it's not showing you a representation of 17/6. It's printing the result of 17.truediv(6).
I don't quite understand what your trying to do but if you want Python to evaluate your input say 17/6 as if you where to have input the result of 17/6 as a float (2.833333333333333) replace
r = float(input())
with
r = float(eval(input()))
eval will evaluate the input string ("17/6") as 17.truediv(6) which is a float and then save that to r
also in my tests the line
if isinstance(k, int):
always evaluates to false as // doesn't change type to int and even if id did it would do so consistently
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 months ago.
My goal is very simple, which makes it all the more irritating that I'm repeatedly failing:
I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is 3, the code would be:
print(*range(1, 3+1), sep="")
which obviously works, however when using an n = input() , no matter where I put the str(), I get the same error:
"Can't convert 'int' object to str implicitly"
I feel sorry to waste your collective time on such an annoyingly trivial task..
My code:
n= input()
print(*range(1, n+1), sep="")
I've also tried list comprehensions (my ultimate goal is to have this all on one line):
[print(*range(1,n+1),sep="") | n = input() ]
I know this is not proper syntax, how on earth am I supposed to word this properly?
This didn't help, ditto this, ditto this, I give up --> ask S.O.
I see no reason why you would use str here, you should use int; the value returned from input is of type str and you need to transform it.
A one-liner could look like this:
print(*range(1, int(input()) + 1), sep=' ')
Where input is wrapped in int to transform the str returned to an int and supply it as an argument to range.
As an addendum, your error here is caused by n + 1 in your range call where n is still an str; Python won't implicitly transform the value held by n to an int and perform the operation; it'll complain:
n = '1'
n + 1
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1
TypeError: Can't convert 'int' object to str implicitly
That's why you need to be explicit and wrap it in int(). Additionally, take note that the one liner will fail with input that can't be transformed to an int, you need to wrap it in a try-except statement to handle that if needed.
In your code, you should just be able to do:
n = int(input())
print(*range(1,n+1),sep="")
But you would also want to have some error checking to ensure that a number is actually entered into the prompt.
A one-liner that works:
print(*range(1, int(input()) + 1), sep="")
I have an issue that really drives me mad. Normally doing int(20.0) would result in 20. So far so good. But:
levels = [int(gex_dict[i]) for i in sorted(gex_dict.keys())]
while gex_dict[i] returns a float, e.g. 20.0, results in:
"invalid literal for int() with base 10: '20.0'"
I am just one step away from munching the last piece of my keyboard.
'20.0' is a string, not a float; you can tell by the single-quotes in the error message. You can get an int out of it by first parsing it with float, then truncating it with int:
>>> int(float('20.0'))
20
(Though maybe you'd want to store floats instead of strings in your dictionary, since that is what you seem to be expecting.)
It looks like the value is a string, not a float. So you need int(float(gex_dict[i]))
It looks like the problem is that gex_dict[i] actually returns a string representation of a float '20.0'. Although int() has the capability to cast from a float to an int, and a string representation of an integer to an int. It does not have the capability to cast from a string representation of a float to an int.
The documentation for int can be found here:
http://docs.python.org/library/functions.html#int
The problem is that you have a string and not a float, see this as comparison:
>>> int(20.0)
20
>>> int('20.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '20.0'
You can workaround this problem by first converting to float and then to int:
>>> int(float('20.0'))
20
So it would be in your case:
levels = [int(float(gex_dict[i])) for i in sorted(gex_dict.keys())]
I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so far:
#! /usr/bin/env python
value = raw_input('Please enter a mass difference:')
fh = open ( "values" );
x = []
for line in fh.readlines():
y = [float for float in line.split()]
x.append(y)
fh.close()
for i in range(0,len(x)-1):
for j in range(i,len(x)):
if x[j][0] - x[i][0] == value:
print x[i][0],x[j][0]
The compiler complains that i am not allowed to substract strings from strings (logically) but my question is ... why are they strings? Shouldn't the nested list be a list of floats as i use float for float?
Literal error:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I would greatly appreciate if someone can tell me where my reasoning goes wrong ;)
Try this in place of your list comprehension:
y = [float(i) for i in line.split()]
Explanation:
The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via float() .. which you tried, but not quite correctly/successfully. This should give you the results you were looking for.
If you have other values to convert, this syntax will work:
float_val = float(string_val)
assuming that string_val contains valid characters for a float, it will convert, otherwise you'll get an exception.
>>> float('3.5')
3.5
>>> float('apple')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): apple
The list comprehension isn't doing what you think it's doing. It's simply assigning each string to the variable float, and returning it. Instead you actually want to use another name and call float on it:
y = [float(x) for x in line.split()]
Error 1: y = [float(x) for x in line.split()] or simply map(float,lines.split())
Error 2: if x[j][0] - x[i][0] == float(value): #you didn't converted value to a float
I have an issue that really drives me mad. Normally doing int(20.0) would result in 20. So far so good. But:
levels = [int(gex_dict[i]) for i in sorted(gex_dict.keys())]
while gex_dict[i] returns a float, e.g. 20.0, results in:
"invalid literal for int() with base 10: '20.0'"
I am just one step away from munching the last piece of my keyboard.
'20.0' is a string, not a float; you can tell by the single-quotes in the error message. You can get an int out of it by first parsing it with float, then truncating it with int:
>>> int(float('20.0'))
20
(Though maybe you'd want to store floats instead of strings in your dictionary, since that is what you seem to be expecting.)
It looks like the value is a string, not a float. So you need int(float(gex_dict[i]))
It looks like the problem is that gex_dict[i] actually returns a string representation of a float '20.0'. Although int() has the capability to cast from a float to an int, and a string representation of an integer to an int. It does not have the capability to cast from a string representation of a float to an int.
The documentation for int can be found here:
http://docs.python.org/library/functions.html#int
The problem is that you have a string and not a float, see this as comparison:
>>> int(20.0)
20
>>> int('20.0')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '20.0'
You can workaround this problem by first converting to float and then to int:
>>> int(float('20.0'))
20
So it would be in your case:
levels = [int(float(gex_dict[i])) for i in sorted(gex_dict.keys())]