Category Archives: Lessons

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.

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 
##_ _ _ _ - _ - _ _ _ _ - _ _ _ 
##>>> 

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.

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.

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: Algorithm – Hangman Intro

Functions revisited
1. A function is defined with a name and a set of parentheses followed by a colon
2. A def is a function
3. It also has a key word: def at the left side, no indentation
4. It should be defined right after any imports
5. If the function needs a value from another function, it should be inside the
parentheses. This is called the argument
6. If there is more than one argument, it is called an argument list
7. If there are no arguments, it is called an empty argument list

hangman.py

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]

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


Classwork:
A. Write a short program, YI_printSpecial.py to display the shape on the screen using ‘ ‘ ‘:

   ___
 /     \
|       |
 \ ___ /
 

B. Write a short program, YI_wordList1.py as follows:
1) Use the words list with
2) the split() function and
3) print all the elements of this list by using a “while” or “for” loop


Homework:
Write a short program, YI_wordList2.py with the following specifications:
1) Must contain a list of words
2) Use the split() function
3) Have a random integer from 0 to 9 to pick a word.
4) Display 3 random words by using a “while” or “for” loop.

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.

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: Prepare for the Battleship

Continuing to prepare for the Battleship program

Classwork:

1. On a piece of paper decide in which edge you will place a 2 or 3-square ship.

2. Write a program, YI_4Edges.py to prompt the user for 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.
– 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 AM Screen Shot 2015-02-02 at 8.06.20 AM

Algorithm: Hangman Game using what you learned


Hangman Game
More on lists:

What is the output from the next code snippet?

>>> wordIndex = 2
>>> print(wordIndex)
2
>>> print(['biology','chemistry','physics','algebra'][wordIndex])
physics
>>> 

Displaying the Board to the Player

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()

Open a new window and create a python program, YI_displayBoard.py and copy the following code:

secretWord = 'apple'
blanks = '_' * len(secretWord)
correctLetters = 'l'
blanks

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()

Change the correctLetters variable and play with the program until you figure out how it works.
There is a post in edmodo.com for you to submit the file and to explain how the program works.


Homework:
Write YI_WheelOfFortune.py using what you learned from Hangman.py

1. Have the variable secretWord changed to secretPhrase and have a value assigned to it.
2. Prompt the user for a letter and display it in the right positions if it is in the secretPhrase. Otherwise, send a message to the player “incorrect” and keep track of how many times the player guesses the wrong letters.
3. Terminate the game after 5 tries. Display “game over” if it fails. Otherwise, displays “You are a winner!!” and add message with the prize(s)

Dictionaries

Classwork:

Two ways to create a dictionary in python:
1.

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}

2.

