Technocamps

Here is some of the code that I write for Technocamps

You may find these useful if you have been to one of our workshops

Magic 8 Ball

Version 1.0

#####################################################################
#	Author		:		Robert Lutken								#
#	Date		:		18/01/2016									#
#	File		:		MagicEightBall.py							#
#	Purpose		:		Demonstration of IF statements in python	#
#	Version		:		1.0											#
#####################################################################
# Use code from the Random Library (Someone else's code)
import random
#Define Computer's Answers 
ans1 = "Go For It!"
ans2 = "No way!"
ans3 = "I'm not sure!?"
ans4 = "The universe states that is inconceivable"
ans5 = "That is not possible"
ans6 = "Yes."

# Generate a random number
randomNumber = random.randint(0,6)

#Output start prompt 
question = input("Please enter a question: ")

# Calculate response
if randomNumber == 1:
	answer = ans1
elif randomNumber == 2:
	answer = ans2
elif randomNumber == 3:
	answer = ans3
elif randomNumber == 4:
	anwer = ans4
elif randomNumber == 5:
	answer = ans5
elif randomNumber == 6:
	answer = ans6
else :
	answer = ans6
	
print ("You asked the computer:", question)
print ("The computer says:", answer)
input ("Press [Enter] to Exit:")

Version 1.1 – While Loops

#########################################################################################
#	Author		:		Robert Lutken                                   #
#	Date		:		18/01/2016                                      #
#	File		:		MagicEightBall.py                               #
#	Purpose		:		Demonstration of While statements in python     #
#	Version		:		1.1                                             #
########################################################################################
# Use code from the Random Library (Someone else's code)
import random
#Define Computer's Answers 
ans1 = "Go For It!"
ans2 = "No way!"
ans3 = "I'm not sure!?"
ans4 = "The universe states that is inconceivable"
ans5 = "That is not possible"
ans6 = "Yes."
# Set user input to 0 so we enter the loop
usrInput = 0
# Loop untill usrInput is not 0
# This says keep doing what ever is indented untill
# usrInput is EQUAL (==) to 0
while usrInput == 0:
        # Generate a random number
        randomNumber = random.randint(0,6)

        #Output start prompt 
        question = input("Please enter a question: ")

        # Calculate response
        if randomNumber == 1:
                answer = ans1
        elif randomNumber == 2:
                answer = ans2
        elif randomNumber == 3:
                answer = ans3
        elif randomNumber == 4:
                answer = ans4
        elif randomNumber == 5:
                answer = ans5
        elif randomNumber == 6:
                answer = ans6
        else :
                answer = ans6
        # Print answer
        print ("You asked the computer:", question)
        print ("The computer says:", answer)
        # Ask if user wants to quit
        usrInput = int(input ("Enter 1 to exit or 0 to continue:"))
print ("Exiting....")

Version 1.2 – Functions

#########################################################################################
#	Author		:		Robert Lutken                                   #
#	Date		:		18/01/2016                                      #
#	File		:		MagicEightBall.py                               #
#	Purpose		:		Demonstration of Functions in python            #
#	Version		:		1.2                                             #
########################################################################################
# Use code from the Random Library (Someone else's code)
import random
# Define a function that has a random number passed into it
# The function will calculate as normal then return the answer
def CalculateResponse(randomNumber):
        # Calculate response
        if randomNumber == 1:
                answer = ans1
        elif randomNumber == 2:
                answer = ans2
        elif randomNumber == 3:
                answer = ans3
        elif randomNumber == 4:
                answer = ans4
        elif randomNumber == 5:
                answer = ans5
        elif randomNumber == 6:
                answer = ans6
        else :
                answer = ans6
        return answer

