curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · web vieware short,...

44
AOIT Introduction to Programming Lesson 10 Advanced Sequence Manipulation Student Resources Resource Description Student Resource 10.1 Analysis: The Hangman Program Student Resource 10.2 Reading: Advanced Sequence Manipulation Student Resource 10.3 Notes and Practice: Advanced Sequence Manipulation Student Resource 10.4 Guide: Minor Project Planning and Implementation Student Resource 10.5 Design and Coding: Hangman Program Student Resource 10.6 Test Plan: Hangman Program Student Resource 10.7 Assessment: Individual Contribution Copyright © 2009–2015 NAF. All rights reserved.

Upload: others

Post on 03-Aug-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to Programming

Lesson 10Advanced Sequence Manipulation

Student Resources

Resource Description

Student Resource 10.1 Analysis: The Hangman Program

Student Resource 10.2 Reading: Advanced Sequence Manipulation

Student Resource 10.3 Notes and Practice: Advanced Sequence Manipulation

Student Resource 10.4 Guide: Minor Project Planning and Implementation

Student Resource 10.5 Design and Coding: Hangman Program

Student Resource 10.6 Test Plan: Hangman Program

Student Resource 10.7 Assessment: Individual Contribution

Copyright © 2009–2015 NAF. All rights reserved.

Page 2: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.1

Analysis: The Hangman ProgramStudent Names:_____________________________________________________ Date:____________

Directions: After you watch the Hangman program demonstration, analyze how the programming constructs in the following table might be used in the Hangman program. Then fill in the missing information in the table. The first row has been done for you.

Programming Construct Construct Type

How You Think Construct Could Be Used in Hangman

isalpha() String Method

To test user input to be sure it is alphabetic

lower()

animal_words("horse","cow","dog")

def display_figure(bad_guesses):

guesses=word_len*['_']

if len(letter)==1 andletter.isalpha():

Copyright © 2009–2015 NAF. All rights reserved.

Page 3: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.2

Reading: Advanced Sequence Manipulation

This presentation does the following:

• Reviews and categorizes the key Python methods and functions used with sequences (strings, lists, and tuples) that have already been introduced

• Introduces new string methods and functions that will be used in programming projects yet to come in this course and puts them into the correct categories

• Provides an opportunity for additional analysis and practice for the methods and functions that will be used in the minor project (Hangman program)

Copyright © 2009–2015 NAF. All rights reserved.

Page 4: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

In this presentation, you’ll learn how to use both methods and functions to make sequences more powerful. To begin, let’s review the difference between a method and a function.

Methods use object-oriented notation. For example, string.isalnum() is invoking the isalnum method of the String class. This works with "124".isalnum() because of a concept called inheritance. Because "124" is a string, it inherits all of the methods that belong to the String class. If you did this:

test='124'

test.isalnum()

It would also work, because the assignment statement set test to a string, which means that test has inherited all of the methods for the String class.

A function is not part of a class, so you don’t need to specify class in the call, which means you’re not using object-oriented notation. So, for example, len('124') is all you would need.

Copyright © 2009–2015 NAF. All rights reserved.

Page 5: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Sequences (strings, lists, and tuples) are common constructs in Python programs. It’s the methods and functions applied to these constructs that make them powerful.

This presentation reviews and categorizes some of the methods and functions you have used in past programs, and it introduces a few new methods and functions you will be using in the Hangman program.

Copyright © 2009–2015 NAF. All rights reserved.

Page 6: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

String-testing methods test to see whether a string has a certain form, and they return True or False.

You have seen these methods before in the New Password program, where you tested the user’s proposed password to be sure it followed the password formation rules.

You will see the string.isalpha() method again in the Hangman program.

The method string.islower() tests to see whether the string is all lowercase.

Copyright © 2009–2015 NAF. All rights reserved.

Page 7: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Case-changing methods change the case of a string. Rather than simply testing, like the string-testing methods, they operate on the string and return the changed string.

You have seen these methods before in the Menu and Vacation programs, where you changed the case of some of the text.

You will see the string.lower() method again in the Hangman program.

