Category Archives: Homework

Functions: Intro

Improving programs by using FUNCTIONS



Q: Why?
A:
To be able to reuse the code multiple times.
To make the program easier to read.
To organize the many lines of code.

Q: How?
A:
By keeping together related instructions in groups or blocks.
By writing a driver of instructions.

Parts of a good-style program:

1. Header
2. Imports
3. Functions
4. Driver: main
5. Input/output as comment

Let’s look at a general outline:

#####################################
#             Imports
#####################################

#####################################
#  Author's name
#  Assignment description
#  Python version
#  Date
#####################################

#####################################
#             Functions
#####################################

def one():
    # something

def two():
    # something else

#######################################
# Driver: control the flow of execution
#######################################

# main

one()
two()

Here is a working example:

#####################################
#  G. Elia
#  YI_GreetingFunct.py
#  Greeting program with functions
#  Python version 3.4
#  Date 10/22/15
#####################################

#####################################
#             Functions
#####################################

def welcome():
     # something
     name = input("What is your name? ")
     print ("Hi ", name, "! Nice to meet you ")
     
def howRU():
    # something else
     feeling = input(" How are you?  ")
     print ("Did you say you are are feeling ", feeling, "? ")

#######################################
# Driver: control the flow of execution
#######################################
# main
welcome()
howRU()

Another way to use a function

#####################################
#  G. Elia
#  YI_WeeklySchedule.py
#  My weekly activities
#  Python version 3.4
#  Date 10/22/15
#####################################

#####################################
#             Functions
#####################################

def morning(day):
     if day.startswith("M") or day.startswith("W"):
         print ("Come to school early morning for extra help ")
     elif day.startswith("Tu") or day.startswith("Th"):
         print ("Go to the weight room early morning to exercise ")
     
def afternoon(day):
    if day.startswith("M") or day.startswith("W"):
         print ("Swimming right after school ")
    elif day.startswith("Tu") or day.startswith("Th"):
         print ("Club meeting in room 242 right after school ")

#######################################
# Driver: control the flow of execution
#######################################
# main
morning("Monday")
afternoon("Monday")
morning("Tuesday")
afternoon("Tuesday")
##>>> 
##Come to school early morning for extra help 
##Swimming right after school 
##Go to the weight early morning room to exercise 
##Club meeting in room 242 right after school 
##>>> 

Functions: Circle Calc

Classwork:

Re-write the circle calculator program to use functions and add two more functions: sphereVolume
This function must:

calculate the volume of the sphere
print volume with a message

The other function, sphereSurfArea must:
calculate the surface area of the sphere
print the surface area with a message

#####################################
#             Functions
#####################################
def getRadius():
# prompt the user for radius
     radius = float(input(“What is the radius?”))
     print(“The circumference is “, 2 * pi * radius)
     return radius

     

def sphereVolume(radius):
    # calculate the volume of the sphere
    # print volume with a message

 

def sphereSurfArea(radius):
    # calculate the area of the sphere
    # print area with a message

 

#####################################
#   Driver: control the flow of execution
#####################################
#
#   main
#
radius = getRadius()
sphereSurfArea(radius)
sphereVolume(radius)

 

NOTE
import math # on first line
piVariable = math.pi

Functions: constructor

Constructor Functions and the type() function: Functions that have the same name as their data type and create objects or values of this data type are called constructor functions. How do you find the value’s data type?

pygame.PixelArray Data Type and the PixelArray() constructor function.

Advanced: switch and more on Scope – Functions



Python Variable scopes


#####################################################################
#  YI_MoreOnScopes1.py
#  Mrs. Elia
#  12/17/14
#  Local and global variables
#####################################################################
#
#  Definitions
#
#####################################################################

def intro():
    message = ' Welcome to my world '
    switch = 'off'
    print(switch)


def closing():
    switch = 'neither'
    print(switch)

## Main
switch = 'on'
print(switch)
intro()
closing()
print(switch)

Classwork:
1. Change the definitions so each of them reassign the value of the global variable switch.
2. Remove the print statement in each of the definitions but print the value of the global variable switch after each definition call.
This is what it should look like:

# Main
switch = 'on'
print(switch)
intro()
...
print(switch)
closing()
...
print(switch)

Output:
on
off
neither

 
Homework:
The output should be: It is a wonderful day. Fix the problem without removing the definitions and without adding print staments to the definitions.

#####################################################################
#  YI_MoreOnScopes2.py
#  Mrs. Elia
#  12/15/2014
#  Local and global variables
#
#####################################################################
#  Definitions
#####################################################################

def intro():
    word1 += "is a"
    word2 = "wonderful"
    return word2

def closing():
    word4 = "day."

## Main
word1 = "It"
message = word1
message = intro()
message = closing()
print(message)


# The output should be: It is a wonderful day.
# Fix the problem without removing the definitions and
# without adding print staments to the definitions.

The output should be:
It is a wonderful day.

Functions: with return

A “different” function: return

#####################################
#  G. Elia
#  GreetingFunct2_YI.py
#  Greeting program with functions and 
#  the return keyword
#  Python version 3.4
#  Date 10/22
#####################################
#             Functions
#####################################

