This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 2 years ago.
I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,
y = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!
nums=0
i=0
x = int(input())
while x>0:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
This error occurs when you try to input a string of characters, instead of numbers.
E.g:
if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
It is likely the line y = int(input()) is receiving a string from the user input .
See this example.
>>> while True:
... y = int(input())
... print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
Like #Blade said you should give numbers as input. You can do this:
nums=0
i=0
try:
x = int(input())
while x>0:
try:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
except:
print("Input is not a number")
except:
print("Input is not a number")
You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int
For calculating the average of two numbers you can use this simple code instead : -
def average(x, y):
" Returns the average of two numbers "
return (x+y)/2
x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))
Related
This question already has answers here:
How to convert an integer to a string in any base?
(35 answers)
Closed 4 days ago.
Write a program that prompts the user for input of a positive integer n and
converts that integer into each base b between 2 and 16 (using a for loop). I'm halfway there (still have to convert the numbers to letters for bases 10+).
When I run the program, the error pops up. I thought int() took integers as parameters?
n = int(input("Enter a positive number: "))
while n < 0:
n = int(input("Please input a positive number: "))
for x in range(2, 17): #x being the iteration of base numbers
baseConvert = int(n, x)
textString = "{} = {} in base {}".format(n, baseConvert, x)
print(textString)
Traceback (most recent call last):
File "/tmp/sessions/fdb8f9ea1d4915eb/main.py", line 8, in <module>
baseConvert = int(n, base)
TypeError: int() can't convert non-string with explicit base
Credits to https://stackoverflow.com/a/53675480/4954993
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(number, base):
res = "" #Starts with empty string
while number and base>1: #While number is not zero, it means there are still digits to be calculed.
res+=BS[number%base] #Uses the remainder of number divided by base as the index for getting the respective char from constant BS. Attaches the char to the right of string res.
number//= base #Divides number by base and store result as int in var number.
return res[::-1] or "0" #Returns reversed string, or zero if empty.
n=-1
while n < 0:
n = int(input("Please input a positive number: "))
for i in range(2,17):
print("Base", i, "Number", to_base(n,i))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to receive input where there is a newline in Python.
I want to input a number and I have implemented the following code, but I get the following error
Code
string = []
while True:
input_str = int(input(">"))
if input_str == '':
break
else:
string.append(input_str)
Error
ValueError: invalid literal for int() with base 10: ''
line error
>1
>2
>3
>
Traceback (most recent call last):
File "2750.py", line 4, in <module>
input_str = int(input(">"))
ValueError: invalid literal for int() with base 10: ''
try isdigit function of string, see below example:
string = []
while True:
input_str = input(">")
if input_str.isdigit():
input_str = int(input_str)
if input_str == '':
break
else:
string.append(input_str)
I would suggest a try-except approach:
strList = []
while True:
try:
strList.append(int(input('Enter the number > ')))
except ValueError:
print ('Invalid number. Please try again!')
break
print(strList)
OUTPUT:
Enter the number > 1
Enter the number > 2
Enter the number > 3
Enter the number >
Invalid number. Please try again!
[1, 2, 3]
I made a code like this to find the arithmetical mean for numbers the user has typed in but for some reason the program couldn't convert string to float in the end. What should I change?
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if negative not in x:
jnr += 1
elif negative in x:
pass
elif x == "": break
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
I got his Error :
Traceback (most recent call last): File
"C:\Users\siims\Desktop\Koolitööd\individuaalne proge.py", line 11, in
sum = sum + float(x) ValueError: could not convert string to
float
As I said in my comment the error comes from the fact that calling float(x) when the user uses Enter result in the error. The easiest way to fix your code without changing everything is by checking first if the input is "". That way you will not be trying to convert an empty string to float.
print("I'm going to find the arithmetical mean! \n")
jnr = 0;
sum = 0
negative = "-"
while True:
x = input(f"Type in {jnr}. nr. (To end press Enter): ")
if x == "":
break
elif negative not in x:
jnr += 1
sum = sum + float(x)
print("Aritmethmetical mean for these numbers is: "+str(round(sum/(jnr-1), 2)))
You're trying to convert a string to a float but it is an invalid string if you are using the string for that purpose. I would just continue asking until the user gives the right input, like this:
def float_input(s):
while True:
try:
x = input(s)
except ValueError:
print('Invalid input. Try again.')
else:
break
return x
Then, instead of input, use float_input in your code.
An updated version of your code :
print("I'm going to find the arithmetical mean! \n")
jnr = 0; sum = 0
while True:
x = int(input())
if x>1:
jnr += 1
elif x<1:
pass
if x == 0:
break
sum += float(x)
print(sum)
print("Aritmethmetical mean for these numbers is: {}".format(sum/jnr))
output:
I'm going to find the arithmetical mean!
9
9
9
9
9
0
Aritmethmetical mean for these numbers is: 9.0
Pythonic way:
You can find mean by:
print("I'm going to find the arithmetical mean! \n")
inp=[int(i) for i in input().split()]
print(sum(inp)/len(inp))
output:
I'm going to find the arithmetical mean!
9 9 9 9 9
9.0
I have created a program in Python 3.4.1 that;
asks for a whole number,
verifies that it is a whole number,
throws an error message and asks for the number to be re-input if not a whole number,
once the number is verified adds it to a list,
ends if -1 is input.
mylist = []
def checkint(number):
try:
number = int(number)
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
while int(number) != -1:
mylist.append(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
This all works fine, except in one scenario. If a non-whole number is input e.g. p (which gives an error message) followed by -1 to end the program, I get this message:
Traceback (most recent call last):
File "C:/Users/************/Documents/python/ws3q4.py", line 15, in <module>
while int(number) != -1:
ValueError: invalid literal for int() with base 10: 'p'
I don't understand why this is happening, as the input of p should never get as far as
while int(number) != -1:
Here is a minimal example to illustrate the issue:
>>> def change(x):
x = 2
print x
>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside
You need to fix the function to return something, and assign that to number in the outer scope:
def checkint(number):
try:
return int(number) # return in base case
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
return checkint(number) # and recursive case
number = input("Enter a whole number. Input -1 to end: ")
number = checkint(number) # assign result back to number
Also, it is better to do this iteratively rather than recursively - see e.g. Asking the user for input until they give a valid response.
I made a program where the user enters a number, and the program would count up to that number and display how much time it took. However, whenever I enter letters or decimals (i.e. 0.5), I would get a error. Here is the full error message:
Traceback (most recent call last):
File "C:\Documents and Settings\Username\Desktop\test6.py", line 5, in <module>
z = int(z)
ValueError: invalid literal for int() with base 10: 'df'
What can I do to fix this?
Here is the full code:
import time
x = 0
print("This program will count up to a number you choose.")
z = input("Enter a number.\n")
z = int(z)
start_time = time.time()
while x < z:
x = x + 1
print(x)
end_time = time.time()
diff = end_time - start_time
print("That took",(diff),"seconds.")
Please help!
Well, there really a way to 'fix' this, it is behaving as expected -- you can't case a letter to an int, that doesn't really make sense. Your best bet (and this is a pythonic way of doing things), is to simply write a function with a try... except block:
def get_user_number():
i = input("Enter a number.\n")
try:
# This will return the equivalent of calling 'int' directly, but it
# will also allow for floats.
return int(float(i))
except ValueError:
#Tell the user that something went wrong
print("I didn't recognize {0} as a number".format(i))
#recursion until you get a real number
return get_user_number()
You would then replace these lines:
z = input("Enter a number.\n")
z = int(z)
with
z = get_user_number()
Try checking
if string.isdigit(z):
And then executing the rest of the code if it is a digit.
Because you count up in intervals of one, staying with int() should be good, as you don't need a decimal.
EDIT: If you'd like to catch an exception instead as wooble suggests below, here's the code for that:
try:
int(z)
do something
except ValueError:
do something else