The method string.swapcase() swaps the case from lowercase to uppercase, or vice versa.

No method ever changes a string in place. Rather, it returns a new string derived from the old one.

Copyright © 2009–2015 NAF. All rights reserved.

Page 8: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

String formatting methods format string (or text) output, either to the Python IDLE screen or to printed output.

You have seen these methods before in the Menu program, and you might use them again in formatting the text art in Hangman.

The method to right-justify is string.rjust(width). To right-justify means to line up the string (text) with the right side of the available print space.

Copyright © 2009–2015 NAF. All rights reserved.

Page 9: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Escape sequences are used in Python programs to print characters that have a special meaning (for example, quotation marks that are used to delimit strings) or that cannot be indicated with single keyboard characters or words (like \n to direct Python to put printed output on a new line).

Escape sequences were introduced in the Vacation and Menu programs, and they might be useful in the Hangman text art.

The escape sequence to print a single quote is \'.

Copyright © 2009–2015 NAF. All rights reserved.

Page 10: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

The most common and useful string-searching method is find(), which finds the first occurrence of a substring in a string.

The find() method is used in Hangman to check whether the letter just guessed by the user is in the mystery word. If the letter is in the word, the method will return the zero-based position of the letter. If the letter is not in the word, the method will return -1. The program branches one way or another based on the return value.

Copyright © 2009–2015 NAF. All rights reserved.

Page 11: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

In the Hangman program, you want to be sure the letter guess doesn’t have any leading or trailing blanks (that is, blanks at the beginning or the end of the string) that the player inadvertently typed in.

To ensure that this is true, you use the strip() string method to strip off the blanks (if they are there). (The strip() method doesn’t return an error if the blanks are not there; it only strips off whatever blanks happen to be there.)

"Happy Birthday! ".strip() returns this:

Happy Birthday!

This type of function is more useful than it may appear. A lot of data that is read in from files will have blank spaces at the beginning or end of the string. This can cause many problems for comparisons. The string-stripping and string-replacement methods help to easily remove the blanks.

Copyright © 2009–2015 NAF. All rights reserved.

Page 12: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

You have seen several list and tuple methods and functions recently in the Shuffle Cards program.

The append() function was used in Shuffle Cards to append each card string in turn to the end of the list of cards.

You used the pop() built-in list method to return the first card in the deck to the calling function and remove it from the list.

If you wanted to return the last card in the deck instead, you would code this:

return deck.pop()

Copyright © 2009–2015 NAF. All rights reserved.

Page 13: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

In the Hangman program, the current state of the mystery word with the player’s correct guesses inserted is constantly being printed out. For example, if the mystery word is hyena and the player has just guessed a, the player needs to get a printout of “_ _ _ _ a.” If the mystery word is cat and the player has already correctly guessed c and a, the user needs to see “c a _.”

The join() method has a format of string.join(list). In the Hangman program, in the example on this slide, the string is re-created each time the user guesses, so there is no string to join to. Therefore, the string is designated as a null string ('').

In the second example on the slide, the word (theword) is a tuple, and its length is being assigned to variable word_len.

If the mystery word is antelope, the value assigned to word_len is 8.

Copyright © 2009–2015 NAF. All rights reserved.

Page 14: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

String methods have been used extensively in prior programs. In future programs, especially the minor project (Hangman) and the culminating projects, string methods, plus list and tuple methods and functions, will play a major role.

To keep track of all these common and powerful programming constructs, it is helpful to categorize them by what they do and how they operate.

This course’s QuickStart Guide contains additional information about these methods and functions.

Copyright © 2009–2015 NAF. All rights reserved.

Page 15: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.3

Notes and Practice: Advanced Sequence ManipulationStudent Names:_____________________________________________________ Date:____________

Directions: While you are watching the presentation called “Advanced Sequence Manipulation,” take notes and answer the questions in Part 1. Then do the programming exercises in Part 2.

Part 1: Notes and AnalysisAs you watch the presentation, fill in the table below, and answer the questions after the table.

Category Definition Examples (One to Two per Category)

Program(s)

String-testing methods

Tests to see whether a string has a certain form

s.isalnum()