def welcome():
     # something
     aName = input("What is your name? ")
     return aName
     
def howRU(aName):
    # something else
    print ("Hi ", aName, "! Nice to meet you ")
    feeling = input(" How are you?  ")
    print ("Did you say your are feeling ", feeling, "? ")

#######################################
# Driver: control the flow of execution
#######################################
# main
aName = welcome()
howRU(aName)

Homework:

The circle calcualtor program: CircleCalulations_YI.py

#####################################
#             Functions
#####################################
def getRadius():
     # prompt the user for radius

 

def sphereSurfArea(radius):
    # calculate the area of the sphere
    # print area with a message

 

#####################################
#   Driver: control the flow of execution
#####################################
#
#   main
radius = getRadius()
sphereSurfArea(radius)

List: phrase.replace(‘ ‘,’-‘)

A little help with the spaces in the phrase:


phrase = "have a good day"
phrase = phrase.replace(' ','-') # replace space with dash
newphrase = ''

blanks = '_ ' * len(phrase) # underscore plus space

for i in range(len(phrase)):
    newphrase += phrase[i] +' ' # add a space to each letter to match
                                # the underscores plus space


for i in range(len(blanks)):
    if newphrase[i] == '-':
        blanks = blanks[:i] + '-' + blanks[i+1:] # replace the underscore
                                              # with the corresponding dash

print(newphrase)
print(blanks)


##>>> 
##h a v e - a - g o o d - d a y 
##_ _ _ _ - _ - _ _ _ _ - _ _ _ 
##>>> 

Function: Mail Order System

Good programming style:

  1. Header (Description, author’s name, date and python version)
  2. Imports
  3. Functions definitions
  4. Driver (#main)
  5. Proper exit of the program with a message
  6. Input/output as comment

NOTE: Have a comment with “main” in it to indicate the beginning of instructions execution
mail-orders

A mail-order house sells five products whose retail prices are as follows: Product 1, $2.98, Product 2, $4.50, Product 3, $9.98, Product 4, $4.49, Product 5, $6.87.

Write a python program MailOrder_YI.py that reads a series of pairs of numbers as follows:

a) Product number;
b) Quantity sold.
Your program should use functions and good programming practices. It should calculate and display the total retail value of all products sold. Use a sentinel-controlled (like “yesNo”) loop to determine when the program should stop looping and display the final results.
Sample output:

Welcome to Mrs. “Elia’s Mail Order Clearing House”
Product 1, $2.98
Product 2, $4.50
Product 3, $9.98
Product 4, $4.49
Product 5, $6.87

Product number?: 1
Quantity?: 2
Do you want to continue?(yes/no): yes
Product number?: 2
Quantity?: 5
Do you want to continue?(yes/no): yes
Product number?: 3
Quantity?: 3
Do you want to continue?(yes/no): yes
Product number?: 4
Quantity?: 1
Do you want to continue?(yes/no): no
Total Price: $62

An example of a program outline Draft

#### Documentation
#### imports
#### 
#### function definitions
#### maybe welcome function definitions
#### maybe product and quantity function definitions with other features 
#### maybe tally function definitions
#### exit/goodbye function definitions
#### 
#### main
#### 
## call welcome function with prompt for input
## call function(s) with arguments from the welcome function
## call tally function?
## call exit function
#### 
## output: shopper activity
#### 

Algorithm: Mail Order and Variable Scope (Resource)

Classwork:
Scope: Local

#####################################
#      NO Imports
#####################################

#####################################
#  G.Elia
#  Mail Order application with functions
#  Python 3.5
#  today's date
#####################################

print("This is an order form for a mail-order house.")

#####################################
#      Functions' Definitions
#####################################

def initializeTotal():
    totalinit = float(0)
    return totalinit

def productPrompt():
    product = int(input("Product number? "))
    return product

def quantityPrompt(product):
    quantity = int(input("Quantity? "))
    if product == 1:
        subTotal = quantity * 2.98
    elif product == 2:
        subTotal = quantity * 4.50
    elif product == 3:
        subTotal = quantity * 9.98
    elif product == 4:
        subTotal = quantity * 4.49
    elif product == 5:
        subTotal = quantity * 6.87
    return subTotal

def final (total):
    print("Total Price:",total)

    
##############################################
# main - Driver: control the flow of execution
##############################################

yesNo = 'y'
totalInit = initializeTotal()
while yesNo == 'y':
    product = productPrompt()
    totalInit += quantityPrompt(product)
    yesNo = input("Do you want to continue? (y/n) ")
final(totalInit)

## input/output
##>>> 
##This is an order form for a mail-order house.
##Product number? 1
##Quantity? 2
##Do you want to continue? (y/n) y
##Product number? 2
##Quantity? 3
##Do you want to continue? (y/n) n
##Total Price: 19.46
##>>> 

localscope

List: Applications – food survey

List Applications

# Creating a histogram from a list of values.

values = []   # a list of values

# input 10 values from user
print ("Enter 10 integers:")