#Define Computer's Answers 
ans1 = "Go For It!"
ans2 = "No way!"
ans3 = "I'm not sure!?"
ans4 = "The universe states that is inconceivable"
ans5 = "That is not possible"
ans6 = "Yes."
# Set user input to 0 so we enter the loop
usrInput = 0
# Loop untill usrInput is not 0
# This says keep doing what ever is indented untill
# usrInput is EQUAL (==) to 0
while usrInput == 0:
        # Generate a random number
        randomNumber = random.randint(0,6)

        #Output start prompt 
        question = input("Please enter a question: ")

        answer = CalculateResponse(randomNumber)
        # Print answer
        print ("You asked the computer:", question)
        print ("The computer says:", answer)
        # Ask if user wants to quit
        usrInput = int(input ("Enter 1 to exit or 0 to continue:"))
print ("Exiting....")

A-Level Mock Assessment


Assessment Mock Questions PDF

Video Tutorial for Task 1


Customers.py

# Only works in Python 3 (Created in 3.4.2)
# tkinter comes as part of the standard install - messagebox has to be imported explicitly

'''
    Author          :   Robert Lutken
    Date            :   24/03/2016
    File            :   Customers.py
    Purpose         :   Tkinter Customer Information UI for Games Tech Ltd Mock Assesment 
    Version         :   1.0
'''

from tkinter import *
from tkinter import messagebox

'''
    SaveDetails 
    -Gets the information from each of the Tkinter UI elements
    -Adds padding to the strings 
    -Opens File to save
    -Writes newly padded details to the file
    -Closes the file

    Task : 
    a) Add the appopriate number to pad the variables correctly for:
    LN38: ageSave
    LN42: dobSave
    LN46: postcodeSave
    LN48: telSave.ljust
    b) Add the filename to save customer details too.
    LN52: fileObject = open(...)
'''
def saveDetails() :
    # for each field get the value from the screen and pad with spaces or chop if necessary
    nameSave= nameVar.get()
    nameSave = nameSave.ljust(30)
    
    ageSave = ageVar.get()
    ageSave = ageSave.ljust('''#...Add Correct Padding HERE!''')

    #25/06/1993
    dobSave = dobVar.get()
    dobSave = dobSave.ljust('''#...Add Correct Padding HERE!''')

    #NP145SW
    postCodeSave = postCodeVar.get()
    postCodeSave = postCodeSave.ljust('''#...Add Correct Padding HERE!''')
    
    telSave = telVar.get()
    telSave = telSave.ljust('''#...Add Correct Padding HERE!''')
    
    #open the file to append - if it's not there it'll be created
    fileObject = open('''#... Open The Correct File HERE!''' , "a")

    # write to the file with a newline character at the end
    fileObject.write(nameSave + ageSave + dobSave + postCodeSave + telSave + "\n")
    fileObject.close()
    
    return
