Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Introduction to Python Programming Code Page

Author: Sophia
what's covered
This page provides the code that is used in the Introduction to Python Programming course. Below are links to each project's full code.

Note: Each of these are main.py code snippets. In Units 3 and 4, you will notice that there are external files needed to be included prior to executing the main program (main.py), make sure the file names are entered exactly as presented in this lesson.

Table of Contents

Unit 1

Project 1: Mentalism Program


#We are importing a module that we need to be able to generate random numbers
import random

#We are creating a random even number between 2 and 10 by
#first randomizing an integer between 1 and 5. This will be our
#final number. The number to add will take that and multiply it by 2.
randomFinalNumber = random.randrange(1, 5)
numberToAdd = randomFinalNumber * 2

#Asking the user to enter in their name
name = input("Hello! What is your name? ")

#Script to walk through each of the steps
print("Welcome " +name +", we’ll perform some mind reading on you.")
print("First, think of a number between 1 and 10.")
print("Multiply the result by 2.")
answer = input("Ready for the next step? ")
print("Now, add...let's see...")
print(numberToAdd)
answer = input("Ready for the next step? ")
print("Now, divide the number have by 2.")
answer = input("Ready for the next step? ")
print("Now, subtract the original number that you thought about.")
answer = input("Ready for the last step? ")

#Guessing the number
print("Well " +name +", let me read your mind...The number that you have right now is a....")
print(randomFinalNumber)

#Validating the results
enteredNumber = int(input(">> Enter in the number the individual guessed between 1 and 10: "))
userNumber = enteredNumber * 2
print(">> Muliplied by 2 = " + str(userNumber))
userNumber = userNumber + numberToAdd
print(">> Told to add "+ str(numberToAdd) + " = " + str(userNumber))
userNumber = userNumber / 2
print(">> Divided by 2 = " + str(userNumber))
userNumber = userNumber - enteredNumber
print(">> Subtracted the original number "+ str(enteredNumber) +" = " + str(userNumber))

Project 2: Drink Order Program


drinkDetails=""
drink = input('What type of drink would you like to order?\nWater\nCoffee\nTea\nEnter your choice: ')
if drink == "Water":
    drinkDetails=drink
    temperature = input("Would you like your water? Hot or Cold: ")
    if temperature == "Hot":
        drinkDetails += ", " + temperature
    elif temperature == "Cold":
        drinkDetails += ", " + temperature  
        ice = input("Would you like ice? Yes or No: ")
        if ice == "Yes":
            drinkDetails += ", Ice"
    else:
        drinkDetails += ", unknown temperature entered."
elif drink == "Coffee":
    drinkDetails=drink
    decaf = input("Would you like decaf? Yes or No: ")
    if decaf == "Yes":
        drinkDetails += ", Decaf"
    milkCream = input("Would you like Milk, Cream or None: ")
    if milkCream == "Milk":
        drinkDetails += ", Milk"
    elif milkCream == "Cream":
        drinkDetails += ", Cream"
    sugar = input("Would you like sugar? Yes or No: ")
    if sugar == "Yes":
        drinkDetails += ", Sugar"
elif drink == "Tea":
    drinkDetails=drink
    teaType = input("What type of tea would you like? Black or Green: ")
    if teaType == "Black":
        drinkDetails += ", " + teaType
    elif teaType == "Green":
        drinkDetails += ", " + teaType
else:
    print("Sorry, we did not have that drink available for you.")
print("Your drink selection: ",drinkDetails)


Unit 2

Project 1: Tic-Tac-Toe Program


#the following code creates the board
board = [ ["-", "-", "-"],
          ["-", "-", "-"],
          ["-", "-", "-"] ]
 
print(board[0])
print(board[1])
print(board[2])
 
#this is player X’s first move
col = int(input("X player, select a column 1-3: "))
row = int(input("X player, select a row 1-3: "))
col -= 1
row -= 1
 
board[row][col] = "X"
print(board[0])
print(board[1])
print(board[2])
 