s.isnumeric()

New Password

Hangman

Case-changing methods

Menu

Vacation

String-formatting methods

Escape sequences

String-searching methods

String-stripping method

String-replacement method

List/tuple methods/functions

(Make sure one of your examples is the print statement from slide 11)

1. String-testing methods test to see whether a string has a certain form. What do you think s.islower() does?

Copyright © 2009–2015 NAF. All rights reserved.

Page 16: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

2. Case-changing methods change the case of a string. What do you suppose s.swapcase() does?

3. String-formatting methods format string (text) output. What do you think is the method to right-justify? What does right-justify mean?

4. find() is the most useful string-searching method. What does "abcd".find("e") return?

5. The string-stripping and string-replacement methods change strings. In the space below, write a Python statement to strip the following string: " Spring has arrived! ". What does the method strip out?

6. Hangman uses several list and tuple methods and functions. Given the statement word_len = len(theword) with theword being "antelope", what value is assigned to word_len?

Part 2: Independent ExercisesFollowing the directions in each of the sections below, create various code sequences that you will be using in the Hangman program.

User-Defined Function (prompt_for_letter())Follow these steps to produce the prompt_for_letter() user-defined function (write your code in the space that follows):

● Begin with an empty print statement (to produce a blank line).

● Assign the Hangman player’s guess to the answer string variable. Use str(input()) for the prompt and give the player an appropriate prompt (for example, “Guess a letter in the mystery word: ”).

Copyright © 2009–2015 NAF. All rights reserved.

Page 17: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

● Remove any leading or trailing blanks the player may have inadvertently typed in. (Hint: Don’t forget that you need both the appropriate string method and an assignment statement assigning the stripped input back into the answer variable.)

● Convert the answer to all lowercase letters. (Hint: See the hint above.)

● Print another empty line.

● Return the answer to the player.

Code to Manipulate the Mystery Word and Individual Letter GuessesFollow these steps to produce various independent lines of code that you will need in Hangman to manipulate the mystery word and letter guesses (that is, the underscores representing the mystery word). Write your code in the spaces below each instruction:

● Assign mystery word "antelope" to variable theword.

● Write a statement to return the length of theword and assign it to variable word_len.

● Create a list of underscore strings that is equal in length to the mystery word, and assign it to variable guesses. (Hint: The right side of your assignment statement is word_len*['_'].)

Copyright © 2009–2015 NAF. All rights reserved.

Page 18: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

● Write the for-loop header for a loop in which range is word_len. (Analysis question: What will range be when the mystery word is "antelope"?)

● Write the print statement that joins guesses into a single string. (Hint: Look at the print statement you wrote in the table in Part 1 of this worksheet.)

Additional Code with len() and find()Follow these steps to produce various independent lines of code that you will need in Hangman. Write your code in the spaces below each instruction:

● Write the first line of branching code that tests whether the player has guessed a single letter of the alphabet. (Hint: Your statement should start with if, the variable is letter, and you need two string methods, one of which is len().)

● Write a line of code to test whether the letter that the player just guessed has already been picked: check whether it is in the string of previously guessed letters. The letter picked is letter; the string of previously guessed letters is letters_tried. (Hint: You need to use the find() method.)