for i in range( 10 ):
   newValue = int( input( "Enter integer %d: " % ( i + 1 ) ) )
   values += [ newValue ]

# create histogram
print ("\nCreating a histogram from values:")
print ("%s %10s %10s" % ( "Element", "Value", "Histogram" ))

for i in range( len( values ) ):
   print ("%7d %10d  %s" % ( i+1, values[ i ], "*" * values[ i ] ))


ClassworkHomework:
Exercise 1: NoDuplicates_YI.py
Use a list to solve the following problem: Read in 20 numbers. As each number is read, print it only if it is not a duplicate of a number already read.
Make it an interactive program:
1. A message should be displayed when the user enters a number that has already entered as input.
2. As a way to validate no repeats it prints back the number.


Sample Output:
Enter a number: 2
2
Enter a number: 4
4
Enter a number: 5
5
Enter a number: 2
2 is a duplicate
Enter a number: 10
10


Exercise 2:
StudentPoll_YI.py
Write a python program StudentPoll_YI.py that uses a list to summarize data collected in a survey. Consider the following problem statement:

cafeteriafood

Sixteen students were asked to rate on a scale of 1 to 10 the quality of the food in the student cafeteria, with 1 being “awful” and 10 being “excellent”. Place the 16 responses in a list and determine the frequency of each rating.

Randomly assign 16 numbers between 1 and 10 to a list, survey, and use this list as an index of another list, ranking, to keep track of the count of the responses.
Create a histogram with the ranking data.

A little help…

ranking = [0,0,0,0,0,0,0,0,0,0,0]
survey = [1,5,3,4,1,1,1,2,1,2,1,3,4,5,1,7]

Do not  use "if's" statements. Instead use the following:

       ranking[ survey[ i ]  ] + = 1



Exercise 3: ScoreKeeper_YI.py
You are a score keeper for 20 ice hockey players. Implement the code to keep track of their scores using a list. Program accepts integers as input and it is called ScoreKeeper_YI.py. Simulate a game by entering a good number of scores.

icehockey

Sample output:

>>> 
... the game is on!!!
what player scored a goal? 3
what player scored a goal? 5
what player scored a goal? 3
what player scored a goal? 3
what player scored a goal? 5
still game on?y/n y
what player scored a goal? 5
what player scored a goal? 5
what player scored a goal? 5
what player scored a goal? 4
what player scored a goal? 6
still game on?y/n y
what player scored a goal? 5
what player scored a goal? 5
what player scored a goal? 7
what player scored a goal? 8
what player scored a goal? 1
still game on?y/n y
what player scored a goal? 5
what player scored a goal? 5
what player scored a goal? 3
what player scored a goal? 2
what player scored a goal? 5
still game on?y/n n

Creating a histogram from players:
Player      Goals  Histogram
      1          1  *
      2          1  *
      3          4  ****
      4          1  *
      5         10  **********
      6          1  *
      7          1  *
      8          1  *
      9          0  
     10          0  
     11          0  
     12          0  
     13          0  


Exercise 4: BingoNumKeeper_YI.py
You are in charge of keeping track of the numbers that are called out in a Bingo game. Using a list implement the code to keep track of the numbers. The numbers will be called until the board is completely filled up. You can think of this simulation as if the balls are replaced back for drawing again. In this program use the random feature to simulate turning the spherical basket with all the balls inside. It is similar to the game of Bingo but not quite. At the end of the program print the number of times a random number was called with a meaningful message. Name your program BingoNumKeeper_YI.py

bingobasket
bingo

Function: Algorithm – Tic Tac Toe

Classwork:
Open a new file, YI_PythonSyntax.py
Include the output and some comments from the following code:

# don't forget the header and comments

import random

# returning a list
x = 2
y = 3


def returnAList(a,b):
    a += 2
    b += 3
    return [a,b]

# Main
xyList = returnAList(x,y)

print(xyList)
print(xyList[0])
print(xyList[1])
# print either 0 or 1
for i in range(10):
    print(random.randint(0, 1),end = ' ')

# print the first letter
print()

print('yes'.lower().startswith('y'))

# adding items to any list
anyList = []
anyList.append(2)
anyList.append(3)

print(anyList)

sentence = 'it is a wonderful day'
sentence = sentence.split()
print(sentence)

sentence = ' '.join(sentence)
print(sentence)

# random choice
spaces = '1 2 3 4 5 6 7 8 9'.split()
print(spaces)
print(random.choice(spaces))
print(random.choice(spaces))
print(random.choice(spaces))

# what does this print?
print(None)


Screen Shot 2014-12-04 at 10.01.11 PM

Classwork:Tic-Tac-Toe.
Write an algorithm to play Tic-Tac-Toe. (Use pseudocode)
You are allowed to use the following functions from Al Sweigart’s program but your don’t have to:
isWinner(bo, le)
drawBoard(board)
isBoardFull(board)
getPlayerMove(board)
The rest must be implemented with your original and creative algorithm.