#this is player O’s first move
col = int(input("O player, select a column 1-3: "))
row = int(input("O player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "O"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player X’s second move
col = int(input("X player, select a column 1-3: "))
row = int(input("X player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "X"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player O’s second move
col = int(input("O player, select a column 1-3: "))
row = int(input("O player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "O"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player X’s third move
col = int(input("X player, select a column 1-3: "))
row = int(input("X player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "X"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player O’s third move
col = int(input("O player, select a column 1-3: "))
row = int(input("O player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "O"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player X’s fourth move
col = int(input("X player, select a column 1-3: "))
row = int(input("X player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "X"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player O’s fourth move
col = int(input("O player, select a column 1-3: "))
row = int(input("O player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "O"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])
 
#this is player X’s fifth move
col = int(input("X player, select a column 1-3: "))
row = int(input("X player, select a row 1-3: "))
col -= 1
row -= 1
 
if board[row][col] == '-':
  board[row][col] = "X"
else:
  print("Oops, that spot was already taken. ")
print(board[0])
print(board[1])
print(board[2])

Project 2: Revisiting the Tic-Tac-Toe Program


board = [ ["-", "-", "-"],
          ["-", "-", "-"],
          ["-", "-", "-"] ]
 
print(board[0])
print(board[1])
print(board[2])
col=0
row=0
playerTurn = "X"

for counter in range(1,10):

    validMove = False #setting the validMove variable to False
    while (validMove == False): #while loop checking the validMove variable
      col=0
      row=0
      while (col < 1 or col > 3):
        col = int(input(playerTurn + " player, select a column 1-3: "))
        if (col < 1 or col > 3):
          print("The column must be between 1 and 3.")
      while (row < 1 or row > 3):
        row = int(input(playerTurn + " player, select a row 1-3: "))
        if (row < 1 or row > 3):
          print("The row must be between 1 and 3.")
      col -= 1
      row -= 1
      if board[row][col] == '-':
        board[row][col] = playerTurn
        validMove=True; #setting validMove to True to exit loop
      else:
        print("Oops, that spot was already taken. Please select another spot.")
 
    print(board[0])
    print(board[1])
    print(board[2])
 
    if playerTurn =="X":
      playerTurn="O"
    else:
      playerTurn="X"

Project 3: Finishing the Tic-Tac-Toe Program


board = [ ["-", "-", "-"],
          ["-", "-", "-"],
          ["-", "-", "-"] ]
 
#printing the board
def printBoard(board):
    print("\n")
    print("\t     |     |")
    print("\t  {}  |  {}  |  {}".format(board[0][0], board[0][1], board[0][2]))
    print('\t_____|_____|_____')
 
    print("\t     |     |")
    print("\t  {}  |  {}  |  {}".format(board[1][0], board[1][1], board[1][2]))
    print('\t_____|_____|_____')
 
    print("\t     |     |")
    print("\t  {}  |  {}  |  {}".format(board[2][0], board[2][1], board[2][2]))
    print("\t     |     |")
    print("\n")
 
def checkWinner(currPlayer, board):
  #Checking for the winner in the row
  for row in range(0,3):
    if board[row][0]==board[row][1]==board[row][2] and board[row][0] != '-':
      if board[row][0]==currPlayer:
        print("{} is winner".format(currPlayer))
        return True
  #used to check the winner in column
  for col in range(0,3):
    if board[0][col]==board[1][col]==board[2][col] and board[0][col] != '-':
      if board[0][col]==currPlayer:
        print("{} is winner".format(currPlayer))
        return True
  #used to check winner in one diagonal
  if board[0][0]==board[1][1]==board[2][2] and board[0][0] !='-':
    if board[0][0]==currPlayer:
      print("{} is winner".format(currPlayer))
      return True
  #used to check winner in another diagonal
  if board[0][2]==board[1][1]==board[2][0] and board[0][2]!='-':
    if board[0][2]==currPlayer:
      print("{} is winner".format(currPlayer))
      return True
  return False
 
printBoard(board)
col=0
row=0
playerTurn = "X"
 
for counter in range(1,10):
    validMove = False
    while (validMove == False):
      col=0
      row=0
      while (col < 1 or col > 3):
        col = int(input(playerTurn + " player, select a column 1-3: "))
        if (col < 1 or col > 3):
          print("The column must be between 1 and 3.")
      while (row < 1 or row > 3):
        row = int(input(playerTurn + " player, select a row 1-3: "))
        if (row < 1 or row > 3):
          print("The row must be between 1 and 3.")
      col -= 1
      row -= 1
      if board[row][col] == '-':
        board[row][col] = playerTurn
        validMove=True;
      else:
        print("Oops, that spot was already taken. Please select another spot.")
        validMove=False
        row=0
        col=0
 
    printBoard(board)
    if (checkWinner(playerTurn,board)):
      break
 
    if playerTurn =="X":
      playerTurn="O"
    else:
      playerTurn="X"


Unit 3

Project 1: The Employee Class Program


import datetime 
class Employee:
  def __init__(self, fname, lname, empid, title, sal):
    self.firstname = fname
    self.lastname = lname
    self.employeeid = empid
    self.jobtitle = title
    self.salary = sal
 
    self.hiredate = datetime.date.today()
  
  #returns first name
  def get_firstname(self):
    return self.firstname
  
  #sets firstname if fname isn't an empty string
  def set_firstname(self,fname):
    if len(fname) > 0:
      self.firstname = fname
 
  #returns last name
  def get_lastname(self):
    return self.lastname
  
  #sets lastname if lname isn't an empty string
  def set_lastname(self,lname):
    if len(lname) > 0:
      self.lastname = lname
 
  #returns job title
  def get_jobtitle(self):
    return self.jobtitle
  
  #sets job title if job title isn't an empty string
  def set_jobtitle(self,title):
    if len(title) > 0:
      self.jobtitle = title
 
  #return employee id
  def get_employeeid(self):
    return "Employee ID: " + str(self.employeeid)
 
  #returns salary
  def get_salary(self):
    return "${:,.2f}".format(self.salary)
  
  #sets salary if salary isn't an empty string
  def set_salary(self,sal):
    if sal > 0:
      self.salary = sal
 
  #increase salary
  def increase_salary(self,percent):
    if percent > 0:
      self.set_salary(self.salary + self.salary * percent)
    else:
      print("Increase of salary must be greater than 0.")
 
sophia = Employee("Jack","Krichen", 1000, "Manager", 50000)
print(sophia.get_firstname())
print(sophia.get_lastname())
print(sophia.get_employeeid())
print(sophia.get_jobtitle())
print(sophia.get_salary())
 
#increase of salary
sophia.increase_salary(-0.02)
print("After increase: " + sophia.get_salary())

Project 2: Revisiting the Employee Class Program


import datetime 
class Person:
  def __init__(self, fname, lname, title):
    self.firstname = fname
    self.lastname = lname
    self.jobtitle = title
 
    self.hiredate = datetime.date.today()
  
  #returns first name
  def get_firstname(self):
    return self.firstname
  
  #sets firstname if fname isn't an empty string
  def set_firstname(self,fname):
    if len(fname) > 0:
      self.firstname = fname
 
  #returns last name
  def get_lastname(self):
    return self.lastname
  
  #sets lastname if lname isn't an empty string
  def set_lastname(self,lname):
    if len(lname) > 0:
      self.lastname = lname
 
  #returns job title
  def get_jobtitle(self):
    return self.jobtitle
  
  #sets job title if job title isn't an empty string
  def set_jobtitle(self,title):
    if len(title) > 0:
      self.jobtitle = title
 
class Employee(Person):
  def __init__(self,fname,lname,title,sal,empid):
    super().__init__(fname,lname,title)
    self.employeeid = empid
    self.salary = sal
    self.vacationdaysperyear = 14
    self.vacationdays = self.vacationdaysperyear 
 
  #return employee id
  def get_employeeid(self):
    return "Employee ID: " + str(self.employeeid)
 
  #returns salary
  def get_salary(self):
    return "${:,.2f}".format(self.salary)
  
  #sets salary if salary isn't an empty string
  def set_salary(self,sal):
    if sal > 0:
      self.salary = sal
 
  #increase salary
  def increase_salary(self,percent):
    if percent > 0:
      self.set_salary(self.salary + self.salary * percent)
    else:
      print("Increase of salary must be greater than 0.")
 
  #return vacation days
  def get_vacation_days(self):
    return "Vacation Days: " + str(self.vacationdays)
 
  #increase vacation days per year
  def increase_vacation_days_per_year(self,days):
    if days > 0:
      self.vacationdaysperyear = self.vacationdaysperyear + days
 
  #increase vacation days 
  def increase_vacation_days(self,days):
    if days > 0:
      self.vacationdays = self.vacationdays + days
 
  #increase vacation days by year
  def increase_vacation_days_yearly(self):
    self.vacationdays = self.vacationdays + self.vacationdaysperyear
 
  #take some vacation days
  def take_vacation_days(self,days):
    if days > 0 and self.vacationdays - days >= 0:
      self.vacationdays = self.vacationdays - days
    elif days <= 0:
      print("Vacation days taken must be greater than 0.")
    elif self.vacationdays - days < 0: 
      print(f"Employee does not have enough vacation days to take off {days} days.")

class Contractor(Person):
  def __init__(self,fname,lname,title,wage,contractorid):
    super().__init__(fname,lname,title)
    self.contractorid = contractorid
    self.hourlywage = wage
    
  #return contractor id
  def get_contractorid(self):
    return "Contractor ID: " + str(self.contractorid)
 
  #set hourly wage
  def set_hourlywage(self, wage):
    if wage > 0:
      self.hourlywage = wage
 
  #returns wage
  def get_hourlywage(self):
    return "${:,.2f}".format(self.hourlywage)
  
  #sets job wage if wage greater than 0
  def set_get_hourlywage(self,get_hourlywage):
    if get_hourlywage > 0:
      self.wage = get_hourlywage
 
con = Contractor('Temp','Emp','Developer',60,2)
print(con.get_firstname())
print(con.get_lastname())
print(con.get_contractorid())
print(con.get_jobtitle())
print(con.get_hourlywage())
print(con.set_hourlywage(50))
print(con.get_hourlywage())

Project 3: Finishing the Employee Class Program


import csv
import sys

FILENAME = "employees.csv"

#exiting the program
def exit_program():
    print("Terminating program.")
    sys.exit()

#read the employees from the file
def read_employees():
    try:
        employees = []
        with open(FILENAME, newline="") as file:
            reader = csv.reader(file)
            for row in reader:
                employees.append(row)
        return employees
    except FileNotFoundError as error:
        print(f"Could not find {FILENAME} file.")
        exit_program()
    except Exception as e:
        print(type(e), e)
        exit_program()

#write employees to files
def write_employees(employees):
    try:
        with open(FILENAME, "w", newline="") as file:
            writer = csv.writer(file)
            writer.writerows(employees)
    except Exception as e:
        print(type(e), e)
        exit_program()

#add employee to the list
def add_employee(employees):
    empid = input("Enter the employee ID: ")            
    sal = input("Enter the salary of the employee: ")
    employee = [empid,sal]
    employees.append(employee)
    write_employees(employees)
    print(f"Employee {empid}: {sal} was added.\n")

#display the list of employees
def list_employees(employees):
    for i, employee in enumerate(employees, start=1):
        print(f"{i}. Employee ID: {employee[0]} (${employee[1]})")
    print()

#delete an employee based on ID
def delete_employee(employees):
    found = False
    number = input("Enter in the employee ID: ")
    for i, employee in enumerate(employees, start=0):
      if (employee[0] == number):
        print(f"Employee was deleted.\n")
        employee = employees.pop(i)
        found = True

    if (found == False):
      print("Employee was not found.\n")
    else:
      write_employees(employees)

def display_menu():
    print("The Employee Salary List program")
    print()
    print("LIST OF COMMANDS")
    print("list - List all employees")
    print("add -  Add an employee")
    print("del -  Delete an employee")
    print("exit - Exit program")
    print()    

display_menu()
employees = read_employees()
while True:    
    command = input("Command: ")
    if command.lower() == "list":
        list_employees(employees)
    elif command.lower() == "add":
        add_employee(employees)
    elif command.lower() == "del":
        delete_employee(employees)
    elif command.lower() == "exit":
        break
    else:
        print("Not a valid command. Please try again.\n")
print("Ending Salary Program")

• External File

Uses an empty .csv file, call is in main.py code

  1. employee.csv

Unit 4

Project: Final Demonstration Program


#This game plays the game of dice called craps where
#Players would bet on the outcomes of a pair of dice rolls.
#If the sum of the dice is 2, 3 or 12, the player loses immediately.
#If the sum of the dice is 7 or 11, they win immediately.
#The purpose of the program is to simulate the results between two players

from player import Player

#Importing the datetime to get the current date and time
from datetime import datetime


#This function is created to play a single game and print out the results after each roll.
def playOneGame():

    player = Player()
    while not player.isWinner() and not player.isLoser():
        player.rollDice()
        print(player)
    if player.isWinner():
        print("You win!")
    else:
        print("You lose!")


#This function is created to play multiple games and outputs the results based on the number of games selected.
def playMultipleGames(number):
    #Initializing the variables
    wins = 0
    losses = 0
    winRolls = 0
    lossRolls = 0

    #Looping through the number of executions
    for count in range(number):
        player = Player()
        hasWon = player.play()
        rolls = player.getNumberOfRolls()
        if hasWon:
            wins += 1
            winRolls += rolls
        else:
            losses += 1
            lossRolls += rolls

    #Calculating the statistics
    print("The total number of wins is", wins)
    print("The total number of losses is", losses)
    if wins > 0:
        print("The average number of rolls per win is %0.2f" % \
            (winRolls / wins))
    if losses > 0:
        print("The average number of rolls per loss is %0.2f" % \
            (lossRolls / losses))

    print("The winning percentage is %0.3f" % (wins / number))
    print("The multi-game has been saved into the log.")

    logStats(wins, losses, winRolls, lossRolls, number)


#This function will log each multi game run to include the date/time and the details of the run
def logStats(wins, losses, winRolls, lossRolls, number):
    file = open("log.txt", "a")

    #Create a date/time object to get the current date and time
    now = datetime.now()
    #Formatting the output of the date and time to dd/mm/YY H:M:S
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    file.write("\n\ndate and time = " + dt_string)
    #Writing the statistics to a file
    file.write("\nThe total number of wins is " + str(wins))
    file.write("\nThe total number of losses is " + str(losses))
    if wins > 0:
        file.write("\nThe average number of rolls per win is " +
                   str(winRolls / wins))
    if losses > 0:
        file.write("\nThe average number of rolls per loss is " +
                   str(lossRolls / losses))
    file.write("\nThe winning percentage is " + str(wins / number))


#The main function as the point of entry
def main():
    #Play one game
    print("Running one sample game in full:")
    playOneGame()
    number = 0
    #Play multiple games based on the entry by the user

    #Loop while a valid number greater than 0 is entered
    while number <= 0:
        user_input = input("How many games would you want to have tested: ")

        #Check if a valid number is entered
        try:
            number = int(user_input)

            #check if the number entered is > 0
            if number <= 0:
                print("Please enter in a positive number.")
                number = 0
            else:
                playMultipleGames(number)
        except ValueError:
            print("Please enter in a number for the number of games.")


if __name__ == "__main__":
    main()

• External File 1

die.py


#Importing the randint module
from random import randint
#The class Die implements a six sided die
class Die:
    #The __init__ method is used to create a new instance of die with a default value of 1
    def __init__(self):
        self.value = 1
    #The roll method is used to set the value to a random number between 1 and 6
    def roll(self):
        self.value = randint(1, 6)
    #The getValue method returns the top face value of the die
    def getValue(self):
        return self.value
    #The __str__ method returns the string representation of the value of the die
    def __str__(self):
        return str(self.getValue())

• External File 2

player.py


#The player class is to simulate what a player is able to do.

#We will first import the class Die that we have created
from die import Die


#The class Player is the functionality that makes use of the Die class.
class Player(object):

    #The __init__ method will create a pair of dice and initialize the other variables.
    def __init__(self):
        self.firstDie = Die()
        self.secondDie = Die()
        self.roll = ""
        self.rollsCount = 0
        self.startOfGame = True
        self.winner = self.loser = False

    #The getNumberOfRolls will return the rollCount for the number of rolls
    def getNumberOfRolls(self):
        return self.rollsCount

    #The rollDice rolls both of the dice once.
    #Then it updates the roll, the won and the lost outcomes.
    #Lastly it returns a tuple of the values of the dice.
    def rollDice(self):
        #Increment rollCount by 1
        self.rollsCount += 1

        #Roll both dice
        self.firstDie.roll()
        self.secondDie.roll()

        #Set the tuple based on the values from each dice
        (v1, v2) = (self.firstDie.getValue(), self.secondDie.getValue())

        #Set the roll value to the value of the two dice
        self.roll = str((v1, v2)) + " total = " + str(v1 + v2)

        #The logic of the game is now running, if this is the first game
        if self.startOfGame:
            #Initial value is set to the the value of the two dice
            self.initialSum = v1 + v2
            self.startOfGame = False

            #If the initial sum is equal to 2, 3 or 12, the player is set to have lost
            if self.initialSum in (2, 3, 12):
                self.loser = True
            #If the initial sum is equal to 7 or 11, the player is set to have won
            elif self.initialSum in (7, 11):
                self.winner = True
        #If this is not the first game
        else:
            #We are now checking for the later sum of the values
            laterSum = v1 + v2
            #if it's not the start of the game and a 7 is rolled, the player loses
            if laterSum == 7:
                self.loser = True
            #If the player rolled the same sum as the first sum, the player wins
            elif laterSum == self.initialSum:
                self.winner = True
        return (v1, v2)

    #Returns True if the player has won
    def isWinner(self):
        """Returns True if player has won."""
        return self.winner

    #Returns True if the player has lost
    def isLoser(self):
        """Returns True if player has lost."""
        return self.loser

    #With the game, it's possible that both isWinner and isLower is false
    #If this is the case, the game is not finished and we must roll again until one is true.

    #Plays a full game and counts the rolls for that game.
    #This returns True for a win and False if the player loses
    def play(self):
        #We continue to roll as long as both are False
        while not self.isWinner() and not self.isLoser():
            self.rollDice()
        return self.isWinner()

    #The __str__ method will return the last roll as a string.
    def __str__(self):
        """Returns a string representation of the last roll."""
        return self.roll

• External File 3

log.txt

Some runtime data that can exist in the file:

date and time = 29/04/2022 18:38:11
The total number of wins is 1
The total number of losses is 2
The average number of rolls per win is 1.0
The average number of rolls per loss is 3.0
The winning percentage is 0.3333333333333333

date and time = 29/04/2022 18:38:34
The total number of wins is 2
The total number of losses is 0
The average number of rolls per win is 1.0
The winning percentage is 1.0

date and time = 06/05/2022 15:23:20
The total number of wins is 1
The total number of losses is 4
The average number of rolls per win is 1.0
The average number of rolls per loss is 2.25
The winning percentage is 0.2