'''
     CountCustomers 
    -Validates each of the UI Widgets
    -Opens customer details file
    -Cycles through each line of the file and places each line in recordVar
    -For each line it will check if the UI entry i.e. Rob is found on the line 
    -Between characters [0:30] which is the padded string for the Name Entry
    -Adds up how many "Rob's" have been found 
    -Displays message box to the user 

    Task : 
    a) Add the appopriate number to pad the variables correctly for:
    LN90: if len(ageSave) > 0:
    LN96: if len(dobSave) > 0:
    LN102: if len(postCodeSave) > 0:
    LN108: if len(dobSave) > 0:
    b) Add the correct validation to ensure that users are between the ages 1 and 99
    LN113: if int(ageSave) > 0 or int(ageSave) < 0: c) Add the correct index for each record var when reading each line: LN153 - LN159 if ageSave in recordVar[ ] and not ageSave=="" : ''' def countCustomers() : CustomerCount=0 CountNeeded=0 #get the fields off the screen and validate them nameSave = nameVar.get() if len(nameSave) > 30 :
        messagebox.showerror("Error","Too many characters in Name")
        return

    ageSave =ageVar.get()
    '''#... if len(ageSave) > Add Correct Padding Offset HERE :'''
    if len(ageSave) > 0:
        messagebox.showerror("Error","Too many characters in Age")
        return

    dobSave = dobVar.get() 
    '''#... if len(dobSave) > Add Correct Padding Offset HERE':'''
    if len(dobSave) > 0:
        messagebox.showerror("Error","Too many characters in Dob")
        return

    postCodeSave = postCodeVar.get()
    '''#... if len(postCodeSave) >  Add Correct Padding Offset HERE :'''
    if len(postCodeSave) > 0:
        messagebox.showerror("Error","Too many characters in  PostCode")
        return

    telSave = telVar.get()
    '''#... if len(telSave) > Add Correct Padding Offset HERE :'''
    if len(telSave) > 0:
        messagebox.showerror("Error","Too many characters in Tel")
        return

    '''if int(ageSave) > Add Correct Range HERE or int(ageSave) < Add Correct Age range HERE:''' if int(ageSave) > 0 or int(ageSave) < 0:
        messagebox.showerror("Error","Please enter a valid age!")

    
    if not nameSave == "" :
        CountNeeded +=1
    if not ageSave == "" :
        CountNeeded +=1
    if not dobSave == "" :
        CountNeeded +=1
    if not postCodeSave == "" :
        CountNeeded +=1
    if not telSave == "" :
        CountNeeded +=1

    if CountNeeded == 0 :
        messagebox.showerror("Error","Please enter something to count! \n" + int(CountNeeded) + " are missing!")
        return
    # try opening the file for reading
    try:
        fileObject=open("customerdetails.txt","r")
        
    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:
            CountGot=0
            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break
         
            if nameSave in recordVar[0:30] and not nameSave=="" :
                CountGot +=1
            if ageSave in recordVar[''' Add Correct Index HERE'''] and not ageSave=="" :
                CountGot +=1
            if dobSave in recordVar[''' Add Correct Index HERE'''] and not dobSave=="":
                CountGot +=1
            if postCodeSave in recordVar[''' Add Correct Index HERE'''] and not postCodeSave =="":
                CountGot +=1
            if telSave in recordVar[''' Add Correct Index HERE'''] and not telSave=="":
                CountGot +=1
            if CountGot == CountNeeded:
                CustomerCount +=1
                
        messagebox.showinfo("Information",str(CustomerCount) + " Customer found.")    
    
    return

'''
    MakeWindow
    -Creates global variables for each of the reqiured fields
    -Sets up Tkinter Window
    -Creates Labels and Entry Widgets
    -Adds two buttons and Registers the correct callbacks

    a) Add Correct Function Command to Buttons
    LN238 - 239:   b1= Button(frame2, text=" Save ", command= )
'''
def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

    #Name
    #Age
    #DOB
    #PostCode
    #Tel
    global nameVar,ageVar,dobVar,postCodeVar,telVar
    
    #here's my window
    win = Tk()
    win.wm_title("Games Tech Ltd")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Customer Details", font=("Helvetica 12 bold")).grid(row=0, column=0)
    
    Label(frame1, text="Name").grid(row=1, column=0, sticky=W)

    # Setup entry widget for NAME
    nameVar=StringVar()                 
    nameEntry= Entry(frame1, textvariable=nameVar)# Set where text is saved
    nameEntry.grid(row=1,column=1,sticky=W)

    # Label for Age
    Label(frame1, text="Age").grid(row=2, column=0, sticky=W)
    # Setup entry widget for AGE
    ageVar=StringVar()
    ageEntry = Entry(frame1, textvariable=ageVar)
    ageEntry.grid(row=2,column=1,sticky=W)

    # Label for DOB
    Label(frame1, text="Date of Birth").grid(row=3, column=0, sticky=W)
    # Setup entry for DateOfBirth
    dobVar=StringVar()
    dobEntry= Entry(frame1, textvariable=dobVar)
    dobEntry.grid(row=3,column=1,sticky=W)
    
    # Label for POSTCODE
    Label(frame1, text="Post Code").grid(row=4, column=0, sticky=W)
    postCodeVar=StringVar()
    # Setup entry for POSTCODE
    postCodeEntry= Entry(frame1, textvariable=postCodeVar)
    postCodeEntry.grid(row=4,column=1,sticky=W)
    
    # Label for Telephone
    Label(frame1, text="Telephone").grid(row=5, column=0, sticky=W)
    # Setup entry for Telephone
    telVar=StringVar()
    telEntry= Entry(frame1, textvariable=telVar)
    telEntry.grid(row=5,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command='''Add Funciton To Call Here''')
    b2= Button(frame2, text=" Count ", command='''Add Funciton To Call Here''')
    b1.pack(side=LEFT); b2.pack(side=LEFT)
    
    return win