NOTE: this is a “what if” type of program. Think of all the moves ahead at each step. You can use as many “if’s” as you want!!
Keeping in mind the different locations in the board:
Screen Shot 2014-12-05 at 8.19.05 AM

Visit edmodo.com and answer these questions that could help you put together your algorithm. Remember it is your algorithm!

1. Before you commit to a move, what two things should your program check for?
2. What is the best spot on the board to start or to take the next safe move in the game?
3. What is the next best spot?
4. What is left when all the good spots are gone?
5. How many moves does it take to win, tie or lose a game of Tic Tac Toe? Best case, worse case and in an average case.

Make sure your algorithm addresses all these questions otherwise it would not be a good tool to help you write a smart AI program.

Programming Design:
1. What do you think is the best way to hold information about the space selected? Would you have 9 variables or a list?
2. Would you use while, for loop or both?

Homework:
Write first draft for TTT.py using pseudocode

NOTE: TO MAKE IT MORE INTERESTING AND INVITING TO THE PLAYER, MAKE THE FIRST COMPUTER MOVE RANDOM. However, it should be intelligent once the game is on.

Algorithm: Hangman Game


Hangman Game

HANGMANPICS = ['''

  +---+
  |   |
      |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()

def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]

hangman0.py

import random

### variables for reading purpose only

words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
#print(words)


def getRandomWord(wordList):
    # This function returns a random string from the passed list of strings.
    wordIndex = random.randint(0, len(wordList) - 1)
    return wordList[wordIndex]


print("a random word ",getRandomWord(words))

## run this code 4 times and copy the words here

##>>> abc = 'casa puerta tierra arbol'
##>>> abcList = abc.split()
##>>> abcList
##['casa', 'puerta', 'tierra', 'arbol']
##
##the split function turns a string with spaces into a list of words
##
##>>> abc = 'casa puerta tierra arbol'
##>>> abcList = abc.split()
##>>> abcList
##['casa', 'puerta', 'tierra', 'arbol']
##>>> ln = len(abcList)
##>>> ln
##4
##>>> import random
##>>> aNum = random.randint(0, len(abcList) - 1)
##>>> aNum
##3

Homework: study the displayBoard function the same way we did with getRandomWord

print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False

Homework: Understand the program by using the strategies we already learn, tracing, flowchart, pseudocode or by taking the program apart into smaller pieces.

List: TwoMatchingFiles_YI.py

Classwork: questions on edmodo.com

Homework: Given the following code

rect_a = 'a'
rect_b = 'b'
rect_c = 'c'
rect_d = 'd'
rect_e = 'e'
rect_f = 'f'
rect_g = 'g'
rect_h = 'h'

original_images = ['trees.bmp','sky.bmp','water.bmp','lilypads.bmp','trees.bmp','sky.bmp','water.bmp','lilypads.bmp']
    
rectangles = [rect_a,rect_b,rect_c,rect_d,rect_e,rect_f,rect_g,rect_h]


## Write a program in python, YI_twoMatchingFiles.py to prompt the user for two strings from 'a' through 'h'(in the alphabet). Use the variables shown above.
## 1. Check if the user guesses two matching bmp file names. Use a for loop to accomplished this.
## 2. Loop until the user found a match.
## 3. Prompt the user to quit? or play again?
## 4. If play again is selected, randomly scramble the bmp file names before the program continues.
## 5. If you already written your program for the matching cards, copy your code snippet
##    for this part of the program. 

Algorithm: Tic-Tac-Toe Comment

python version 3

Classwork:Tic-Tac-Toe.
Write an algorithm to play Tic-Tac-Toe. (Use pseudocode)
Keeping in mind the different locations in the board:

Classwork: Keep on working on your program, YI_TTT.py to implement your algorithm. Write the program for the algorithm only. There is no need to show the board at this stage. Prompt the user for a number from 1 through 9 and display back the number your program decides to occupy.

Keep in mind that you need to test your program multiple times to make sure it works properly

If your program works well, compare it to the one in the book and see if you can improve yours if it is necessary


Function: Algorithm – Tic-Tac-Toe by Al Sweigart


Screen Shot 2014-12-04 at 10.01.11 PM

Classwork:Tic-Tac-Toe.
Write an algorithm to play Tic-Tac-Toe. (Use pseudocode)
Keeping in mind the different locations in the board:
Screen Shot 2014-12-05 at 8.19.05 AM

A pseudocode you could follow:

start and reset the board

choose who goes first

start the while loop to play the game 

     if it is the player's turn, 
        draw the board
    prompt the user for move
    check if it is a valid move
    if the player wins, draw the board, and print a message.
    if player doesn't win, if all the spaces are taken, it is a tie, 
                               if not all spaces are taken, let the computer make a move
    if it is the computer's turn, choose a space
    if the computer wins, draw the board and print a message
    if the computer doesn't win, if all spaces are taken, it is a tie,
                     if not all spaces are taken, let the player make a move
    
    

Advice:
Write small parts of the program and test them before you move on to the next one.

# Name: G. Elia
# Description: This program demonstrates definitions, variables scopes
#              and how to implement a good exit from a loop
# Version: 3.2.5
# Date: 12/8

import random

# returning a list
x = 2
y = 3


def returnAList(a,b):
    a += 2
    b += 3
    return [a,b] # This returns a list

#  Main - This is where the execution of the program starts

playAgain = "y"

while playAgain.lower().startswith('y'):
    print("Before call to returnAlist def: x =",x,"y =",y)
    xyList = returnAList(x,y)
    print("This list is coming from returnAList def: ",xyList)
    print("Before update: x =",x,"y =",y)
    x = xyList[0]
    y = xyList[1]
    print("After update: x =",x,"y =",y)
    playAgain = input("Would you like to run this program again? yes/no ")

print("Good bye")


##>>> 
##Before call to returnAlist def: x = 2 y = 3
##This list is coming from returnAList def:  [4, 6]
##Before update: x = 2 y = 3
##After update: x = 4 y = 6
##Would you like to run this program again? yes/no y
##Before call to returnAlist def: x = 4 y = 6
##This list is coming from returnAList def:  [6, 9]
##Before update: x = 4 y = 6
##After update: x = 6 y = 9
##Would you like to run this program again? yes/no n
##Good bye
##>>> 

Reminder:

Turn in your friend’s name for Thursday’s Hour of Code activity.
One activity you might want to show your friend:

Screen Shot 2014-12-07 at 12.04.44 PM

Algorithm: Next Hangman

NOTE: IF YOU TURNED IN THE MAIL ORDER ASSIGNMENT AND DIDN’T GET A GRADE, LOOK FOR MY COMMENT ON THAT POST.

Classwork:
Complete missing assignments before you move on

Learning
Variable Scope
Global Scope and Local Scope
Parameters
Where the Program Really Begins: MAIN

Start reading the next chapter:
Screen Shot 2014-11-04 at 8.49.34 AM

Download the program and play with it. Pay special attention to details
Screen Shot 2015-11-09 at 3.06.05 AM

Functions: getGuess(alreadyGuessed) Hangman Part 3


Hangman Game

def getGuess(alreadyGuessed):
    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
    while True:
        print('Guess a letter.')
        guess = input()
        guess = guess.lower()
        if len(guess) != 1:
            print('Please enter a single letter.')
        elif guess in alreadyGuessed:
            print('You have already guessed that letter. Choose again.')
        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
            print('Please enter a LETTER.')
        else:
            return guess
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False

while True:
    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

    # Let the player type in a letter.
    guess = getGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters = correctLetters + guess

        # Check if the player has won
        foundAllLetters = True
        for i in range(len(secretWord)):
            if secretWord[i] not in correctLetters:
                foundAllLetters = False
                break
        if foundAllLetters:
            print('Yes! The secret word is "' + secretWord + '"! You have won!')
            gameIsDone = True
    else:
        missedLetters = missedLetters + guess

        # Check if player has guessed too many times and lost
        if len(missedLetters) == len(HANGMANPICS) - 1:
            displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
            print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
            gameIsDone = True

    # Ask the player if they want to play again (but only if the game is done).
    if gameIsDone:
        if playAgain():
            missedLetters = ''
            correctLetters = ''
            gameIsDone = False
            secretWord = getRandomWord(words)
        else:
            break

List: more about python lists


Deleting an item in a list:

>>> aList = ['one', 'two','three', 'four','five','six', 'seven']
>>> del aList[3]
>>> aList
['one', 'two', 'three', 'five', 'six', 'seven'] # 'four' is missing
>>> 
or 
>>> aList.remove('two')
>>> aList
['one', 'three', 'five', 'six', 'seven']  # 'two' is missing
>>> 

List of lists:

>>> twoLists = [['biology','chemistry','physics','horticulture', 'english','math','physed','spanish'],['period 1','period 2','period 3', 'period 4','period 5','period 6','period 7', 'period 8']]
>>> twoLists[0][0]
'biology'
>>> twoLists[1][0]
'period 1'
>>> 

Changing the text to lower case or upper case.

>>> aString1 = 'Hello, World'
>>> aString2 = aString1.lower()
>>> aString2
'hello, world'
>>> aString3 = aString1.upper()
>>> aString3
'HELLO, WORLD'
>>> 


Classwork:
Write a program, WordList.py with the following:
1. Create a list with 10 items and show how to delete a given item in the list.
2. Use the same list to delete the third item in the list.
3. Create a new list with two elements. Each element is also a list with nine elements.
4. Use two for loops to display the elements of this list.
Each element of this list should be displayed in a row of its own.

   biology chemistry physics horticulture english math physed spanish 
   period 1 period 2 period 3 period 4 period 5 period 6 period 7 period 8 
   

5. Use two for loops to display the elements in the list side by side:

biology      period 1
chemistry    period 2
physics      period 3
horticulture period 4
english      period 5
mathematica  period 6
physed       period 7
spanish      period 8

Here is code for string format

>>> print("%15s %14s" % ("hello","goodbye"))
          hello        goodbye

Clue for twoLists second part:

for i in range(len(twoLists[0])):
    for j in range(len(twoLists)):
        print( '\t',twoLists[?][?],' ',end='')
    print()

6. Print a sentence in lower case and then in upper case.

Classwork:

List: Slicing and Indexing with Connect 4

In the program hangman.py we learned how to slice a string and indexing in the previous assignments, pig latin and swapping letters.

The Connect 4 program can be written using strings.
Here is a little help:

# Using strings:
connect_board = '''|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|'''

# what do the indices look like?

# |  1  |  3  |  5  |  7  |  9  | 11  | 
# | 15  | 17  | 19  | 21  | 23  | 25  | 
# | 29  | 31  | 33  | 35  | 37  | 39  | 
# | 43  | 45  | 47  | 49  | 51  | 53  | 
# | 57  | 59  | 61  | 63  | 65  | 67  | 
# |  1  |  2  |  3  |  4  |  5  |  6  | 
In the last row you have the column numbers.


print('Empty board: ')
print(connect_board)
print( ' 1 2 3 4 5 6 ')
print('\nThe length of the string is ',len(connect_board))


print('')
yesNo = 'y'
while yesNo == 'y':
    column = int(input("Enter the column number "))
    offset = 1
    if column == 2:
        offset = 3
    elif column == 3:
        offset = 5
    elif column == 4:
        offset = 7
    elif column == 5:
        offset = 9
    elif column == 6:
        offset = 11
    empty = True
    position = offset + (14 * 4)
    while empty:
        if connect_board[position] == '_':
            connect_board = connect_board[:position] + 'A' + connect_board[position + 1:]
            print(connect_board)
            print( ' 1 2 3 4 5 6 ')
            empty = False
        else:
            position -= 14

    yesNo = input('More? ')

A test run could look like this:

Empty board: 
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
 1 2 3 4 5 6 


Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 4
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|_|_|
 1 2 3 4 5 6 
More? y
Enter the column number 6
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|_|A|
 1 2 3 4 5 6 
More? y
Enter the column number 5
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 2
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 1
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|_|A|A|A|
 1 2 3 4 5 6 
More? y
Enter the column number 3
|_|_|_|_|_|_|
|_|_|_|_|_|_|
|A|_|_|_|_|_|
|A|_|_|_|_|_|
|A|A|A|A|A|A|
 1 2 3 4 5 6 
More? 

Homework:
Write the pseudocode for the “Connect 4” program. Check edmodo.com for a little help on the pseudocode.

Algorithm: Agnes Grades

Assignment:

Agnes Gru keeps track of her grades with the help of a python program, YI_AgnesGrades.py. (YI in the program name represents your initials)

agnesgru
This is her schedule:

twoLists = [['biology','chemistry','physics','horticulture', 'english','math','phys ed','spanish'],['period 1','period 2','period 3', 'period 4','period 5','period 6','period 7', 'period 8']]


##        biology        period 1
##      chemistry        period 2
##        physics        period 3
##   horticulture        period 4
##        english        period 5
##           math        period 6
##        phys ed        period 7
##        spanish        period 8

She has Test grades, Homework grades and Classwork grades for all of her classes. These categories have different weights. Homework and Classwork represent each 30% of her grade. Her test category represents 40% of her marking period grade. Write YI_AgnesGrades.py program for Agnes using functions and what your learned from twoLists.
You program should

  1. Prompt Agnes for her grades. (This function should be activated after the program is successfully completed)
  2. Calculate each category average.
  3. Calculate her final grade for the marking period for each period.
  4. End the program by displaying each of her categories percentages and her marking period grade.

Make sure you use full sentences so Agnes can easily understand the results.

Use the following data with the purpose of developing your program and assessment:
Suggestion code:

# Program description
# author's name
# python version

##################
# Use these data
##################


#Period 1

#    15 homework grades
hwk1 = [86 ,76 ,79 ,72 ,78 ,77 ,90 ,86 ,79 ,71 ,89 ,79 ,98 ,87 ,96 ]
#    20 classwork grades
clwk1 = [71 ,86 ,76 ,86 ,88 ,79 ,85 ,98 ,75 ,87 ,76 ,99 ,75 ,85 ,74 ,71 ,77 ,80 ,85 ,76 ]
#    5 test grades
tst1 = [94 ,84 ,92 ,80 ,86 ]

#Period 2

#    15 homework grades
hwk2 = [90 ,97 ,74 ,80 ,93 ,75 ,84 ,94 ,94 ,86 ,79 ,88 ,100 ,80 ,71]
#    20 classwork grades
clwk2 = [84 ,92 ,93 ,83 ,86 ,82 ,84 ,98 ,76 ,80 ,74 ,71 ,95 ,99 ,73 ,78 ,70 ,80 ,73 ,72 ]
#    5 test grades
tst2 = [95 ,83 ,85 ,96 ,86 ]

#Period 3

#    15 homework grades
hwk3 = [88 ,74 ,88 ,100 ,82 ,77 ,85 ,90 ,98 ,89 ,99 ,96 ,81 ,75 ,85 ]
#    20 classwork grades
clwk3 = [83 ,79 ,94 ,71 ,92 ,90 ,97 ,96 ,77 ,89 ,100 ,80 ,95 ,85 ,78 ,73 ,95 ,75 ,92 ,70 ]
#    5 test grades
tst3 = [83 ,92 ,88 ,85 ,99 ]

#Period 4

#    15 homework grades
hwk4 = [82 ,76 ,85 ,81 ,80 ,73 ,73 ,100 ,96 ,97 ,74 ,78 ,91 ,90 ,82 ]
#    20 classwork grades
clwk4 = [97 ,98 ,71 ,90 ,79 ,90 ,72 ,84 ,73 ,83 ,87 ,91 ,81 ,74 ,76 ,91 ,82 ,82 ,87 ,75 ]
#    5 test grades
tst4 = [96 ,87 ,82 ,82 ,94 ]

#Period 5

#    15 homework grades
hwk5 = [77 ,95 ,79 ,75 ,97 ,90 ,76 ,94 ,93 ,84 ,89 ,95 ,74 ,91 ,97 ]
#    20 classwork grades
clwk5 = [96 ,91 ,91 ,86 ,92 ,76 ,72 ,70 ,87 ,84 ,87 ,87 ,76 ,83 ,72 ,99 ,82 ,76 ,75 ,79 ]
#    5 test grades
tst5 = [81 ,84 ,100 ,84 ,81 ]

#Period 6

#    15 homework grades
hwk6 = [94 ,91 ,71 ,82 ,73 ,78 ,84 ,82 ,75 ,83 ,93 ,98 ,86 ,100 ,76 ]
#    20 classwork grades
clwk6 = [81 ,86 ,95 ,92 ,83 ,80 ,97 ,84 ,96 ,90 ,97 ,82 ,79 ,77 ,74 ,94 ,78 ,85 ,80 ,74 ]
#    5 test grades
tst6 = [87 ,92 ,85 ,96 ,89 ]

#Period 7

#    15 homework grades
hwk7 = [88 ,83 ,97 ,82 ,78 ,89 ,99 ,74 ,71 ,86 ,81 ,72 ,91 ,87 ,95 ]
#    20 classwork grades
clwk7 = [97 ,83 ,99 ,100 ,97 ,88 ,92 ,73 ,88 ,82 ,96 ,76 ,95 ,75 ,93 ,95 ,93 ,72 ,93 ,95 ]
#    5 test grades
tst7 = [92 ,94 ,95 ,81 ,87 ]

#Period 8

#    15 homework grades
hwk8 = [100 ,88 ,92 ,74 ,82 ,88 ,75 ,80 ,93 ,82 ,85 ,85 ,97 ,94 ,78 ]
#    20 classwork grades
clwk8 = [97 ,85 ,90 ,73 ,73 ,99 ,96 ,100 ,99 ,77 ,99 ,88 ,78 ,83 ,96 ,84 ,89 ,93 ,99 ,90 ]
#    5 test grades
tst8 = [90 ,88 ,91 ,94 ,89 ]

##################
# functions
##################

def homework(hwk):
    ...
    return avg
        

def classwork(clwk):
    ...
    return avg

def test(tst):
    ...
    return avg


##################
# main
##################
...
while yesNo =="y":
    ...
    ...
    hwkAvg = round(homework(hwk))
    clswkAvg = round(classwork(clwk))
    tstAvg = round(test(tst))
    print('Averages are ',hwkAvg,'for Homework', clswkAvg, 'for Classwork',tstAvg, 'for Tests')
    ....
    print("The final quarter grade for period", periodx, "is", finalGrade)
    ...


NOTE: the three dots represent missing code that you need to fill in

Algorithm: Calorie and Fat Calculator

screen-shot-2016-11-16-at-10-32-19-pm

Write a python program, YI_FoodChart.py to provide calories and fat content in a selected number of foods.
– Choose 4 different categories of foods from the link attached to the image or any other resource you might want to use.
– Write a function for each of the categories with at least 5 foods choices.
– Display a menu and prompt the user for choices.
– Once the user is finished selecting, display the number of calories and the fat content.

Example:

1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category: 2

1. Rice, brown long-grain  Fat: 1.8 grams Calories: 216
2. Pasta, whole wheat      Fat: 1 gram    Calories: 214
3. Pasta, corn             Fat: 1.5 grams Calories: 210
4. Pasta, Quinoa           Fat: 0 grams   Calories: 200
5. Pasta, Soba (buckwheat) Fat: 1.5 grams Calories: 190
Choose the food: 4

Do you want to continue? y/n

if the answer is not:
   The total gram of fat is ... and the calories are ...
   Would you like to start again? y/n
else
    
1. Meats
2. Grains
3. Vegetables
4. Fruit

Choose a category:


NOTES:
– Include friendly and clear messages to the user.
– Include an introduction and goodbye or exit message.

Algorithm: Game – connect four

Classwork/Homework:
(Game: connect four) Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically suspended grid, as shown below.

connect4

The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a red or yellow disk alternately. In the preceding figure, the red disk is shown in a dark color and the yellow in a light color. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue). Here is a sample run:

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
———————————————

Drop a red disk at column (0–6): 0
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | | | | |
———————————————

Drop a yellow disk at column (0–6): 4

| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
|R| | | |Y| | |
.
.
.
.

Drop a yellow disk at column (0–6): 6 

| | | | | | | |
| | | | | | | |
| | | | |Y| | |
| | | |Y|Y|Y|R|
| | |Y|R|R|Y|Y|
|R|Y|R|Y|R|R|R|
———————————————
The yellow player won
Do you want to play again?

Write the two-player program, Connect4_YI.py. Display at every move the board as shown in the example above. Include a prompt to continue playing.

Your program should include:
1. Good documentation
2. An introduction message
3. Functions
4. Main
5. An end of game message
6. Input/output

What is good documentation?
Answer:

  1. Header with author’s name, assignment description, date and python version.
  2. Comments in each function. A short sentence will be sufficient.
  3. Comments for code snippets written for specific handling. An example might be checking if there are 3 in a row, or 4 in a row.
  4. Comments to indicate unusual or rare situations that don’t follow a pattern or repetition.

Advanced: Variable scopes



Python Variable scopes



Fix the problem:

#####################################################################
#  YI_MoreOnScopes3.py
#  Mrs. Elia
#  12/18/14
#  variables outside a definition and in other definitions
#
#####################################################################
#  Definitions
#
#####################################################################

def increase():
    num += 150

def decrease():
    num -= 50

## main
num = 100
print(num)
increase()
print(num)
decrease()
print(num)


## desired output:
## 100
## 250
## 200

Hint:

num = 100
print(num)
...increase(...)
print(num)
...decrease(...)
print(num)

Fix this problem

#####################################################################
#  YI_MoreOnScopes4.py
#  Mrs. Elia
#  12/18/14
#  variables outside a definition and in other definitions
#
#####################################################################
#  Definitions
#
#####################################################################

def two_terms():
    term1 = seed1 + seed2
    term2 = seed2 + term1
    return term1
    return term2


## main

seed1 = 3
seed2 = 5
two_terms()
print(...)

## desired output:
## 8 13

Hint:

## main

seed1 = 3
seed2 = 5
...two_terms(...,...)
print(...,...)

The output should be:
8 13

Algorithm: Tic-Tac-Toe to Battleship

Battleship

The next assignment is to write a python program YI_battleship1.py using the concepts and algorithms learned in Tic-Tac-Toe. In this version of the program you will only limit the board to be 3 x 3 and only 2 ships: one ship has 3 contiguous places and the other ship has 2 contiguous places. The ships could be placed horizontally or vertically. The purpose of this 1st version of the game is for the computer to guess the player’s ships positions. Your program’s algorithm will allow the player to enter the locations for the 2 ships( 2 and 3 places in length).

Classwork:
With a partner, play on paper our version of battleship but for two players.
1. Make sure you follow the rules of the game.
2. Play the game several times with the ships in different locations.
3. Pay attention to the strategy you use to find the ships and to sink them.
4. Categorize the strategies by the specific locations of the ships. (edmodo.com)
5. Write a short paragraph describing the strategy you use. Make sure your description is categorized by the different locations of the ships.(edmodo.com)

NOTE: You can use random to find a ship but once you have a hit, you should not select the next location using random. Develop an intelligent algorithm.

Homework:
Submit your answers to the following posts (edmodo.com)
1. What python feature would you use to hold the information about the ships locations? (e.g. lists, a list of lists, a dictionary, variables or something else)
2. Describe how you would access that information based on your choice in the previous question.
3. Given that a 3-place ship is located at the upper left corner of the board, write the pseudocode to sink it.

Algorithm: Battleship Day 4

Continuing to prepare for the Battleship program

Classwork:

1. Write the pseudocode to handle checking if there is a ship on one of the edges. What steps would your program follow?

Suggested Classwork:

2. Write a program, Edges4_YI.py to handle the following scenario:

– a hit is found on one of the edges locations on the 3 x 3 board and based on the user’s response write the code to find the ship and sink it.

The idea at every scenario is to find a pattern so you can minimize the code and reuse it.

– Use a list of three lists with 3 items each.
– Randomly select the edges where the program will place the ship.

Screen Shot 2015-02-02 at 7.32.57 AMScreen Shot 2015-02-02 at 8.06.20 AM

Reminder:

Requirements for an A:
1. Don’t forget the introduction with the rules of the game. Let the player know that the ships can only be placed horizontally or vertically.
2. The program has to be turned in on time.
3. The program must have the pygame component.
4. The program has to display at least one board.
5. The program has to handle two ships: 1 of two places and 1 of three places.
6. The program uses a smart algorithm after it finds the first occupied place.
7. The program’s quality of design
8. The program has to run until the game is over.

What will cause a drop in the grade?
The program is not able to tell if the ships overlap.
The program is not able to recognize invalid input.(Prompt the user for valid input)
The program is not able to detect duplicate entries. (Prompt the user for valid input)
The program has no header, no documentation and no output.
The program is over due.