My code supposed to ask for a 7 digit number (GTIN 8) and tell you the 8th digit and/or ask you for an 8 digit (GTIN 8) number and tell whether it's a valid GTIN 8 number. I am not getting these outputs though.
ERROR message when I type in a not 7 digit number
c = int(GTIN[2])*3
IndexError: string index out of range
ERROR message when I type in an 8 digit number
if len(str(GTIN))==8 and sum(total)%10==0:
TypeError: 'int' object is not iterable
What do I need to do to my code to fix this error?
Thanks. This is my code (I can clarify anything you aren't sure about):
while 2>1:
GTIN = input("Enter 7 digit number for check-digit. Enter 8 digit number for validity.")
if GTIN.isdigit()==False:
continue
a = int(GTIN[0])*3
b = int(GTIN[1])*1
c = int(GTIN[2])*3
d = int(GTIN[3])*1
e = int(GTIN[4])*3
f = int(GTIN[5])*1
g = int(GTIN[6])*3
total = (a+b+c+d+e+f+g)
checkdigit = (total + 9) // 10 * 10 - total
if len(GTIN) == 7:
print("Your check digit is",checkdigit)
if len(str(GTIN))==8 and sum(total)%10==0:
print("Valid GTIN-8 number")
else: print("Invalid GTIN number")
What I suggest doing here is to do some extra checking to ensure you have what you need. So, when you get the user input and you are checking for isdigit, make sure the length as well.
Furthermore, you should not use continue the way you have your condition set up. You should let the logic just proceed if it passes initial validation. So, instead, what you can do is check if it does not match the conditions and you can print an error message and then pass a continue to re-prompt the user:
if not GTIN.isdigit() or not len(GTIN) == 8:
print("invalid entry...")
continue
To total up the numbers you can use a short list that you can use as the variable to calculate the check digit.
I put mine like this:
num_sum = num * 3 +num_1 + num_2 * 3 + num_3 + num_4 * 3 + num_5 + num_6 * 3
Then when you calculate you can use rounded - num_sum = check digit.
Related
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!!!")
This is my program to find the factorial of a number. I would like help to make it so that a negative number would run the same code as Value error, so that count decreases by -1, instead of returning an error. Any advice on how i could structure the code better would be helpful too.
The code starts below:
c = ""
long = ""
factorial_number = 1
count = 3
attempts_left = ""
while count != 0:
try:
number = int(input("Please enter a number above one to find the factorial of" + attempts_left ))
break
except:
ValueError or number < 0
print("Invalid answer")
count -= 1
attempts_left = ", " + str(count) + " attempts remaining."
if count == 1:
attempts_left = attempts_left = ", " + str(count) + " attempt remaining."
if count == 0:
print("NO MORE ATTMEPTS")
else:
if number == 0:
factorial_number = 1
print("Your factorial number is 1")
else:
for interger in range(1,number +1, 1):
factorial_number = interger * factorial_number
a = (str(factorial_number)) + " "
long = long + c + str(interger)
if int(interger) > 0:
c = " * "
print(" The equation is " + long + " = "+a)
You can name multiple exceptions in the except clause, for example:
try:
number = int(input(...))
assert number >= 0
except (ValueError, AssertionError):
print("Invalid answer")
Code Review:
As already noted, the except clause was not implemented properly
factorial_number and long accumulate with each loop and aren't cleared
New Implementation:
As per "Any advice on how i could structure the code better would be helpful too."
Use f-Strings: A New and Improved Way to Format Strings in Python so you don't have to convert numbers to strings
Everything inside a function
Let the while loop be broken with pass, then try to convert number to int. Any letters will result in a ValueError.
int('10') works
int('10.5') doesn't work; int(float(10.5)) is used to also catch decimal numbers.
Handle non-numeric characters as an exception, so a different statement can be printed. Negative numbers are caught with the if condition, and print a different statement.
Alternatively, use an assertion, as shown in the solution by pauliner, to catch both types of invalid input.
Removed separate handling of number = 0
number, long, and factorial_number are reset with each iteration of the while loop, so they don't continue to accumulate from the previous iteration.
def get_factorial():
def failed(value: int) -> str:
return f'{value} failed attempts remaining.'
def game_over(value: int):
if value == 0:
print('NO MORE ATTEMPTS')
count = 3
while count != 0:
number = None
long = 1
factorial_number = 1
try:
number = input(f"Please enter a number above one to find the factorial of, {failed(count)} Type 'pass' to quit." )
if number.lower() == 'pass':
print('Thank you for playing!')
break
number = int(float(number))
if number < 0:
print("Negative numbers are not valid.")
count -= 1
game_over(count)
else:
for integer in range(1, number + 1, 1):
factorial_number *= integer
if integer > 1:
long = f'{long} * {integer}'
else:
long = f'{integer}'
print(f'The equation is {number}! = {long} = {factorial_number}')
except ValueError as e:
print('You input something other than a number')
count -= 1
game_over(count)
Usage:
get_factorial()
# Output 1:
Please enter a number above one to find the factorial of, 3 failed attempts remaining. Type 'pass' to quit. a
You input something other than a number
Please enter a number above one to find the factorial of, 2 failed attempts remaining. Type 'pass' to quit. -1
Negative numbers are not valid.
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. 0
The equation is 0! = 1 = 1
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. 1
The equation is 1! = 1 = 1
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. 2
The equation is 2! = 1 * 2 = 2
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. 9
The equation is 9! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 = 362880
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. pass
Thank you for playing!
# Output 2:
Please enter a number above one to find the factorial of, 3 failed attempts remaining. Type 'pass' to quit. -1
Negative numbers are not valid.
Please enter a number above one to find the factorial of, 2 failed attempts remaining. Type 'pass' to quit. é
You input something other than a number
Please enter a number above one to find the factorial of, 1 failed attempts remaining. Type 'pass' to quit. a
You input something other than a number
NO MORE ATTEMPTS
my problem is i have to calculate the the sum of digits of given number and that no is between 100 to 999 where 100 and 999 can also be include
output is coming in this pattern
if i take a=123 then out put is coming total=3,total=5 and total=6 i only want output total=6
this is the problem
there is logical error in program .Help in resolving it`
this is the complete detail of my program
i have tried it in this way
**********python**********
while(1):
a=int(input("Enter any three digit no"))
if(a<100 or a>999):
print("enter no again")
else:
s = 0
while(a>0):
k = a%10
a = a // 10
s = s + k
print("total",s)
there is no error message in the program because it has logical error in the program like i need output on giving the value of a=123
total=6 but i m getting total=3 then total=5 and in last total=6 one line of output is coming in three lines
If you need to ensure the verification of a 3 digit value and perform that validation, it may be useful to employ Regular Expressions.
import re
while True:
num = input("Enter number: ")
match = re.match(r"^\d{3}$, num)
if match:
numList = list(num)
sum = 0
for each_number in numList:
sum += int(each_number)
print("Total:", sum)
else:
print("Invalid input!")
Additionally, you can verify via exception handling, and implementing that math you had instead.
while True:
try:
num = int(input("Enter number: "))
if num in range(100, 1000):
firstDigit = num // 10
secondDigit = (num // 10) % 10
thirdDigit = num % 10
sum = firstDigit + secondDigit + thirdDigit
print("Total:", sum)
else:
print("Invalid number!")
except ValueError:
print("Invalid input!")
Method two utilizes a range() function to check, rather than the RegEx.
Indentation problem dude, remove a tab from last line.
Also, a bit of python hint/tip. Try it. :)
a=123
print(sum([int(x) for x in str(a)]))
I am creating a code that checks the 8th digit of a 7 digit GTIN 8 number and then tells you if it is a vaild GTIN number. But I get this message and do not know what to do to fix it.
How should I alter my code to stop this problem and have the functions of the code work? Thanks
CODE:
while 2>1:
GTIN = input("Enter 7 digit number for check-digit. Enter 8 digit number for validity.")
if not GTIN.isdigit() or not len(GTIN) == 7:
print("invalid entry...")
continue
a = int(GTIN[0])*3
b = int(GTIN[1])*1
c = int(GTIN[2])*3
d = int(GTIN[3])*1
e = int(GTIN[4])*3
f = int(GTIN[5])*1
g = int(GTIN[6])*3
total = (a+b+c+d+e+f+g)
checkdigit = (total + 9) // 10 * 10 - total
if len(GTIN) == 7:
print("Your check digit is",checkdigit)
if sum(total)%10==0:
print("Valid GTIN-8 number")
else:
print("Invalid GTIN number")
ERROR MESSAGE:
if sum(total)%10==0:
TypeError: 'int' object is not iterable
The exception occurs because sum expects a sequence (for example a list of numbers) as its argument, but you have passed it a single integer (or int), total. An int is not composed of other objects, so you cannot iterate over it like you can with a list or set, for example, hence the TypeError.
total is already the sum of a, b, c, d, e, f, and g, so you don't need to call sum on it.
Just do
if total % 10 == 0:
I am working in python 3 and I am making a program that will take in a 10 digit ISBN Number and applying a method to it to find the 11th number.
Here is my current code
ISBN=input('Please enter the 10 digit number: ')
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Digit1=int(ISBN[0])*11
Digit2=int(ISBN[1])*10
Digit3=int(ISBN[2])*9
Digit4=int(ISBN[3])*8
Digit5=int(ISBN[4])*7
Digit6=int(ISBN[5])*6
Digit7=int(ISBN[6])*5
Digit8=int(ISBN[7])*4
Digit9=int(ISBN[8])*3
Digit10=int(ISBN[9])*2
Sum=(Digit1+Digit2+Digit3+Digit4+Digit5+Digit6+Digit7+Digit8+Digit9+Digit10)
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)
I want to create some kind of loop so that the number after "Digit" for the variable name increases starting from 1 (or zero if it makes life easier), the number in the square brackets increases starting from 0 and the multiplication number to decrease from 11 to 2.
Is there any way of doing this code in a more efficient way?
I think this should do what you want.
def get_isbn_number(isbn):
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
return isbn_number
EXAMPLE
>>> print(get_isbn_number('2345432681'))
22303640281810242428
>>> print(get_isbn_number('2345432680'))
2230364028181024240X
Explanation of second line:
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
Could be written out like:
isbn_letters = list(isbn) # turn a string into a list of characters
isbn_numbers = map(int, isbn_letters) # run the function int() on each of the items in the list
digits = [] # empty list to hold the digits
for i, num in enumerate(isbn_numbers): # loop over the numbers - i is a 0 based counter you get for free when using enumerate
digits.append((11 - i) * num) # If you notice the pattern, if you subtract the counter value (starting at 0) from 11 then you get your desired multiplier
Terms you should look up to understand the one line version of the code:
map,
enumerate,
list conprehension
ISBN=int(input('Please enter the 10 digit number: ')) # Ensuring ISBN is an integer
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Sum = 0
for i in range(len(ISBN)):
Sum += ISBN[i]
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)