#this is the main program!
win = makeWindow()
win.mainloop()

Video Tutorial for Part 2

Games.py

# Only works in Python 3 (Created in 3.4.2)
# tkinter comes as part of the standard install - messagebox has to be imported explicitly

'''
    Author          :   Robert Lutken
    Date            :   28/04/2016
    File            :   Games.py
    Purpose         :   Tkinter Games Information UI for Games Tech Ltd Mock Assesment 
    Version         :   1.0
'''

from tkinter import *
from tkinter import messagebox

'''
    SaveDetails 
    -Gets the information from each of the Tkinter UI elements
    -Adds padding to the strings 
    -Opens File to save
    -Writes newly padded details to the file
    -Closes the file

'''
def saveGame() :
    # for each field get the value from the screen and pad with spaces or chop if necessary
    titleSave = titleVar.get()
    titleSave = titleSave.ljust(30)
    
    priceSave = priceVar.get()
    priceSave = priceSave.ljust(3)

    quantitySave = quantityVar.get()
    quantitySave = quantitySave.ljust(3)

    pegiSave = pegiVar.get()
    pegiSave = pegiSave.ljust(3)
    
    genreSave = genreVar.get()
    genreSave = genreSave.ljust(20)

    publisherSave = publisherVar.get()
    publisherSave = publisherSave.ljust(30)
    
    #open the file to append - if it's not there it'll be created
    fileObject = open("GameStock.txt","a")

    # write to the file with a newline character at the end
    fileObject.write(titleSave + priceSave + quantitySave + pegiSave + genreSave + publisherSave + "\n")
    fileObject.close()
    
    return
'''
     CountCustomers 
    -Validates each of the UI Widgets
    -Opens customer details file
    -Cycles through each line of the file and places each line in recordVar
    -For each line it will check if the UI entry i.e. Rob is found on the line 
    -Between characters [0:30] which is the padded string for the Name Entry
    -Adds up how many "Rob's" have been found 
    -Displays message box to the user 

'''
def countStock() :
    CustomerCount=0
    CountNeeded=0

    #get the fields off the screen and validate them
    titleSave = titleVar.get()
    if len(titleSave) > 30 :
        messagebox.showerror("Error","Too many characters in Title")
        return

    priceSave = priceVar.get()
    if len(priceSave) > 3:
        messagebox.showerror("Error","Too many characters in price")
        return

    quantitySave = quantityVar.get() 
    if len(quantitySave) > 3:
        messagebox.showerror("Error","Too many characters in Quantity")
        return

    pegiSave = pegiVar.get()
    if len(pegiSave) > 3:
        messagebox.showerror("Error","Too many characters in  pegi")
        return

    genreSave = genreVar.get()
    if len(genreSave) > 20:
        messagebox.showerror("Error","Too many characters in genre")
        return
    
    publisherSave = publisherVar.get()
    if len(publisherSave) > 30:
        messagebox.showerror("Error","Too many characters in publisher")
        return

    if not titleSave == "" :
        CountNeeded +=1
    if not priceSave == "" :
        CountNeeded +=1
    if not quantitySave == "" :
        CountNeeded +=1
    if not pegiSave == "" :
        CountNeeded +=1
    if not genreSave == "" :
        CountNeeded +=1
    if not publisherSave == "" :
        CountNeeded +=1

    if CountNeeded == 0 :
        messagebox.showerror("Error","Please enter something to count! \n" + int(CountNeeded) + " are missing!")
        return
    # try opening the file for reading
    try:
        fileObject=open("GameStock.txt","r")
        
    # if it's not there then say
    except IOError:
        messagebox.showerror("Error","No file to read")

    # if we did open it then let's carry on!
    else:
        while True:
            CountGot=0
            recordVar=fileObject.readline()
            # Python keeps reading till EOF then returns a blank
            if recordVar=="":
                fileObject.close()
                break
         
            if titleSave in recordVar[0:30] and not titleSave=="" :
                CountGot +=1
            if priceSave in recordVar[30:33] and not priceSave=="" :
                CountGot +=1
            if quantitySave in recordVar[33:36] and not quantitySave=="":
                CountGot +=1
            if pegiSave in recordVar[36:39] and not pegiSave =="":
                CountGot +=1
            if genreSave in recordVar[39:59] and not genreSave=="":
                CountGot +=1
            if publisherSave in recordVar[59:89] and not publisherSave=="":
                CountGot +=1
            if CountGot == CountNeeded:
                CustomerCount +=1
                
        messagebox.showinfo("Information",str(CustomerCount) + " Customer found.")    
    
    return

