Functions: an Introduction

Using definitions to write better style programs

 

###################################
#  Re-write this program using functions 
#  happy1_GE.py
#  
#  Mrs. Elia
#  python 3.9
#  10/8
#
###################################

name = input("what is your name? ")
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear ", name + "!")
print("Happy Birthday to you!")

##/My_Python_Programs/Unit2/happy1_GE.py
##what is your name? grace
##Happy Birthday to you!
##Happy Birthday to you!
##Happy Birthday, dear grace!
##Happy Birthday to you!
##>>> 

Let’s re-write it with functions:

###################################
#
#  happy2_GE.py
#  Using functions to design your program
#  Mrs. Elia
#  python 3.9
#  10/8
#
###################################

def happy():
   print("Happy Birthday to you!")

def sing(person):
   print("Happy Birthday, dear ", person + "!")
   
def main():
   name = input("what is your name? ")
   happy()
   happy()
   sing(name)
   happy()

main()



##/My_Python_Programs/Unit2/happy2_GE.py
##what is your name? grace
##Happy Birthday to you!
##Happy Birthday to you!
##Happy Birthday, dear grace!
##Happy Birthday to you!
##>>> 

Functions: Say Hello

Complete this assignment.

 

###################################################################
# Description: improve this program by using functions 
# Mrs. Elia
# 10/7
# python 3.9
#
###################################################################
aName = input("Hi! What is your name? ")
print "Hello ",aName, "! I hope you are enjoying your day!"

##>>> 
##Hi! What is your name? grace
##Hello grace! I hope you are enjoying your day!
##>>> 

Here is an outline of the changes:

#from
aName = input("Hi! What is your name? ")
print "Hello ",aName, "! I hope you are enjoying your day!"

# to functional programming
def hello(aName): # it prompts the user for a name
                  # it prints a message with the name

def main():       # it calls the only one function

main()  # execute by calling it

Read this article: Fostering Tech Talents in School. All of it.

Functions: Visualization

Classwork:

function_machines_composed_combined_mod
You will be drawing a sketch like this one
visualizing-functions
1. Draw a visualization for the Circle_Calulations_YI.py
2. Draw a visualization for the following assignment:

Write a program, Alge_Calc_WFunctions_YI.py to simulate a 4-function calculator.
Follow these guidelines:
a. Define dataInput function to prompt the user for two integer numbers and passes them to the other functions. Here is the syntax to pass more than one parameter: return [num1,num2]
b. Define function menu:

  1. Add
  2. Subtract
  3. Multiply
  4. divide

c. Define a function for each operation
def add(nums):

def subtract(nums):

def multiply(nums):

def divide(nums):

d. main should look like this:

Welcome to "My Python Calculator"
Would you like to 
1. Add
2. Subtract
3. Multiply
4. Divide
Select your option by entering the number 1

Enter a number 4
Enter another number 9
The sum of 4 and 9 is 13
Would you like to do another operation?  y/n 

Functions: Temperature Functions

Classwork/Homework:

Implement the following function fahrenheit to return the Fahrenheit equivalent of a Celsius temperature.

   F = (9/5) * C + 32

Use this function to write a program, TemperatureTables_YI.py that prints a chart showing the Fahrenheit equivalents of all Celsius temperature 0-100 degrees. Use one position of precision to the right of the decimal point for the results. Use the “%” to format your output properly.

Add a function celsius to return the Celsius equivalent of a Farenheit temperature.

    C = (5/9) * ( F – 32 )

Just like the previous function, print a chart with the Celsius equivalents of all Fahrenheit temperature 0-100 degrees. Use one position of precision to the right of the decimal point for the results. Use the “%” to format your output properly. The program should start with a menu to choose which temperature’s table the user wants to select
Welcome to Farenheit-Celsius Tables
Pres 1 for Farenheit 2 for Celsius and 3 to exit.

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: Pig Latin Project

NOTE: USE SLICING FOR THESE ASSIGNMENTS

Programming Project:
One of the rules for converting English to Pig Latin states: If a word begins with a consonant, move the consonant to the end of the word and add “ay”. Thus “dog” becomes “ogday”, and “crisp” becomes “rispcay”. If the word starts with a vowel, move the vowel to the end of the word and add the vowel followed by “way”. Example: “about” would turn into “boutaway” There are some variations to this last rule but it is ok if you do something else.

