Python Forum

Full Version: GTIN code validation program not working!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

def mainmenu(): #Defining mainmenu as a function so it can be called in future if need be.
    while True: 
        print(" MAIN MENU") 
        print("1. Find the check digit of a barcode")
        print("2. Validate a barcode")
        print("3. Quit")  # prints out 3 options for the user to select
        selection=input("Enter choice: ") #tells user to enter a choice
        if selection=='1':
            find() #calls the function and performs the chosen task.
        elif selection=='2':
            validate() #calls the function and performs the chosen task.
        elif selection=='3':
            print("See you in future!")
            exit()
        else:
            print("Invalid choice. Enter 1-3")
            mainmenu()
#Stops the user from entering irrelevant info so the program doesnt fall over.
            
def find(arg=''):
#Defining find as a function with the abillity to have a parameter run through it, this is critical for the validate function.
    GTIN = arg
    if arg == '':
#Starts the find function only if there no parameter being through it, which there isnt in this case.
        GTIN=(input("Enter a 7 digit GTIN number: "))
    if(len(GTIN)==7):
        a=(int(GTIN[0])) #Odd position gets multiplied by three.
        b=(int(GTIN[1])) #Even Position does not change.
        c=(int(GTIN[2]))
        d=(int(GTIN[3]))
        e=(int(GTIN[4]))
        f=(int(GTIN[5]))
        g=(int(GTIN[6]))
#The seven digit barcode is split into seven individual integers which makes it possible to find the check digit.
        GTINT=int(a*3+b+c*3+d+e*3+f+g*3)
#The math for the find check digit function, this is why we split the Barcode into seven numbers.
        roundup=round(GTINT, -1)
#Using the roundup function to round GTINT (GTIN total).
        GTIN8 = int(roundup - GTINT) % 10
        if arg =='':
            print(arg)
            print("Your full GTIN-8 code is: "+str(GTIN)+str(GTIN8))
#Prints the original seven digits (GTIN) with the added GTIN 8 (check digit) added on the end.
        return GTIN8
    else:
        print("Sorry, that's invalid!")
        print("                         ")
        print("1. Yes")
        print("2. No")
        retry=int(input("Would you like to try again?:"))
#The program enquires the user to see if they'd like to try again.
        if retry ==1:
            mainmenu()
#If they do, they get taken back to the main menu.
        elif retry ==2:
            print("Okay! goodbye!")
            exit()
#If they dont, they're given a goodbye and we use the integrated exit function to kill the program.
        else:
            print("Wrong Input!")
            mainmenu()
#This stops the user from entering invalid values causing the program to fall apart.

def validate():
#Defining validate as a function with closed parameter functionallity.
    GTIN=(input("Enter an 8 digit GTIN number: "))
    GTIN8 = find(GTIN[0:7])
#Checks the whole barcode through the GTIN parameter in the find function for the eighth value.
    if str(GTIN8) == GTIN[7]:
#It checks the last value of the entered value and compares it to the checked value to see if they match.
        print("Your code is valid")
#And if they do match, the program says it's valid.
        print("                         ")
        print("1. Yes")
        print("2. No")
        retry=int(input("Would you like to try again?:  "))
#The program enquires the user to see if they'd like to try again.
        if retry ==1:
            mainmenu()
#If they do, they get taken back to the main menu.
        elif retry ==2:
            print("Okay! goodbye!")
            exit()
#If they dont, they're given a goodbye and we use the integrated exit function to kill the program.
        else:
            print("Wrong Input!")
            validate()
#This stops the user from entering invalid values causing the program to fall apart.
    else:
        print("Your code is invalid!")
        mainmenu()
#This tells the user the barcode they entered is invalid, taking them to the main menu.
    
mainmenu()
#Calling the main menu.
Error:
Traceback (most recent call last): File "C:\Users\xxx\Downloads\GTIN-899 (1).py", line 138, in <module> mainmenu() File "C:\Users\xxx\Downloads\GTIN-899 (1).py", line 21, in mainmenu mainmenu() File "C:\Users\xxx\Downloads\GTIN-899 (1).py", line 13, in mainmenu find() # calls the function and performs the chosen task. File "C:\Users\xxx\Downloads\GTIN-899 (1).py", line 43, in find g = int(GTIN[6]) ValueError: invalid literal for int() with base 10: 'p'
Right, first post. most definitely wont be my last knowing my noobiness. Anyways, I need help, I have been slaving over this code for hours and I just cannot get it to work properly, my issue here is the find function not returning an error message when I enter "123456p" as my 7 digit code, it should say that it is a wrong code? its linked to the if statement or is it not? I experimented with some stuff and ended up with another piece of broken code.

def mainmenu(): #Defining mainmenu as a function so it can be called in future if need be.
    while True: 
        print(" MAIN MENU") 
        print("1. Find the check digit of a barcode")
        print("2. Validate a barcode")
        print("3. Quit")  # prints out 3 options for the user to select
        selection=input("Enter choice: ") #tells user to enter a choice
        if selection=='1':
            find() #calls the function and performs the chosen task.
        elif selection=='2':
            validate() #calls the function and performs the chosen task.
        elif selection=='3':
            print("See you in future!")
            exit()
        else:
            print("Invalid choice. Enter 1-3")
            mainmenu()
#Stops the user from entering irrelevant info so the program doesnt fall over.
            
def find(arg=''):
#Defining find as a function with the abillity to have a parameter run through it, this is critical for the validate function.
    GTIN = arg
    if arg == '':
        #Starts the find function only if there no parameter being through it, which there isnt in this case.
        try:
            GTIN=input("Enter a 7 digit GTIN number: ")
            if(len(GTIN)==7):
                a=int(GTIN[0:1]) #Odd position gets multiplied by three.
                b=int(GTIN[1:2]) #Even Position does not change.
                c=int(GTIN[2:3])
                d=int(GTIN[3:4])
                e=int(GTIN[4:5])
                f=int(GTIN[5:6])
                g=int(GTIN[6:7])
        except ValueError:
                print('Please enter an integer value.')
#The try except is used to prevent the user from entering values that would otherwise cause the program to fall apart.
#The seven digit barcode is split into seven individual integers which makes it possible to find the check digit.
        GTINT=int(a*3+b+c*3+d+e*3+f+g*3)
#The math for the find check digit function, this is why we split the Barcode into seven numbers.
        roundup=round(GTINT, -1)
#Using the roundup function to round GTINT (GTIN total).
        GTIN8 = int(roundup - GTINT) % 10
        if arg =='':
            print(arg)
            print("Your full GTIN-8 code is: "+str(GTIN)+str(GTIN8))
#Prints the original seven digits (GTIN) with the added GTIN 8 (check digit) added on the end.
        return GTIN8
    else:
        print("Sorry, that's invalid!")
        print("                         ")
        print("1. Yes")
        print("2. No")
        retry=int(input("Would you like to try again?:"))
#The program enquires the user to see if they'd like to try again.
        if retry ==1:
            mainmenu()
#If they do, they get taken back to the main menu.
        elif retry ==2:
            print("Okay! goodbye!")
            exit()
#If they dont, they're given a goodbye and we use the integrated exit function to kill the program.
        else:
            print("Wrong Input!")
            mainmenu()
#This stops the user from entering invalid values causing the program to fall apart.

def validate():
#Defining validate as a function with closed parameter functionallity.
    GTIN=(input("Enter an 8 digit GTIN number: "))
    GTIN8 = find(GTIN[0:7])
#Checks the whole barcode through the GTIN parameter in the find function for the eighth value.
    if str(GTIN8) == GTIN[7]:
#It checks the last value of the entered value and compares it to the checked value to see if they match.
        print("Your code is valid")
#And if they do match, the program says it's valid.
        print("                         ")
        print("1. Yes")
        print("2. No")
        retry=int(input("Would you like to try again?:  "))
#The program enquires the user to see if they'd like to try again.
        if retry ==1:
            mainmenu()
#If they do, they get taken back to the main menu.
        elif retry ==2:
            print("Okay! goodbye!")
            exit()
#If they dont, they're given a goodbye and we use the integrated exit function to kill the program.
        else:
            print("Wrong Input!")
            validate()
#This stops the user from entering invalid values causing the program to fall apart.
    else:
        print("Your code is invalid!")
        mainmenu()
#This tells the user the barcode they entered is invalid, taking them to the main menu.
    
mainmenu()
#Calling the main menu.
And ended up with this error:
Error:
Traceback (most recent call last): File "C:\Users\xxx\Downloads\GTIN-8999.py", line 98, in <module> mainmenu() File "C:\Users\xxx\Downloads\GTIN-8999.py", line 9, in mainmenu find() #calls the function and performs the chosen task. File "C:\Users\xxx\Downloads\GTIN-8999.py", line 39, in find GTINT=int(a*3+b+c*3+d+e*3+f+g*3) UnboundLocalError: local variable 'g' referenced before assignment
I understand if im not worth your time, any help is good help, thanks!
You're calling variables outside of their assignment.

Everything that is intended to be within your "find()" function's first "if:" statement should be inside of the "try:" statement as well, currently they reside outside. Hopefully, you understand what I mean by this, if not I'll explain further.

Also, consider using a while loop instead of calling your functions again.