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 :)
Related
I have to create a fortune teller for school. I want the user to input a number between 1-9. But i also want to give an error message if they put in a different number. I'm using a set containing my numbers, but I can't call it in my if statements.
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! Choose a number from 1 to 9 and hit enter: ')
print()
if user_num == fortune_num:
print(user_num)
else:
print('Error')
Use the keyword in to check set membership, also cast input into int:
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune!
\nChoose a number from 1 to 9 and hit enter: ')
print()
if int(user_num) in fortune_num: #this would throw an error if input is not int
print(user_num)
else:
print('Error')
You can use this code,
fortune_num = list(range(1,10))
user_num = input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: ')
if int(user_num) in fortune_num:
print(user_num)
else:
raise ValueError("You entered a wrong input!")
This would raise an actual Python error if the input is wrong.
If you want to give the user another chances to enter a correct input use this,
fortune_num = list(range(1,10))
while True:
try:
user_num = int(input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: '))
if user_num in fortune_num:
print(user_num)
break
else:
raise ValueError
except:
print("\nYou entered a wrong input. Please enter a valid number!")
Change the code as per your needs but this would do work as the perfect foundation.
First of all, input takes user input as a string. So even if they enter 1, that won't match your set, because your set is of int, and their input is the string '1', not the integer 1. Also, there's no need to use a set. A range object is easier to generate, and since it contains multiple numbers, the variable name should be plural. You also don't have your indentation correct. I don't see what the f in the input function is doing, and if you want a multi-line string, you need triple quotes. Also, if you have a carriage return in your string, putting \n in the string gives you two line breaks; I'm not sure that's intended. So one way of doing this is:
fortune_nums = [str(num) for num in range(1,10)]
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
if user_num in fortune_nums:
print(user_num)
else:
print('Error')
If you want to get fancier, you can keep your fortune_nums as int, then do a try-except on converting the input to int, catching the invalid literal error:
fortune_nums = range(1,10)
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
try:
if(int(user_num) in fortune_nums):
print(user_num)
except ValueError:
print("That's not a valid integer!")
if user_num == fortune_num: // instead of this; you can use keyword in int(user_num) in fortune_num:,
Also your print statement must be indented, otherwise you might get indentation error.
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.
I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")
I trying to learn to write in Python and am attempting to making a calculator. For this I am using an input to choose which type of calculation and then inputs for the numbers to be calculated.
print ("1. add ; 2. subtract ; 3. multiply ; 4. divide " )
print ("wat is your choise")
choise = input()
if choise == 1 :
num_1_1 = input()
num_2_1 = input()
anwsr_add = (num_1_1 + num_2_1)
print (anwsr_add)
and repetition for the rest of the options.
This however returns that anwsr_add can't be printed because it is not defined. It leads me to believe the second inputs are not valid, giving nothing equal to anwsr_add.
Is there a extra code for these input functions within an if stream or am I completely of track with this approach?
This depends on what version of python you are using.
If you are using python 3, then input() is returns a type of 'str', which leads to your error. To test this theory, try print(type(choice)) and see what type it returns. If it returns str, then there is your culprit. If not, get back to us so we can continue to debug. I've posted my approach to your problem below in python 3 just so you have a reference in case I am unable to reply. Please feel free to ignore it if you would like to write it all on your own.
choice = int(input('Enter 1 to add, 2 to subtract, 3 to multiply, 4 to divide\n'))
if 1 <= choice <= 4:
num1 = int(input('What is the first number? '))
num2 = int(input('What is the second number? '))
if choice == 1:
answer = num1 + num2
elif choice == 2:
answer = num1 - num2
elif choice == 3:
answer = num1 * num2
elif choice == 4:
# In python 3, the answer here would be a float.
# In python2, it would be a truncated integer.
answer = num1 / num2
else:
print('This is not a valid operation, goodbye')
print('Your answer is: ', answer)
The main issue I found is you are comparing a char data type to an int data type. When you ask for input from the user, it is stored as a character string by default. Character strings cannot be compared to integers, which is what you are trying to do with your if block. If you wrap the input in an int() call it will convert the char to an int data type, and can then be properly compared with your == 1 statement. Additionally, within your if statement you call input() twice, and it will also give you a character string. This means if you input 1 and 1, you will get 11 out (like a + b = ab). To fix this, also wrap those input() statements with int() calls. I fixed these problems in the code below:
choice = int(input())
if choice == 1:
num_1_1 = int(input())
num_2_1 = int(input())
anwsr_add = (num_1_1 + num_2_1)
print(anwsr_add)
Hey Dalek I've copied your code and got this result:
1. add ; 2. subtract ; 3. multiply ; 4. divide
What's your choise?
1
Traceback (most recent call last):
File "C:\Users\timur\AppData\Local\Programs\Python\Python36-32\Game.py", line 10, in <module>
print (anwsr_add)
NameError: name 'anwsr_add' is not defined
The NameError occurs because the programm trys to call anwsr_add while it executes the code below if choise == ...
You can use this code. It works. The reason why your code doesn't works is that you call anwr_add not in the if choise == ... method:
choise = input("1. add ; 2. subtract ; 3. multiply ; 4. divide. What's your choise?")
if str(choise) == '1':
print('First_num:')
num_1_1 = input()
print('Second_num:')
num_2_1 = input()
anwsr_add = (int(num_1_1) + int(num_2_1))
print (anwsr_add)
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.