Strange error in python 3.2 - python

The following code is to find the mean of a given input set of numbers.
#!/usr/bin/env python3
print("Enter some integers")
count = 0
total = 0
while True:
line = input("integer: ")
if (line):
try:
number = int(line)
except ValueError as err:
print(err)
continue
total += number
count += 1
#print("Post",line)
else:
break
if count:
print('Count is ',count ,'Total is ',total,'Mean is ',total/count)
However, whenever I run the program, the even numbered input gives me an error even though I enter a number. The following is the sample output.
Enter some integers
integer: 4
integer: 5
invalid literal for int() with base 10: 'integer: 5'
integer: 5
integer: 6
invalid literal for int() with base 10: 'integer: 6'
integer:
Count is 2 Total is 9 Mean is 4.5
However, this code works fine if I uncomment the line before the else: statement. Can anyone tell me what is going on here?
Thanks in advance.

Your problem is a question of cut and paste.
The line
number = int(line)
Generates the error
invalid literal for int() with base 10: 'integer: 6'
This means that the line
line = input("integer: ")
Must have recieved the input:
'integer: 6'
And the only way it could have recieved this, is if that is what you inputted.
Obviously, you would not be so daft as to type in "integer: 6". Hence the only reason this happens is that you have cut and pasted your previous input without noticing that you got to much when you copied, which is something that happens to me all the time.

Related

How to exit loop when input is nothing

I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.

What am I doing wrong on this Python coding, when it shows the ValueError: invalid literal for int() with base 10: '-2.5'?

I'm getting this error. What am I doing wrong? Thank you.
num = input('Enter positive integer: ')
try:
print(int(num))
except:
print('Error: You did not enter a positive integer')
else: # else is executed if no errors were raised
print('Integer input accepted')
finally: # always executes at the end of the try-except block
print('the try block is completed')
if int(num) > 1:
for i in range(2,int(num)):
# for loop is used, iterate from 2 to n / 2
# nested if statement is used to see it's a prime or not:
if (int(num)% i)== 0:
print('It is a composite')
break
else:
print('It is a prime')
break
elif (int(num) ==0 or int(num) ==1):
print('It is neither prime nor composite')
ValueError Traceback (most recent call last)
<ipython-input-46-049b0b9078db> in <module>
11
12
---> 13 if int(num) > 1:
14 for i in range(2,int(num)):
15
ValueError: invalid literal for int() with base 10: '-2.5'
This is actually an interesting point.
Python can parse the string '-2.5' as a float, but not as an int, despite it knowing what to do with int(-2.5), which simply returns the int -2.
If you want to only consider the int part of a float represented as a string, you'll have to first parse the string as a float, then parse the float as an int, like so:
if int(float(num)) > 1:
for i in range(2,int(num)):
...
However, what you may want to do is actually compare the float number and check whether it's greater than 1. In that case you'd simply have to cast the string as float and compare, like so:
if float(num) > 1:
for i in range(2,int(num)):
...

Missing parentheses in call to 'print'

A small game that guesses numbers, but there are the following errors in pycharm, opening with IDLE is no problem. May I ask what is the reason?
#guess number
import random #use import function convert random module
num = random.randint(0,11) #create random int
temp = input ('Please type you guess number: ') #type random str
guess = int (temp) #temp convert to int, if the str is decimal could use int(float(temp)) transfer
while guess != num: #while loop
print ("Sorry! You are wrong.")
temp = input ('Please type the number again: ')
guess = int (temp)
if guess == num:
print ('Amazing!')
else:
if guess > num:
print ("The number is high.")
else :
print ('The number is low.')
print ('Congragulation!')
D:\Anaconda\python.exe "C:/Users/Sky Talk/PycharmProjects/untitled/Key"
File "C:/Users/Sky Talk/PycharmProjects/untitled/Key", line 7
print "dict['name']:",dict['name']
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("dict['name']:",dict['name'])?
Process finished with exit code 1
code screenshot
error message
terminal screenshot
Print(words) is a command that accepts parameters. When you use the print function, you have to use the parenthesis, or you will get an error. Use the suggestion that the error message gave you:
print("dict['name']:",dict['name'])

python - inputting numbers that start with 0

I'm making a program in python. It is suppose to take in a GTIN number and put in a list and then check if it's valid. The program works, but as soon as I enter a GTIN number that starts with a 0, I get a "invalid token (, line 1)" error. I really need a solution because some products have their GTIN numbers starting with a 0.
when I input a number for example:
96080832
The program works great.
When i put in a number like:
00256986
I get an error:
invalid token (<string>, line 1)
pointing to this line:
inputtedInt = int(input("Enter the gtin number: "))
Whole def:
def chooseOption(inputInt):
while(inputInt > 0 and inputInt < 4):
if(inputInt == 1):
print("you picked option number 1")
showOptions()
break
elif(inputInt == 2):
print(" ")
inputtedInt = int(input("Enter the gtin number: "))
gtin = map(int,str(inputtedInt))
checkValidity(gtin, 2)
print(" ")
showOptions()
break
elif(inputInt == 3):
print("you picked option number 3")
showOptions()
break
else:
option = int(input("Error - enter a number from 1 to 3. : "))
chooseOption(option)
Thanks in advance.
You seem to be using Python 2. In Python 2, input tries to evaluate the input string as a Python expression, and a leading 0 on a numeric literal in Python 2 syntax means that the number is in octal, or base 8. Since 8 and 9 are not valid digits in base 8, this input constitutes a syntax error.
If you were supposed to be using Python 3, get on Python 3. If you're supposed to be on Python 2, use raw_input instead of input.
Additionally, if you care about preserving things like leading zeros, you should keep the input as a string and only call int on it when you want to do math on it as an integer.
Error is raised because you are mapping str ant/to int in line:
gtin = map(int,str(inputtedInt))
for example if you ty to run:
a = 005
You will get following error:
File "<stdin>", line 1
a = 005
^
SyntaxError: invalid token
Sollution -> you should use stringsfor GTIN number :)

ValueError: invalid literal for int() with base 10 -- how to guard against invalid user input?

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

Categories

Resources