Write 2 python programs to convert from English to Pig Latin.
1. The first program, PigLatinWord_YI.py, should prompt the user for one English word. Your program then should display the word in Pig Latin.
2. The second program, PigLatinPhrase_YI.py, should prompt the user for a full sentence in English. Your program then should display the sentence in Pig Latin.

Recall what we learned from hangman.py
https://inventwithpython.com/chapter9.html

def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()
 
    print('Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()
 
    blanks = '_' * len(secretWord)
 
    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
        if secretWord[i] in correctLetters:
            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
 
    for letter in blanks: # show the secret word with spaces in between each letter
        print(letter, end=' ')
    print()
 

List: SwapOandE_YI.py and slicing

Classwork:

What does each of the following statements print?
Answer this question and explain what each of them does on edmodo.com ( Use IDLE )
NOTE: be clear
words = “happy face”
print(words[1:3])
print(words[2:-1])
print(words[:])
print(words[:5])
print(words[5:])
print(words[::3])

Write a short python program, SwapOandE_YI.py to replace an ‘o’ with an ‘e’. Prompt the user for a word and display the swapped version of it if it contains an o. Otherwise, the program will just display the original word. This program must use the slicing technique you learned in the Hagman program.
Example:

Type a word and I will replace any 'o' with an 'e': broom
The swapped word is: breem
>>> 

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: Tic-Tac-Toe Functions

February 9th, 2016

Tic Tac Toe program is due on 2/11/16.

Keep in mind programming style tips we have been discussion since the beginning of the year:
1. Documentation: COMMENTS – the header and a short line in each function definition.
2. Naming: use relevant names for variables and functions.
3. Test all possible scenarios to make sure every part of the program executes successfully.

Screen Shot 2016-02-11 at 8.13.56 AM

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.

A- 1 day late
B+ 2 days late
B 3 days late
B- 4 days late
C+ 5 days late
C 6 days late
C- 7 days late
D+ 8 days late
D 9 days late
D- 10 days late
F 11 days late
0 after 11 days pass the due date

I encourage you to talk to me ahead of time if this is a problem.

These two functions can be borrowed from the author’s program:


def drawBoard(board):
    # This function prints out the board that it was passed.

    # "board" is a list of 10 strings representing the board (ignore index 0)
    print('   |   |')
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('   |   |')
    print('-----------')
    print('   |   |')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
    print('   |   |')

and

def isWinner(bo, le):
    # Given a board and a player's letter, this function returns True if that player has won.
    # We use bo instead of board and le instead of letter so we don't have to type as much.
    return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
    (bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
    (bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
    (bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
    (bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
    (bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
    (bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
    (bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal

Advanced: Recursive Functions

Computer Number Systems

Recursive Functions

A definition that defines an object in terms of itself is said to be recursive. This theoretical mathematical topic serves as an introduction to recursive programming (which is supported by Pascal, but not by most BASICs). It also provides a framework for analyzing algorithms (determining the running time and/or space required) which contain loops or recursive sections.

Many expressions may be defined recursively in a very simple and elegant manner. The art of recursive thinking is an important skill. Applications of recursion appear in many areas of mathematics (factorials, compound interest, difference equations, etc.)

In this round recursive relationships will be shown not in the context of a programming language but usually in functional notation from mathematics or in an algorithmic description.

Consider the following recursive algorithm for painting a square:

  1. Given a square.
  2. If the length of a side is less than 2 feet, then stop.
  3. Divide the square into 4 equal size squares (i.e.,
    draw a “plus” sign inside the square).
  4. Paint one of these 4 small squares.
  5. Repeat this procedure (start at step 1)
    for each of the 3 unpainted squares.

If this algorithm is applied to a square with a side of 16 feet (having a total area of 256 sq. feet), how many square feet will be painted?

recursive1

recursive2

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

List: more advanced concepts in list


more advanced concepts in list

# Creating and accessing tuples.

# retrieve hour, minute and second from user
hour = int( raw_input( "Enter hour: " ) )
minute = int( raw_input( "Enter minute: " ) )
second = int( raw_input( "Enter second: " ) )

currentTime = hour, minute, second   # create tuple

print "The value of currentTime is:", currentTime

# access tuple
print "The number of seconds since midnight is", \
   ( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +
     currentTime[ 2 ] )


List methods:

listsMethods

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: