ValueError: invalid literal for int() with base 10: '0.294' - python

I want to generate a random int and then use time.sleep().
I want it to generate something like 0.123 randomly.
Here is my code:
s = f"0.{str(random.randint(111, 333))}"
s = int(s)
time.sleep(s)
I am getting the error:
time.sleep(s)
ValueError: invalid literal for int() with base 10: '0.198'
I tried a lot of things, different ways of formatting it etc. No luck

You're trying to convert a floating point number (0.xxx) to an int.
What you need to do is convert it to a float instead:
s = float(s)

Related

why I get error when using int() function to convert float to integer?

Why do I get an error When I tried to use int() function to convert a float to integer?
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'
I expected the result to be 99
Your argument isn't a float, it's a string containing the representation of a float. You have to convert it to a float first, then you can convert that to an int.
int(float('99.99'))
Per the docs
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given. If x is a number, return
x.int(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string,
bytes, or bytearray instance representing an integer literal in radix
base.
Pay particular attention to "representing an integer literal". So your str that you are attempting to convert cannot be a float, because that's a float literal, not an int literal.
So, as others have noted, you cannot go directly from a float literal to an int, you need to convert the float first:
x = '123.45'
int(float(x))
You are getting a ValueError because you are overloading int() with an argument that is not consistent with the Python docs.
According to the doc:
"If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal "
Basically, x (in your case '99.99') is the string 99.99 which does not satisfy the requirements of being an integer literal. You provided a floating literal.
TL;DR
int(float('99.99'))

Use int to convert decimal to bianary

I want to convert number 168 to binary using int,
It report error
In [11]: int(168, base=2)
----> 1 int(168, base=2)
TypeError: int() can't convert non-string with explicit base
I read the doc and tried alternativly
In [13]: int("168", base=2)
ValueError: invalid literal for int() with base 2: '168'
I learned that bin could get the job done
In [16]: bin(168)
Out[16]: '0b10101000'
How could I use int to do it?
The purpose of int with base=2 is to convert a string value in a given base (binary for base=2) to integer and not vice versa to convert into binary what you are trying to do.
From the docs
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base.
You can only use int() to convert things to an integer, the simplest way of converting from number to binary is the function bin(). Just so you know, int() can also convert binary to an integer.

ValueError: invalid literal for int () with base 10 [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed last month.
I wrote a program to solve y = a^x and then project it on a graph. The problem is that whenever a < 1 I get the error:
ValueError: invalid literal for int () with base 10.
Any suggestions?
Here's the traceback:
Traceback (most recent call last):
File "C:\Users\kasutaja\Desktop\EksponentfunktsioonTEST - koopia.py", line 13, in <module>
if int(a) < 0:
ValueError: invalid literal for int() with base 10: '0.3'
The problem arises every time I put a number that is smaller than one, but larger than 0. For this example it was 0.3 .
This is my code:
# y = a^x
import time
import math
import sys
import os
import subprocess
import matplotlib.pyplot as plt
print ("y = a^x")
print ("")
a = input ("Enter 'a' ")
print ("")
if int(a) < 0:
print ("'a' is negative, no solution")
elif int(a) == 1:
print ("'a' is equal with 1, no solution")
else:
fig = plt.figure ()
x = [-2,-1.75,-1.5,-1.25,-1,-0.75,-0.5,-0.25,0,0.25,0.5,0.75,1,1.25,1.5,1.75,2]
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
ax = fig.add_subplot(1,1,1)
ax.set_title('y = a**x')
ax.plot(x,y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.spines['left'].set_smart_bounds(True)
ax.spines['bottom'].set_smart_bounds(True)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.savefig("graph.png")
subprocess.Popen('explorer "C:\\Users\\kasutaja\\desktop\\graph.png"')
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
if __name__ == "__main__":
answer = input("Restart program? ")
if answer.strip() in "YES yes Yes y Y".split():
restart_program()
else:
os.remove("C:\\Users\\kasutaja\\desktop\\graph.png")
Answer:
Your traceback is telling you that int() takes integers, you are trying to give a decimal, so you need to use float():
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (ℤ), and floating point numbers, which store real numbers (ℝ). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Previous guess at answer before we had the traceback:
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the - and 1 will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
Advice on code style:
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a) a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x, you don't need to do anything to y, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.
As Lattyware said, there is a difference between Python2 & Python3 that leads to this error:
With Python2, int(str(5/2)) gives you 2.
With Python3, the same gives you: ValueError: invalid literal for int() with base 10: '2.5'
If you need to convert some string that could contain float instead of int, you should always use the following ugly formula:
int(float(myStr))
As float('3.0') and float('3') give you 3.0, but int('3.0') gives you the error.
It might be better to validate a right when it is input.
try:
a = int(input("Enter 'a' "))
except ValueError:
print('PLease input a valid integer')
This either casts a to an int so you can be assured that it is an integer for all later uses or it handles the exception and alerts the user
int() casting can't handle string numbers that have decimal points
- example --> int('13.5') will give you error , but int('13') will convert the
string to integer
Why : This considered as explicit casting required by the user as it prevents you from losing information like 0.5 if you read dataset and don't know it's had floating-point numbers
Work Around >
int(Float("13.5"))
A real-world example I faced: where I wanted the numbers as int while int(I["mpg"]) directly didn't work so I used float() then int()
sum([int(float(i["mpg"])) for i in file])//len(file)

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

Converting string to integer with python

When trying to convert a string into integer to be used as a variable later in the code, I get the following:
print int(urlsuccessful[i])
ValueError: invalid literal for int() with base 10: '2,919,247'
locale.atoi() will "demark" integers based on the current locale setting.
If only problems are commas, try:
>>> int("2,919,247".replace(",", ""))
2919247
int does not understand commas, you'll want to remove those before trying to convert
You can just do
def int2str(my_integer):
return "%d" % my_integer

Categories

Resources