Cannot convert input as fraction string to float - python

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

Related

In Python, how can I get a whole number without decimals from math.sqrt?

import math
a = math.sqrt(25)
print(a)
My output is 5.0, how can I get a 5 (whole number) instead?
You have to check and explicitly convert to integer:
if x == (y := int(x)):
x = y
Or, without the assignment operator:
if x == int(x):
x = int(x)
As of python 3.8, you can use math.isqrt:
math.isqrt(25)
Keep in mind that this will always return an integer, even if the input is not a perfect square.
In a reduced manner, you can use a 1 line if operator to assign an integer value to the result of sqrt if both integer and decimal values are the same:
import math
a = math.sqrt(25)
a = int(a) if int(a)==a else a
print(a)
It depends a little on what exact behavior you want: do you want to just print the number without the decimal, or do you want to round a number to an integer?
For the print statement, Python tries to convert whatever is passed to it to a String in order to print it, and by default it gives floating point numbers decimal places. To stop that, we can use string formatting:
print("{:.0f}".format(a))
What this is doing is making a string (the double quotes "") that contains a special format marker (the curly braces {}). Inside the format marker is the code for the desired behavior (0 decimal places on a floating point number). Then we call the .format method of the string and pass the value (a) we want to be used inside the special format marker.
This looks somewhat arcane and ugly, but is the safest method to print what you want because it does not change 'a' and is easily customizable to other printing behaviors.
For rounding a number and converting it to an int, you can either use int() or round(): both will take in a float and output an integer that will print cleanly (and be an integer for future computation). There is no requirement for the thing being converted to actually be an integer but there is different behavior for the two functions: int returns the value of the first digit of a number, while round returns the rounded value (IE round(1.9) -> 2, int(1.9) -> 1, etc).

formatting very large numbers in python 3

I am performing calculation in python that results in very large numbers. The smallest of them is 2^10^6, this number is extremely long so I attempted to use format() to convert it to scientific notation. I keep getting an error message stating that the number is too large to convert to a float.
this is the error I keep getting:
print(format(2**10**6, "E"))
OverflowError: int too large to convert to float
I would like to print the result of 2^10^6 in a way that is concise and readable
You calculated 2 raised to the 10th then raised to the 6th power. If your aim is "2 times 10 to the sixth", then 2*10**6 is what you want. In python that can also be expressed by 2E6 where E means "to the 10th power". This is confusing when you are thinking in terms of natural logs and Euler's Number e.
You can also use the decimal.Decimal package if you want to side step decimal to binary float problems. In python, floats expressed in decimal are rounded to the nearest binary float. If you really did want the huge number, Decimal can handle it.
>>> Decimal("2E6")
Decimal('2E+6')
>>> Decimal("2")*10**6
Decimal('2000000')
>>> Decimal("2")**10**6
Decimal('9.900656229295898250697923616E+301029')
For printing, use the "g" format
>>> d = Decimal('2')**10**6
>>> format(d,'g')
'9.900656229295898250697923616e+301029'
>>> format(d,'.6g')
'9.90066e+301029'
>>> "{:g}".format(d)
'9.900656229295898250697923616e+301029'
>>> "{:.6g}".format(d)
'9.90066e+301029'

Why does the following evaluate to a ValueError in python?

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!

Convert value in a Python dictionary to an int [duplicate]

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

python float to in int conversion

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

Categories

Resources