I'm trying to assign a new value to a key in a dictionary. But getting "ValueError: invalid literal for int() with base 10:"
Here is what I do.
balance = {'beer':5, 'toast':2}
item = input("what did you eat?: ")
price = input("how much?: ")
if item not in balance:
balance[item] = int(price)
else:
balance[item] = balance[item] + int(price)
I'm puzzled, since I can do balance['beer'] = 5 in python shell, what am I missing?
Read the error message again:
ValueError: invalid literal for int() with base 10
This means, that you are passing an invalid argument to function int(), i.e. a string that does not represent a valid decimal number.
Check what price name holds. As it's taken from the user, your program must be prepared to handle a situation when it's garbage. I usually make a function to handle the boilerplate:
def input_int(prompt):
while True:
data = input(prompt)
try:
return int(data)
except ValueError:
print("That's not a valid number. Try again.")
You can also add some escape condition if it makes sense in your program.
what is the value of price
it is probably a string?
having a value that cannot be converted to an int will cause this
>>> test = 'test'
>>> int(test)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'test'
also please make sure to post your complete traceback as python gives it to you in your question, not just the error string
This is a great opportunity to learn about data validation, as you can see your program requires an integer. You can handle this yourself, displaying your own message to the user, or allow the program to just error (assuming the client of your program will understand the error)
There are no shortcuts to data validation
try:
price = int(input("how much?: "))
catch ValueError:
print('Please enter an integer')
or something to that effect
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm writing a basic program which is to create a team based on age groups. So I want to create a team, but for example for the first team they have to be between the age of 20 and 25:
while True:
if(num<20):
num = int(input("Too young, try again!: "))
elif(num>25):
num = int(input("Too old, try again!: "))
I also want to display a message in the if statement if the user enters text rather than an integer, for example:
elif(num is not int):
num = int(input("Please enter integers(numbers)only!: ")
I'm new to Python so sorry if the example is poor.
You're looking for try/except Exception Handling
try:
value = int(input(...))
except ValueError:
# handle Exception
this works because int() raises ValueError on non-int inputs
>>> int("not an integer")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not an integer'
>>> int("5")
5
would recomend try or except
try:
value = int(input(...))
execpt:
print("intiger please")
A friend of mine is studying Python and gets this error
name = int(input('Type str: '))
if name >= 0:
print('Typed name is wrong')
elif name <= 0:
print('Typed name is wrong')
else:
name1 = str(input('Type your name: '))
print('Your name is: ' + name1)
Of course, I don't understand Python, but when he enters a number, everything works fine, but when he feeds on entering a string value, he gets an error, how can this problem be solved?
So when you use the input() function you read input in string form. When you use int(input()) your string input is typecasted to integer form. If you input anything that can't be typecasted to an integer you'll get an error.
For example: If your input is "3" then it'll be typecasted to 3 and if you input "your name" it can't be typecasted, hence it'll throw an error.
That's why you didn't get any error when you were typing a number because the typecasting was successful.
It'll be helpful if you could elaborate what output you want.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
def mainloop():
inp = input("Which cipher would you like to use?\n[A]a1z26\n[B]Atbash\n[C]Caesar\n[D]ROT13\n>")
elif inp.lower() == 'c':
inp = input("Would you like to decipher or encipher a text?\n>")
while inp.lower() not in ('decipher', 'encipher'):
inp = input("Please enter either 'decipher' or 'encipher'.\n>")
if inp.lower() == 'decipher':
inp1 = input("What text would you like to decipher?\n>")
while True:
try:
inp2 = int(inp2)
except ValueError:
inp2 = int(input("Please enter a valid number.\n>"))
dec_caesar(inp1, inp2)
So the code by itself works and edge cases have already been implemented in my code but I made it shorter so it is easier to read. Essentially what I want is to have inp2 be a number of shift for the cipher, eg if inp2 == 1 and the letter is a it would shift by 1 to become b, and I've already coded this. The problem is handling the case when inp2 cannot be an integer. By default an input is a string so I use int(input) and the except ValueError works the first time, but if i type a string again, it will just Raise a ValueError instead of running the except ValueError. How can I make it so it would keep asking to enter a valid number until int(input) is valid?
the above code produces the error:
Traceback (most recent call last):
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 97, in mainloop
inp2 = int(inp2)
ValueError: invalid literal for int() with base 10: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 105, in <module>
mainloop()
File "C:/Users/justin/Documents/PycharmProjects/cipher.py", line 99, in mainloop
inp2 = int(input("Please enter a valid number.\n>"))
ValueError: invalid literal for int() with base 10: 'a'
You have two problems you can address here.
You are running a while loop over while True which will always run unless you call break
You are running your "check" in the except clause, which does not have a try except block of its own.
We can set inp2 to None earlier in the code and use our while loop to monitor the status of the variable.
Then we only need to check if the value is an integer during our try clause, and when a successful response is entered, the loop will terminate.
def mainloop():
inp2 = None
while inp2 == None:
try:
inp2 = int(input("How much would you like to shift the text by?\n>"))
except ValueError:
print("You can only enter integer values!")
continue
When run, this is your result. Note the error is due to you not having the function defition in your posts code, this should work fine when run in your environment.
Would you like to decipher or encipher a text?
>decipher
How much would you like to shift the text by?
>a
How much would you like to shift the text by?
>f
How much would you like to shift the text by?
>a
How much would you like to shift the text by?
>e
How much would you like to shift the text by?
>2
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
mainloop()
File "<pyshell#39>", line 15, in mainloop
dec_caesar(inp, inp2)
NameError: name 'dec_caesar' is not defined
I'm trying to write a program to calculate densities, and I have tried to create a while loop the prevents the user from entering nothing or a non-number for the volume.
But when I run the program the it just loops "You have to type a value" forever. I've tried the same code in a for loop and it does work after inputing 2 numbers.
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while Volume == ("") or type(Volume) != int:
print("You have to type a value")
Volume = input()
return float(Volume)
This solution is written assuming you are using Python 3. The problem in your code is that you are assuming that if you type in a number, the input method will return a type int. This is incorrect. You will always get a string back from your input.
Furthermore, if you try to cast int around your input to force an int, your code will raise if you enter a string, with:
ValueError: invalid literal for int() with base 10:
So, what I suggest you do to make your implementation easier is to make use of try/exceptinstead to attempt to convert your value to a float. If it does not work, you prompt the user to keep entering a value until they do. Then you simply break your loop and return your number, type casted to a float.
Furthermore, because of the use of the try/except, you no longer need to put in a conditional check in your while loop. You simply can set your loop to while True and then break once you have satisfied your condition in your code.
Observe the code below re-written with what I mentioned above:
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume
def GetVolume():
Volume = input("How many cublic cm of water does the item displace")
while not Volume.replace('.', '').replace(',', '').isdigit():
Volume = input("You have to type a value")
return float(Volume)
x = GetVolume()
print(x)
You have to modify your while because is validating that is str or different than int. An input will always be an str by default unless you modified the type with int() or float() in your case.
You can use 'try' instead to check for this:
while True:
x = input("How many cubic cm of water does the item displace")
try:
x = float(x)
break
except ValueError:
pass
print('out of loop')
I am very new to Python (started 2 days ago). I was trying to validate positive integers. The code does validate the numbers but it asks twice after a wrong input is entered. For example if I enter the word Python, it says: This is not an integer! like is supposed to but if I enter 20 afterwards, it also says it is not an integer and if I enter 20 again it reads it.
def is_positive_integer(input):
#error: when a non-integer is input and then an integer is input it takes two tries to read the integer
flag = 0
while flag != 1:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
input = raw_input("Enter the number again:")
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
if isinstance(input, int):
flag = 1
return input
number = raw_input("Enter the number to be expanded: ")
is_positive_integer(number)
number = int(is_positive_integer(number))
Any help is appreciated.
The main bug is that you call is_positive_integer(number) twice with the same input (the first thing you enter).
The first time you call is_positive_integer(number), you throw away the return value. Only the second time do you assign the result to number.
You can "fix" your program by removing the line with just is_positive_integer(number) on its own.
However, your code is a little messy, and the name is_positive_integer does not describe what the function actually does.
I would refactor a little like this:
def input_positive_integer(prompt):
input = raw_input(prompt)
while True:
try:
input = int(input)
if input <= 0:
print "This is not a positive integer!"
else:
return input
except ValueError:
print "This is not an integer!"
input = raw_input("Enter the number again: ")
number = input_positive_integer("Enter the number to be expanded: ")
The problem stems from the fact that you're calling is_positive_integer twice. So, the first time it's called, you send it a string like 'hello', then it says it's not an integer and tells you to try again. Then you enter '20', which parses fine, and it's returned.
But then you don't save a reference to that, so it goes nowhere.
Then you call the function again, this time saving a reference to it, and it first tries the original bad string, which was still there in number. Then it complains that it's a bad input, asks you for a new one, and you provide it, terminating the program.