● Write two statements. The first statement tests whether the letter just guessed is in the mystery `word by searching for it using the find() method. Store the result in the sequence found_indexes. (You need a sequence because the guessed letter might be in the word multiple times.) The second statement (a branching header) begins the branch to follow if found_indexes is not in the mystery word. (Hint: Do you remember from the presentation what is returned by find() when the condition is False?)

Copyright © 2009–2015 NAF. All rights reserved.

Page 19: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.4

Guide: Minor Project Planning and Implementation Student Names:_____________________________________________________ Date:____________

Directions: Follow the specific instructions in each of the parts of this guide.

Part 1: Chunking and Staging a Complex Project

What Is Chunking and Staging?The methodology you will use in creating the Hangman program is often called “programming in chunks and stages.” Chunking and staging is done in relatively complex programs (and your Hangman program fits into that category) to do the following:

● Split up the tasks among multiple programmers

● Reduce complexity at the beginning and increase it only bit by bit, so that bugs are easier to find and fix

In programming, chunks are short, relatively self-contained (that is, not completely dependent on another part) pieces of code. Examples would be user-defined functions, or code to print out informational messages or rules of a game to the user. The various sections of programs you have been using for some time (for example, the environment setup section, initialization section, and processing section) are examples of chunks.

Staging means deciding which tasks need to be done first, second, and later in the project. For example, putting in the commented skeleton code that you have used in the past few programming projects should be done early in the project, because those pieces are placeholders for the various chunks of actual code that need to be put in their proper places as they are created. Obviously, system testing (where all the chunks of code are integrated into the program) needs to be done near the end.

Your team specialists will be responsible for certain chunks of code, most of which fit logically into one specialty role or another. However, as you design your program, you need to be sure that someone in the team is responsible for every piece of code that is required, whether or not it fits precisely into a specialty area.

How Will Chunking and Staging Be Used in the Minor Project? Following the specific timeline defined in the project schedule in Part 2 of this guide, your team will:

● Set up the program in meaningful sections, as you have done with other recent programs (for example, set up the prolog, environment setup section, and defined function section)

● Design the code in “chunks” (the specialists will do the chunks that relate to their specialty, and perhaps a few others, as required)

● Do a team review of the chunks

● Code the chunks

Copyright © 2009–2015 NAF. All rights reserved.

Page 20: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

● Add temporary code (which will be given to you in the program design document) to test the chunks, and run the program

● Debug and fix whatever problems occur

● Substitute the central programming logic for the temporary code

● Run, debug, and fix again

● Create the test plan and do informal testing

● Do formal testing and report the results

● Debug and fix again

What Can You Use as a Model for This Approach?You have used this approach in several prior programs—the last one was Guess-A-Number. In that program and a few prior ones, the programs were “staged” into basic, intermediate, and advanced versions, each version building on the one before it.

To help you better understand the important concepts of chunking and staging, which is often used in the professional programming world, go back to Guess-A-Number and analyze how it was staged into basic, intermediate, and advanced programs.

That way, you and your team will be better prepared to handle the staging of the Hangman program and to plan and integrate staging and chunking into your culminating project.

Open Student Resource 8.8, Design and Coding: Guess-A-Number Program (it should be in your notebook), and answer the following questions:

What was the focus and what were the key “chunks” of the Guess-A-Number basic program? (Hint: Look at the problem statement and requirements, as well as at the program sections.)

What was the focus and what were the key chunks of the Guess-A-Number intermediate program?

What was the focus and what were the key chunks of the Guess-A-Number advanced program?

Copyright © 2009–2015 NAF. All rights reserved.

Page 21: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Based on what you know already about the Hangman program, how do you think staging, chunking, and specialization will apply to your approach to the minor project? (List three to five bullet points.)

Part 2: Minor Project MilestonesThe table below shows the project milestones (listed by program “stages”) of the key activities in this lesson.

Add the actual dates that the milestones need to be completed.

As the minor project progresses, and following specific instructions from your teacher, your team project lead needs to add status information about your team’s progress in meeting the deadlines. The project lead also needs to ask your teacher to initial your status report at the end of each class period.

Activity, Milestone Class Period

Due Date(s)

Status (To Be Completed by Team Project Lead)

Teacher Initials

STAGE 1: Plan Minor Project

Team members choose code specialty roles.

Team codes the program skeleton.

2

STAGE 2: Design Chunks

Specialists design the chunks of code for which they are responsible.

Team reviews the chunk designs.

3

STAGE 3: Code Chunks

Specialists code the

4

Copyright © 2009–2015 NAF. All rights reserved.

Page 22: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

chunks.

Team integrates the chunks into the Hangman program (except for the processing section).

Team reviews the code chunks, looking for bugs.

STAGE 4: Unit-Test Chunks

Team adds temporary supplied debugging code into the processing section.

Team runs the program and fixes any bugs.

5

STAGE 5: System-Test Program

When chunks are bug-free, team replaces temporary debugging code with final processing code.

Team runs program and fixes bugs.

5

STAGE 6: Debug

The team continues to system-test, debug, and fix.

6

STAGE 7: Write Test Plan

Team writes the program test plan.

6

STAGE 8: Test Program

The programming teams test each other’s programs and report results.

7

STAGE 9: Share, Self-Assess, Reflect

Teams share programs.

Students write self-assessments and reflections.

7

Copyright © 2009–2015 NAF. All rights reserved.

Page 23: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Teams turn in minor project packages for formal assessment by teacher.

Part 3: Choosing Programming SpecialtiesYou have had some time in this lesson and the prior one to learn and think about the specialist roles for the Hangman programming project. Although your entire team is responsible for creating a high-quality project in the time allowed, each of the specialists will take the lead on designing and coding one of these three key areas of the program:

● Text and text art

● User-defined functions

● Initialization and central program logic

Decide as a team which of your team members would be best at each of the three roles, and write their names in the following table.

Specialist Role Name

Text and text art

User-defined functions

Initialization and central programming logic

Copyright © 2009–2015 NAF. All rights reserved.

Page 24: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.5

Design and Coding: Hangman ProgramStudent Names:_____________________________________________________ Date:____________

Directions: Design and code the Hangman program that you will submit for your minor project. Specific instructions are provided in each section of the worksheet, below.

Problem StatementWrite a Python program to play the traditional (paper-and-pencil) game of hangman, in which two players take turns trying to guess a word, letter by letter. The players get seven guesses each. For each incorrect guess, the player acting as game host draws part of a stick figure—head, neck, body, two arms, and two legs—on a scaffold. After the guessing player is “hanged,” the players trade roles and the game starts over.

In the computer version of the game, the computer always acts as “host,” and one or more players try to guess the word.

Requirements and Program Design (Algorithm)General RequirementsWhich team member will put this code into your program?

(Note: You don’t have to type the skeleton code. Use sample file program_template.py as a starting point.)

● Open a new window in Python IDLE.

● Create the Hangman program skeleton with the sections shown in the table below. Name the program hangman.py and save it in your Lesson 10 folder.

Program Section Notes

################################ PROLOG SECTION# hangman.py# Program to play the traditional game of hangman.# The computer picks a word and the player# has to guess it before making 7 wrong# guesses of letters in the word.# Each time the user makes an incorrect guess# of a letter, one more body part gets added# to the text graphic.# Uses multiple user-defined functions.# Uses branching and looping.# (today's date goes here)# (programmer names go here)# (tester names go here)# Possible future enhancements:# Unresolved bugs:###############################

This section contains important information about the program.

The comments give an overview of how the game will be played.

Copyright © 2009–2015 NAF. All rights reserved.

Page 25: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

################################ ENVIRONMENT SETUP SECTION# Imports: random###############################

# code goes here

In this section, you’ll put in a statement to import the Python random number routines.

################################ FUNCTION DEFINITION SECTION# Definitions: print_game_rules(),# display_figure(), prompt_for_letter()###############################

# code goes here

In this program, you’ll define three functions: print_game_rules(), which prints the game rules for the user; display_figure(), which displays the appropriate version of the scaffold and “hanging” stick figure; and prompt_for_letter(), which prompts the user for the next letter guess.

These functions are all called from the main processing section of the program.

################################ PROCESSING INITIALIZATION SECTION###############################

# code goes here

In this section is setup information for the program.

In this program, there are many initialization statements.

################################ PROCESSING SECTION# Branching code: if/else# Looping code: for-loop, while-loop###############################

# code goes here

This section contains the main processing code.

In this program, the main while-loop asks the player for guesses, displays the appropriate version of the hangman figure when the player guesses incorrectly, and displays both the correct guesses and incorrect guesses.

This code also needs to print various messages to the user.

################################ CLEANUP, TERMINATION, and EXIT SECTION###############################

# code goes here

In this program, the only code in this section is a “game over” message to the user.

Copyright © 2009–2015 NAF. All rights reserved.

Page 26: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Environment Setup SectionWhich team member has the primary responsibility for this section of the program?

In the space below, write the statement to import the Python random number routines. (Hint: You first used these routines in Guess-A-Number.)

Function Definition Section (print_game_rules())Which team member has the primary responsibility for this section of the program?

This function will print out the rules of the game and will also give a hint about what the mystery word is by telling the user what kind of word it is and how many letters it contains. This function does not return a value.

The first parameter (argument) for the function is max_incorrect. That means that when the function is called, the calling statement needs to pass the maximum incorrect guesses to the function.

The second parameter is word_len. This parameter indicates the length of the mystery word.

The function definition header statement is as follows:

def print_game_rules(max_incorrect,word_len):

In the space below, write the print statements for the game rules.

Function Definition Section (display_figure())Which team member has the primary responsibility for this section of the program?

This function prints out the appropriate text art (scaffold and stick figure) based on the number of bad letter guesses the player has made. The function is called by the main program after each guess.

The bad_guesses parameter is used to display a text-mode graphics picture of how close the player is to being hanged. This function must have a return statement at the end, but it does not return a value.

The function definition header statement is as follows:

def display_figure(bad_guesses):

Copyright © 2009–2015 NAF. All rights reserved.

Page 27: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

For the function body, create a tuple that has eight elements that represent the various stages from game initialization to the player’s being hanged. The tuple elements are triple-quoted strings of text-mode graphics. The tuple definition should look something like this:

The last picture (element 8 of the tuple) should look something like this:

Sketch out the figure for “three bad guesses” in the space below.

Finally, write a print statement in the space below that prints out the appropriate tuple element using bad_guesses as an index.

Don’t forget to end your defined function with a return statement (with no parameters).

Function Definition Section (prompt_for_letter())Which team member has the primary responsibility for this section of the program?

Copyright © 2009–2015 NAF. All rights reserved.

Page 28: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

You created the code for this function in Part 2 of Student Resource 10.3, Notes and Practice: Advanced Sequence Manipulation. All you need to do here is to copy it to the right location in your Hangman program.

Processing Initialization SectionWhich team member has the primary responsibility for this section of the program?

In this section, you create variables that define the possible mystery words and then keep track of how things are progressing as the player guesses letters.

First write a statement that creates a tuple called animal_words with names of animals. You can put as many words in the tuple as you want. The tuple begins with something like animal_words = ("horse",...). Write your tuple definition in the space below:

You need to use the random choice() function to pick a random word from the tuple just defined. Write the statement that uses choice() to pick a random word from animal_words and store the word in variable theword.

Next, write a statement that creates a variable word_len that is the length of the theword string. Use the len()function to do this. Write the statement in the space below. (Hint: You were introduced to the len() function earlier in this lesson.)

Create a list to display letters not yet guessed and also those that have been guessed. There is one entry in this list for each letter in the mystery word.

The list will contain either "_" if the letter has not yet been guessed or a letter if it has been guessed. So, "__a_t" would mean the letters "a" and "t" have been correctly guessed and that there is still one letter of the word that has not yet been guessed by the player.

In the space below, write the statement that initializes the list of guesses to be a list of length word_len with each element being "_". (Hint: x = word_len * [0] would create a list of zeros like this.)

You end this section by creating some additional variables used in the play of the game.

Write a statement in the space below that creates a numeric variable max_incorrect and sets it to 7:

Copyright © 2009–2015 NAF. All rights reserved.

Page 29: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Add a statement that stores the lowercase letters of the alphabet in variable alphabet. The statement starts with alphabet="abc…. Write the complete statement in the space below:

Write a statement to initialize the variable letters_tried to a null string:

Write a statement to initialize the number variable number_guesses to 0:

Write a statement to initialize the number variable letters_correct to 0:

Processing SectionWhich team member has the primary responsibility for this section of the program?

Fill in the missing information in the following table to create the code required for the processing section.

# print the game rules and a clue to the user about the mystery word (call# the user-defined function)

(put code here)

# below is the main loop to ask the player for letter guesses and to display# the hangman figure.

# the game ends when the player either guesses all the letters in the word or# gets hanged for having too many bad guesses.

# as long as the number of incorrect guesses has not reached the maximum# allowed AND# the number of correct letters has not reached the value of word_len

while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):

# prompt the player to guess a letter in the word# store the guess in letter

letter = prompt_for_letter()

# test if player guessed a single letter in the alphabet

if len(letter)... (finish code statement here)

# the guess is a letter in the alphabet; did player already pick it?# we need to remember each letter that has been guessed# if player guesses the same letter a second time, prompt player # to guess another

Copyright © 2009–2015 NAF. All rights reserved.

Page 30: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

(put code here)

# tell player letter has already been picked

print("You already picked", letter)

else:

# add the latest letter to the end of the string that contains# all the letters guessed so far

letters_tried = letters_tried + letter

# check to see if the letter picked is in the word# by searching for it using the find() string method# store the result in first_index# if -1 is returned by find(), the letter guessed is not in the # mystery word

(put code here)

if first_index == -1:

# the letter just guessed is not in the mystery word# print something like "the letter x is not in the word"

(put code here)

# increment incorrect_guesses# (add 1 to the number of incorrect letters guessed)

(put code here)

else:

# if we get here, the letter guessed is in the mystery word# it may even be in the word in more than one position# update the guesses list to show all the letters in the # mystery word that match the letter just guessed

# print something like "the letter x is in the word"

(put code here)

# loop through all the letters in the mystery word

for i in range(word_len)):

# test to see if the letter just guessed matches the # letter in this position in the mystery word

if letter == theword[i]:

# we have a match# replace '_' in guesses# with the letter just guessed

guesses[i] = letter

# increment letters_correct# (add 1 to the number of letters correctly # guessed)

Copyright © 2009–2015 NAF. All rights reserved.

Page 31: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

(put code here)

else:

# if we get here the player didn't type in a letter at the prompt

print("Please guess a single letter in the alphabet.")

# display the hangman figure for the number of incorrect guesses the # player has made so far

display_figure(incorrect_guesses)

# display the string of letters already tried

print("Letters tried so far: ", letters_tried)

# display the current state of the guesses list showing "_" for letters # not yet guessed and a letter of the alphabet for letters that have been # guessed correctly.# the following statement converts the items in the guesses list # into a single string. hint: use join()

(put code here)

# after the current guess, check for conditions that indicate # the game is about to end

# see if the player has reached the maximum number of incorrect # guesses allowed# if so, the player is hanged

if incorrect_guesses == max_incorrect:

print("Sorry, too many incorrect guesses. You are hanged.")

# tell the player what the mystery word was# print something like "the word was..."

(put code here)

# see if the user has guessed all the letters in the word# by checking that the number of correct letter guesses is the same as # the length of the mystery word

if letters_correct == word_len:

#congratulate the player

print("You guessed all the letters in the word!")

# print out the mystery word# print something like "the word was..."

(put code here)

Cleanup, Termination, and Exit SectionWhich team member has the primary responsibility for this section of the program?

Copyright © 2009–2015 NAF. All rights reserved.

Page 32: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Print an exit message to the user (for example, “The game is over.”).

Temporary Code for DebuggingWhich team member will put this code into your program?

To test the program “chunks” designed and coded by your team specialists, put the following temporary debugging code in the program in the processing section (in place of the central programming logic code), which you will add later.

Before you add this code, the following chunks must already be in place:

● Prolog

● Environment setup section

● Function definition section (with all three functions)

● Processing initialization section

● Cleanup, termination, and exit section

Temporary Debugging Code#

# Test the initialization code.

#

print("*** Testing the initialization code ***")

print("list of mystery words", animal_words)

print("mystery word", theword)

print("mystery word length", word_len)

print("guesses", guesses)

print("alphabet", alphabet)

print("letters tried", letters_tried)

#

# Test the user-defined functions.

#

print("*** Testing the user-defined functions ***")

# print the game rules

# print a clue about the mystery word to be guessed

Copyright © 2009–2015 NAF. All rights reserved.

Page 33: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

print_game_rules(max_incorrect, word_len)

# test the prompt_for_letter() function by calling it multiple times

for i in range(3):

a = prompt_for_letter()

print("prompt_for_letter() returned <"+a+">")

# test the display_figure() function

for i in range(8):

print("bad guesses set to", i)

display_figure(i)

Program ImplementationFollowing specific instructions from your teacher, code and run the Hangman program.

Don’t forget to include appropriate comments in your program!

Copyright © 2009–2015 NAF. All rights reserved.

Page 34: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.6

Test Plan: Hangman ProgramStudent Names:_____________________________________________________ Date:____________

Directions: This is the test plan for your Hangman program. Your testing partners will test your program using this plan as a guide. Test plans are very important in the programming world. When you interview for an internship or a programming job, you should tell the interviewer that you have had experience writing and implementing test plans.

This plan consists of two three-column tables. You, as the programmer (or coder), need to fill in the first two columns. The third column will be filled in by your testing partners as they test your program. Some of the information in the first two columns has already been filled in for you. Complete the plan by doing the following:

1. Fill in any missing information in column one of each table.

2. Test your own program by following the instructions in the first column and filling in the second column. Fix any errors you find. (In the programming world, programmers are often expected to do their own preliminary testing before giving their program to the test team.)

3. When you are confident that your program will pass all the tests, give your program to your testers.

User-Defined Function and Main Processing Section TestsTest Coder: Expected Response Tester: Yes/No or Comment

In response to the “Guess a letter in the word” prompt…

1. Enter: Enter (return)

What is being tested: The guess must be one character.

1. Error message saying guess must be a single letter.

2. Reprompt for a letter.

2. Enter: abcWhat is being tested:

3. Enter: 2What is being tested:

4. Enter: a, followed by a space

What is being tested: Trailing blanks are ignored.

5. Enter: a space followed by a letter

What is being tested:

6. Enter: a letter and then the same letter again at the next

Copyright © 2009–2015 NAF. All rights reserved.

Page 35: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

prompt

What is being tested:

7. Enter: letters one-by-one trying to guess the word

1. Message that you have guessed the word.

OR

2.

Environmental TestsTest Coder:

Yes/NoTester: Yes/No or Comment

Program Execution

8. The program executes without runtime errors.

Initial Messages

9. As the program begins to execute, it prints a clear informational message explaining what is happening and what the user needs to do.

10. The program prints the hangman game rules in clear, understandable language.

11. None of the initial messages have spelling or grammatical errors.

Final Messages

12. Before the program exits, it prints a clear message telling the user the game is over.

13. The final message contains no spelling or grammatical errors.

Copyright © 2009–2015 NAF. All rights reserved.

Page 36: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Student Resource 10.7

Assessment: Individual ContributionStudent Name:____________________________ Date:__________ Project ______________________

Directions: First, answer the questions related to working in a programming team. Answering these questions should help you define the role you would like to have in future programming teams and might also help you explain in an interview situation what types of teams you work best in.

On the second page of this resource, assess your own contribution to this project in the first section. Then have your group members provide their input in the second section.

Finally, submit the form to your teacher, who will provide a final assessment in the last section.

Reflections on Team ProgrammingAnswer the following questions in the space provided:

What specialist role did you play in the Hangman project (text and text art, user-defined functions, or central programming logic)?

What did you like best about playing the role? What did you like least?

If you were doing another programming project like Hangman, would you want to play the same specialist role again? Why or why not?

Based on your experiences so far, which do you enjoy more: working with a programming partner or working in a team of three? Explain why.

What one or two things could your team of three in the Hangman project have done to work more smoothly or efficiently? (That is, what are one or two “lessons learned” that you would do differently the next time?)

Copyright © 2009–2015 NAF. All rights reserved.

Page 37: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads...  · Web vieware short, relatively self-contained (that is, not completely dependent on another part) pieces of code

AOIT Introduction to ProgrammingLesson 10 Advanced Sequence Manipulation

Assessment by Self

A description of the specific tasks I completed:

An explanation of the contribution and value I provided toward my group’s work:

A list of changes I would make if I were to work on these tasks again:

Assessment by Group Members

Name Initials What You Agree and Disagree With

Assessment by Teacher

Pluses Minuses Score

Copyright © 2009–2015 NAF. All rights reserved.