grocery2 = {}
grocery2['lettuce'] = 1.99
grocery2['tomato'] = 0.49
grocery2['onion'] = 0.35
grocery2['olives'] = 0.99
grocery2
{'olives': 0.99, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

Two ways to insert a new key-value pair to the dictionary:
1.

grocery1['lemon'] = 0.78
grocery1
{'olives': 0.99, 'lemon': 0.78, 'tomato': 0.49, 'onion': 0.35, 'lettuce': 1.99}

2.

grocery1.update({'potato':1.10})
grocery1
{'lemon': 0.78, 'onion': 0.35, 'potato': 1.1, 'olives': 0.99, 'tomato': 0.49, 'lettuce': 1.99}

Two ways to create a list of the keys of the dictionary:
1.

keys = grocery1.keys()
keys
dict_keys(['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce'])
for key in keys:
print(grocery1[key], end = '-')
0.78-0.35-1.1-0.99-0.49-1.99-

print(keys)
dict_keys(['onion', 'tomato', 'olives', 'lettuce'])
for key in keys:
print(key, end = ' ')
onion tomato olives lettuce

2.

keys_list = list(grocery1.keys())
keys_list
['lemon', 'onion', 'potato', 'olives', 'tomato', 'lettuce']
 

Two ways to create a list of values:
1.

values_list = []
for key in keys:
    values_list += [grocery1[key]]

values_list
[0.78, 0.35, 1.1, 0.99, 0.49, 1.99]
 

2.

val_list = grocery1.values()
val_list
dict_values([0.78, 0.35, 1.1, 0.99, 0.49, 1.99])
 

More to know:

x = 'lemon' in grocery
x
True

y = 'carrot' in grocery
y
False

How to delete a key-value entry pair from a dictionary:

grocery1 = {'lettuce': 1.99, 'tomato': 0.49, 'onion': 0.35, 'olives': 0.99}
del grocery1['lettuce']
grocery1
{'onion': 0.35, 'tomato': 0.49, 'olives': 0.99}

In edmodo.com
Homework:
Answer the following questions in edmodo.com

1. Do lists allow duplicate elements? what about dictionaries?

adict = {'a':1,'b':2,'a':4}
adict
{'a': 4, 'b': 2}

2. What are two ways to insert key–> value pairs into a dictionary.
3. Can different ‘types’ of keys be used in the same dictionary?
4. What happens when you try entering a value for a key that is already in the dictionary?
5. Create a scenario in which you would use a dictionary (without using the grocery example from these slides), and explain why you’d use a dictionary rather than a list.

Gota, you were right. Here is another way to add a key-value pair to a dictionary from stackoverflow.com

x = {1:2}
print x
{1: 2}

x.update({3:4})
print x
{1: 2, 3: 4}

Dictionaries: One more look

Dictionaries in python

Interesting code found in some python Scrabble programs:
scrabble

word = input("Enter a four letter word ")
word = word.upper()
letterNum = {'A':1,'E':1,'D':2,'R':2,'B':3,'M':3,'V':4,'Y':4,'J':8,'X':8}

What does the following line print?

print(letterNum['A'])

How was it used in the scrabble program?
One possible answer:

value = 0
for i in word:
    value += letterNum[i]

print(value)

Another possible answer:

letterValue = [0,0,0,0]
for i in range(4):
    letterValue[i] = letterNum[word[i]]

print(letterValue)

Classwork:
Work in python’s shell and copy and paste your work on edmodo.com’s post: Dictionary – Clwk 1/8 – Basic Concepts

Create a dictionary: ‘hello’ is the key and ‘hola’ is the value

spanishDictionary = {'hello':'hola','goodbye':'adios','one':'uno','two':'dos'}

Access a value with the key

word = input("what word would like to translate to spanish? ")
palabra = spanishDictionary[word]

Add a new key and value:

spanishDictionary.update({'blue':'azul'})
print(len(spanishDictionary))

Delete a key and the value:

del(spanishDictionary['blue'])

Replace the value of a key:

spanishDictionary['goodbye'] = 'chau'

Remove all items:

spanishDictionary.clear()

You can have a different type of value:

numbers = {'one':1,'two':2,'three':3,'four':4,'five':5}


print( numbers['two'] * numbers['three'])

You can have a different type of key and a different type of value:

numbers = {90:0,91:1,92:2,93:3}

print(numbers[92] * numbers[93])

Homework:
Add ten more words to the dictionary. Write a sentence in English and then translate it to Spanish or the language you chose. Add this new code to the original post.

Dictionaries: Mad Libs

Classwork: having fun with lists.

Screen Shot 2015-11-02 at 2.13.55 PM

Screen Shot 2015-11-02 at 2.14.33 PM

DIY Mad libs: Write your own mad lib program, YI_MadLibs.py using lists. You might want to have a theme.
Recipe:
1. Create 9 lists for adjectives, adverbs, nouns or plural nouns, verbs, exclamations, numbers, colors, and names. You can prompt the user for name to fill your list of names but all the other lists should already contained the items.

  1. Generate 9 random digits one for each of the lists. The range will depend on the number of items each list has.
  2. Create a sentence with the choice of each list. Make sure you put them in the right order!
  3. Prompt the user whether he or she wants to play again.

NOTE:
Adjectives: describes something (green, squishy, cute)
Adverbs: describes an action (quickly, carefully, silently)
Nouns: person, place or thing (car, house, child)
Plural noun: people, places or things (cars, houses, children)
Verbs: an action (run, jump, swim)
Exclamations: wow!, oh!, yuck!

Something to keep in mind:
Find the words for your lists in such a way that fit “nicely” into your theme sentence.

You can play with this site to get an idea:
Screen Shot 2015-11-02 at 2.07.39 PM

Dictionaries: MySpanishDictionary_YI.py

Dictionaries
Screen Shot 2016-01-06 at 1.34.15 AM

dictionary methods

Assignment:
Write a python program, YI_MySpanishDictionary.py using functions and dictionaries.

    Note: You can use a different language. Name your program according to the language you are using.

  • Hardcode a dictionary’s english word (key) and its spanish translation (value) for several english words (entries in the dictionary)
  • Display a menu for the user to choose:
    1. Translate an english word
    2. Display all english words in the dictionary
    3. Add new english/spanish entries
    4. Delete english/spanish entries.

  • Include an introduction
  • Exit the program properly
  • Do not forget to keep your code well documented
  • Pasting your code on the post is a requirement
  • Attaching your file is also a requirement

pygame: Olympic Rings

Graphics and Animations – Chapter 17

Homework:
Complete assignments

Classwork:
1. Write a python/pygame program, Olympic_Rings_YI.py. Draw the Olympic rings like the ones below.
Try to match up the colors and the relationship between the rings.

olympic_rings

Link for antialiased circles.
This link has more drawing options.

anti-alias

2. Write a pygame program, Cars_n_trucks_YI.py to draw a random number of different cars and/or trucks of different colors. Look at some examples bellow.
Draw composite basic shapes

Screen Shot 2014-02-26 at 5.49.41 AM Screen Shot 2014-02-26 at 5.49.46 AM Screen Shot 2014-02-26 at 5.49.54 AM Screen Shot 2014-02-26 at 5.50.01 AM

car3

truck4

Note 1: make them (at least 2 kinds of vehicles) colorful and filled in.
Note 2: create functions: drawCar and drawTruck. Both functions should take two parameters: the scaling factor (suggested factor should be less than 1) and translation constant so it can be placed in different locations. For translation only, the scaling factor should be 1 and for scaling only the translation constant should be zero.
Note 3: the cars and trucks should be placed on the surface in random locations.
Note 4: Keep on reading chapter 17

Geometry review:
Dialation:
Screen Shot 2016-02-22 at 8.14.05 AM

Translation:
Screen Shot 2016-02-22 at 8.16.36 AM

pygame: 1st Maze

Classwork:
Open pygameHelloWorld.py program and save it as Maze1_YI.py. Use what you learned in this program, rectangles, lines and text to draw a simple maze. Include the “Start” and “End” signs on the maze to indicate the beginning and end of the maze. Have a colorful but yet light background.

Open pygameHelloWorld.py program and save it as Maze2_YI.py. Use what you learned in this program, circles, lines, and text to draw a simple circular maze. Include the “Start” and “End” signs on the maze to indicate the beginning and end of the maze. Have a colorful but yet light background.

Warning!
Work on an easy maze like the one below
ClassicMaze

Resources:
For the second maze you will need to know how to draw arcs.

pygameDocumentation

Simple Example: Here is the code for a quarter of a green circle with radius 100

import math

pygame.draw.rect(windowSurface,RED,(50,50,100,100),5)
pygame.draw.arc(windowSurface, GREEN, (50,50,100,100),math.radians(0), math.radians(90),10)

quarterCircle

You can also draw the blue one:
twoQuarters

Can you guess the code for the blue arc in the bottom rectangle?
Explain what each parameter represents. Be concise and give different examples

pygame: Some advice to help you implement the cars and trucks assignment

Some advice to help you implement the cars and trucks assignment:

Consider a rectangle shape from the drawCar method as an example. The rectangle’s upper left corner is at (100,150), width is 100, and height is 50.

def drawCar(x,y,scale):
   pygame.draw.rect(surface, color,(100 + x, 50 + y, 100 * scale, 50 * scale)
   # more shapes completing the car drawing

Then in “main”:

vehicle = random.randint(1,2)
x = random.randint(20,30)
y = random.randint(10,20)
scale = random.random()

if vehicle == 1:
    drawCar(x,y,scale)
else:
    drawTruck(x,y,scale)

1. Define all definitions without x, y and scale.
2. Test them all
3. Include x and y and test your program again.
4. Include the scale and test your program again.
5. Include the random component

pygame: The Bouncing Blocks Algorithm

doRectsOverlap and isPointInsideRect:
Collision detection is figuring when two things on the screen have touched (that is, collided with) each other. For example, if the player touches an enemy they may lose health. Or the program needs to know when the player touches a coin so that they automatically pick it up. Collision detection can help determine if the game character is standing on solid ground or if there’s nothing but empty air underneath them.

In our games, collision detection will determine if two rectangles are overlapping each other or not. Our next example program will cover this basic technique.

overlapping-rectangles

Later in this chapter, we’ll look at how our Pygame programs can accept input from the user through the keyboard and the mouse. It’s a bit more complicated than calling the input() function like we did for our text programs. But using the keyboard is much more interactive in GUI programs. And using the mouse isn’t even possible in our text games. These two concepts will make your games more exciting!

Source Code of the Collision Detection Program
Much of this code is similar to the animation program, so the explanation of the moving and bouncing code is skipped. (See the animation program in the Animating Graphics Chapter for that.) A block will bounce around the window and bounce off each other.

On each iteration through the game loop, the program will read each Rect object in the list and the blocks will have a reaction.

The block is represented by a dictionary. The dictionary has a key named ‘rect’ (whose value is a pygame.Rect object) and a key named ‘dir’ (whose value is one of the constant direction variables like we had in last chapter’s Animation program).

overlapping-rectanglesVert

Use the functions below to make the block react differently when they are close to each other.

## BouncingBlocks.py

## copy the animation.py 

import pygame, sys, random
from pygame.locals import *

## add these two functions 

def doRectsOverlap(rect1, rect2):
    for a, b in [(rect1, rect2), (rect2, rect1)]:
        # Check if a's corners are inside b
        if ((isPointInsideRect(a.left, a.top, b)) or
            (isPointInsideRect(a.left, a.bottom, b)) or
            (isPointInsideRect(a.right, a.top, b)) or
            (isPointInsideRect(a.right, a.bottom, b))):
            return True
    return False

def isPointInsideRect(x, y, rect):
    if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
        return True
    else:
        return False

How to use the functions:

      if b['rect'].right > WINDOWWIDTH+15:
            # block has moved past the right side
            
            if b['dir'] == DOWNRIGHT:
                b['dir'] = DOWNLEFT
            if b['dir'] == UPRIGHT:
                b['dir'] = UPLEFT


        ##### add the call to the doRectsOverlap by pairs of blocks
        ##### Make sure the indentations make sense!!!
       if doRectsOverlap(b3['rect'], b2['rect']):
          if b3['dir'] == UPLEFT:
                b3['dir'] = DOWNLEFT
           if b3['dir'] == UPRIGHT:
                b3['dir'] = DOWNRIGHT

       #### what other pairs do you want to check for overlaps??? 

        # draw the block onto the surface
        pygame.draw.rect(windowSurface, b['color'], b['rect'])

  # draw the window onto the screen
    pygame.display.update()
    time.sleep(0.02)

pygame: pygame.Rect

Classwork:
Discussions on concepts you should know:

  • pygame is so advanced that even the pygame module has its own modules
  • pygame.locals module contains many constant variables QUIT, K_ESCAPE and many more.
  • pygame.init() must always be included in your pygame programs
  • pygame.display.set_mode((500, 400), 0, 32) creates a pop up window of width 500 pixels and height 400 pixels. 0 is used for more options and color 32 for depth. If you want to know more about this syntax, here is the link
  • Surface object represents pop up windows.
  • Differences between values and reference values: a list variable name is actually a reference, the contents of the list are the values.
  • RGB referes to Red, Green and Blue
  • This method: basicFont.render(‘Hello world!’, True, WHITE, BLUE) creates a Surface object with the text drawn on it
  • Anti-aliasing can make your text and lines look blurry but smoother
  • Anti-aliasing

  • A pygame rectangle is an object: Rect((left, top), (width, height)).
    pygame.Rect(left, top, width, height)
  • Documentation

  • pygame.Rect objects have attributes, variables that are associated with an object
  • rectanglesattributes

  • pygame.Rect objects have behaviors, methods that are associated with an object
  • pygamerectangles

  • But you can draw a rectangle with this syntax:pygame.draw.rect(windowSurface, color,( x , y , width, heigth))
    where x is the x coordinate and y is the y-coordinate of the upper left corner of the rectangle.

  • If you are including text in your pygmae window,
    text = basicFont.render(‘Hello world!’, True, WHITE, BLUE)
    textRect = text.get_rect()
    The next step then is to render the text by using the blit method:
    windowSurface.blit(text, textRect)
  • Important: before blit-ting and before drawing: windowSurface.fill(WHITE)
  • In Pygame, nothing is drawn to the screen until the pygame.display.update() function is called.
  • Finally, no pygame should miss the next lines:
    while True:
    ….for event in pygame.event.get():
    ……..if event.type == QUIT:
    …………pygame.quit()
    …………sys.exit()
  • The End

Homework:
Read chapter 17 topics we covered in class.