'''
    MakeWindow
    -Creates global variables for each of the reqiured fields
    -Sets up Tkinter Window
    -Creates Labels and Entry Widgets
    -Adds two buttons and Registers the correct callbacks

'''
def makeWindow():
    #declared my globals here as this is the 1st routine called
    # the other routines have to be in front of this one as they get called by it
    # and the parser would get upset if they weren't there

   
    global titleVar,priceVar,quantityVar,pegiVar,genreVar,publisherVar
    
    #here's my window
    win = Tk()
    win.wm_title("Games Tech Ltd")
    #split into two sections then further split into a grid
    frame1=Frame(win)
    frame1.pack()

    Label(frame1, text="Game Stock", font=("Helvetica 12 bold")).grid(row=0, column=0)
    
    Label(frame1, text="Game Title").grid(row=1, column=0, sticky=W)

    # Setup entry widget for Title
    titleVar=StringVar()                 
    titleVar= Entry(frame1, textvariable=titleVar)# Set where text is saved
    titleVar.grid(row=1,column=1,sticky=W)

    # Label for Price
    Label(frame1, text="Price").grid(row=2, column=0, sticky=W)
    # Setup entry widget for price
    priceVar=StringVar()
    priceVar = Entry(frame1, textvariable=priceVar)
    priceVar.grid(row=2,column=1,sticky=W)

    # Label for quantity
    Label(frame1, text="Quantity").grid(row=3, column=0, sticky=W)
    # Setup entry for DateOfBirth
    quantityVar=StringVar()
    quantityVar= Entry(frame1, textvariable=quantityVar)
    quantityVar.grid(row=3,column=1,sticky=W)
    
    # Label for Pegi
    Label(frame1, text="Pegi").grid(row=4, column=0, sticky=W)
    pegiVar=StringVar()
    # Setup entry for pegi
    pegiVar= Entry(frame1, textvariable=pegiVar)
    pegiVar.grid(row=4,column=1,sticky=W)
    
    # Label for Genre
    Label(frame1, text="Genre").grid(row=5, column=0, sticky=W)
    # Setup entry for Genre
    genreVar=StringVar()
    genreVar= Entry(frame1, textvariable=genreVar)
    genreVar.grid(row=5,column=1,sticky=W)

    # Label for Publisher
    Label(frame1, text="Publisher").grid(row=6, column=0, sticky=W)
    # Setup entry for Publisher
    publisherVar=StringVar()
    publisherVar= Entry(frame1, textvariable=publisherVar)
    publisherVar.grid(row=6,column=1,sticky=W)

    frame2 = Frame(win)
    frame2.pack()

    # build my buttons in the other frame then pack them side by side
    b1= Button(frame2, text=" Save ", command=saveGame)
    b2= Button(frame2, text=" Count ", command=countStock)
    b1.pack(side=LEFT); b2.pack(side=LEFT)
    
    return win


#this is the main program!
win = makeWindow()
win.mainloop()