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

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)

Related

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!

Converting decimal numbers to binary with functions in python

I have to create a program to convert decimal numbers to binary for my class but im lost. These are the directions.
3 Files must be used
user_input.py
Obtain an integer from the user between 0-255.
No conversion or print statements allowed in the user_input.py
Obtaining the integer must be done in a function
No import statements allowed
conversion.py
Convert the number provided to a binary number (e.g., 254 provided and converted to 11111110)
No print statements, input statements, or built in functions to convert a number to binary. Conversion must be done manually.
Small hint, concatenating the 1s and 0s is going to be tough b/c python will want to add the numbers (e.g., 1+1 = 2 vs 1+1 = 11). So, how are you going to handle this issue?
The conversion must be done in a function
No import statements allowed
main.py
Print the eight bit binary representation (00000000 - 11111111) of the number provided and converted. To do so, you will have to access the necessary functions in conversion.py and user_input.py
Note - the program is only allowed to access functions. No direct access to variables allowed.
No input or conversions allowed in main.py
Note - the binary print must only be the eight binary numbers. No commas, brackets etc. - ['1', '0', '0', ...] or [1,1,0,0,1..] are not allowed.
to make the function to get the inputted number I use
def number ():
num =int(input('Pick a number from 0 - 255'))
return num
number()
After that when I do not know how I would access it without importing it.
This is the code I'm using to convert
def conversion(num):
cnv_bin = ''
num = ''
while num // 2 > 0:
if num % 2 == 0:
cnv_bin += '0'
else:
cnv_bin += '1'
num = num // 2
return cnv_bin
In the last file I tried
import conversion
import user_input
print(conversion.conversion(user_input.number()))
and that gave me this error
Traceback (most recent call last):
File "C:/Users/adkir/PycharmProjects/lab_23/main.py", line 4, in <module>
print(conversion.conversion(user_input.number()))
File "C:\Users\adkir\PycharmProjects\lab_23\conversion.py", line 5, in
conversion
while num // 2 > 0:
TypeError: unsupported operand type(s) for //: 'str' and 'int'
So basically im lost. Can anyone point me in the right direction so I can figure this out?
Your conversion function takes num as a parameter and yet it overwrites num's value by assigning an empty string to it.
Remove the line:
num = ''
and it should work.

value error in my code (python 3.0) 'chr() arg not in range'

I have to take in a string and an integer value and check if the string is lowercase or uppercase, and based on that I have to increment it by number k. for eg if k=4 and string is 'ABab' it should give the output 'EFef'.
This is my code only for checking lowercase. Unfortunately is giving ValueError.
s=input()
k=int(input())
l=[]
for i in s:
if i.islower():
if 97>=(ord(i)+k)<=122:
l.append(chr(ord(i)+k))
else:
k=k-122
if 97>=(ord(i)+k)<=122:
l.append((chr(ord(i)+k)))
break
else:
continue
print(l)
The traceback shows where the error occurs.
Traceback (most recent call last):
File "C:/Users/rob/test.py", line 11, in <module>
l.append((chr(ord(i)+k)))
ValueError: chr() arg not in range(0x110000)
You are passing an argument to chr that is not within the allowed range. As described here:
The valid range for the argument is from 0 through 1,114,111 (0x10FFFF
in base 16). ValueError will be raised if i is outside that range.
This is because you have changed the value of k to (probably) be a large negative number:
k=k-122
So the result of ord(i)+k is also often negative. Negative numbers are not in the allowed range, so the call to chr fails.
There are lots of other problems with your code, and I don't think you'd learn much if I just wrote "my solution" to the problem. Another thing you might want to look at to begin with is that:
if 97>=(ord(i)+k)<=122:
doesn't do what you want, you probably want:
if 97<=(ord(i)+k)<=122:

Grok Learning: Halve this TypeError [duplicate]

This question already has answers here:
How can I concatenate str and int objects?
(1 answer)
String formatting: % vs. .format vs. f-string literal
(16 answers)
Closed 7 months ago.
I have to write a program that reads in a whole number and prints out that number divided by two. This is my code:
a= int(input("Number: "))
h= a/2
print("Half number: " + h)
But I keep getting this
Number: 6
Traceback (most recent call last):
File "program.py", line 3, in <module>
print("Half number: " + h)
TypeError: Can't convert 'float' object to str implicitly
I don't see anything wrong with my code and I have no idea what the error is. Any idea what's wrong?
The expression:
"Half number: " + h
is trying to add a string to a float. You can add strings to strings:
"This string" + ", then this string"
and floats to floats:
100.0 + 16.8
but Python isn't willing to let you add strings and floats. (In the error message above, Python has processed the first string and the addition, and it now expects a string -- that's why you get the error that it can't -- or at least won't -- convert a 'float' number to a string.)
You can tell Python this is what you really want it to do in a few ways. One is to use the built-in str() function which converts any object to some reasonable string representation, ready to be added to another string:
h = 100
"You can add a string to this: " + str(h)
a= int(input("Number: "))
h= a/2
print('Half number:', h)
Without the spaces in between though
Here is a very simple way to do it.
Here's a sample solution from Grok Learning:
n = int(input('Number: '))
print('Half number:', n/2)
Here's my explanation below:
As you might've already guessed, n here is a variable. And in this code, we will be assigning some information to n. int(input('Number ')) is the statement that Python will then read, and follow. int() tells Python that the input will be an integer, and input() allows the user to input whatever they would like to input. n/2 is simply another way of saying "n divided by two". print() tells Python to print a statement, and so print('Half number:', n/2) will print out that "Half number" is simply just half of the number entered above.
Here's an example of what the output should look like:
Number: 6
Half number: 3
(In that example, the input was 6.)
So, yes, I know that you may already know this stuff but I am leaving this information for people who may visit this website in the future. The error that you had was that you used a +, when you should've used a ,. Python is pretty strict when it comes to processing what you're saying, so it didn't allow you to put a str and an int together using a +. So next time, remember to use a ,.
I hope this helps you.

Print function input into int [duplicate]

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="")

Categories

Resources