curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and...

34
AOIT Introduction to Programming Lesson 9 User-Defined Functions and Sequences Student Resources Resource Description Student Resource 9.1 Minor Project Work: Project Overview Student Resource 9.2 Worksheet: Designing and Coding a User-Defined Function Student Resource 9.3 Reading: Sequences—Lists and Tuples Student Resource 9.4 Notes and Practice: Sequences—Lists and Tuples Student Resource 9.5 Design and Coding: The Shuffle Cards Program Copyright © 2009–2015 NAF. All rights reserved.

Transcript of curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and...

Page 1: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to Programming

Lesson 9User-Defined Functions and

Sequences Student Resources

Resource Description

Student Resource 9.1 Minor Project Work: Project Overview

Student Resource 9.2 Worksheet: Designing and Coding a User-Defined Function

Student Resource 9.3 Reading: Sequences—Lists and Tuples

Student Resource 9.4 Notes and Practice: Sequences—Lists and Tuples

Student Resource 9.5 Design and Coding: The Shuffle Cards Program

Copyright © 2009–2015 NAF. All rights reserved.

Page 2: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Student Resource 9.1

Minor Project Work: Project OverviewStudent Names:_____________________________________________________ Date:____________

In this project, you will be working with your group to design and code the traditional game of hangman, usually played with paper and pencil. You will create a version in which the computer plays against a human player. The driving question for your project is this:

“How can we use what we have learned about designing and coding Python programs to create a well-designed, attractive game of hangman that runs without errors?”

This project overview provides the details of what you need to know about the game of hangman, plus some important information about organizing your team so that each member can fully contribute.

Part 1: The Game of HangmanAs you probably already know, the game usually has two players, although there can be more. The players take turns thinking up and guessing a “mystery word.”

The player who acts as game host (“the host”) thinks of a word, tells the other player what category the word is in (for example, names of cities), and writes in a line the same number of underscores as there are letters in the word. For example, for Albuquerque, the host would write “_ _ _ _ _ _ _ _ _ _ _.”

The player who is trying to figure out what the word is (“the player”) does so by guessing letters, one by one. If a guess is correct, the host writes it on the appropriate underscore(s). For the first incorrect guess, the host draws a scaffold and a stick-figure head, and begins a list of wrong guesses. For each wrong guess thereafter, the host adds a body part to the stick figure (neck, body, left arm, right arm, left leg, and right leg). After seven incorrect guesses, the figure is hanged, and the game is over. Then the players change roles, and a new game begins.

Part 1 Review: In the space below, draw a hangman game and play it with your group.

Part 2: A Hangman Computer ProgramIn the Hangman program, one or more human players play one at a time against the computer, which always acts as game host. The program chooses a random mystery word from a list of words in a certain category (for this project, a list of animal words) that is coded into the program.

The Hangman program has three defined functions:

Copyright © 2009–2015 NAF. All rights reserved.

Page 3: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

● print_game_rules()This function is called from the main processing section of the program to print game and game rule information for the user.

● display_figure()This function contains a “library” of scaffold and stick-figure combinations—a tuple of triple-quoted strings. Which piece of text art gets displayed depends on how many incorrect guesses the player has.

● prompt_for_letter()This function prompts the player for a guess, assigns it to the answer variable, strips out leading or trailing blanks, converts it to all lowercase letters, and returns the result.

Variables that need to be initialized in the initialization section of the program include the following:

● The length of the word chosen

● The maximum number of incorrect guesses (seven)

● The count of incorrect letter guesses (zero)

The main processing section contains a while-loop (the code executes while the number of incorrect guesses has not yet reached seven). Inside the while-loop is branching code and a for-loop.

The cleanup, termination, and exit section contains code to print “The game is over.”

Part 2 Review: Write two or three sentences to summarize what you learned in this section about the Hangman computer program.

Part 3: Working in Teams

Team Organization for This ProjectFor this project, you will be working in teams of three instead of two, as you have been doing up until now.

Although your entire team is responsible for the final result (the completed Hangman program), each team member will take the lead role for one of the “code specialties.” For this project, the specialties are (1) text and text art, (2) user-defined functions, and (3) central programming (processing) logic. You have worked before with text and text art, and every program has central programming logic, but you have not yet worked on user-defined functions.

Here is a little more information about each role:

● Text and text art: Writing information, instructions, and error messages to the user. Using text art similar to the art used in the Menu program in Lesson 7.

● User-defined functions: Writing customized functions unique to a given program, rather than using Python built-in functions like input() and string.isupper(). You will do that early in this lesson.

Copyright © 2009–2015 NAF. All rights reserved.

Page 4: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

● Central programming logic: Figuring out what kind of information will be required for the program to produce the intended results and how to design and implement branching and looping code. This specialist also needs to take the lead role on initializing variables. In professional terms, this person would be the lead developer.

Besides deciding who will play which code specialist role, your team of three needs to figure out the following:

● Who will keep track of your team’s progress and make sure you are on time? (This person is called the project lead.)

● Will all three team members work at the keyboard, or should two team members design on paper and only one type?

● How will you conduct your code reviews?

● How will you bring together all the specialty code written by the team members and put it into the final program?

You will be working on these questions over the next few days, before you start the actual work of designing and coding the Hangman program.

Learning about Teams from a Guest Speaker You will have a chance to learn about good teamwork practices from a guest speaker in the next class period. Based on what you’ve learned about programming teams, write at least two questions that your programming team has for the guest speaker—questions about the speaker’s experience working as a programmer and working in professional programming teams. You will be asking your questions as part of the interview.

Our questions:

Copyright © 2009–2015 NAF. All rights reserved.

Page 5: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Student Resource 9.2

Worksheet: Designing and Coding a User-Defined Function

Student Names:_____________________________________________________ Date:____________

Directions: Design and write the code to draw five intersecting rings that resemble the Olympic rings. The output should look exactly like the Olympic Rings program in Lesson 2, but in this program you will create a user-defined function to do the drawing routines.

For more information about the original Olympic Rings program, see Student Resource 2.6, Worksheet: Olympic Rings Program, and the sample program olympic_rings.py.

Problem StatementUsing a user-defined function to do the drawing routines, write a Python program to draw five intersecting rings that resemble the Olympic rings. The output should look exactly like the Olympic Rings program in Lesson 2.

Requirements and Program Design (Algorithm)General Requirements

● Open a new window in Python IDLE.

● Using a template that your teacher provides you (program_template.py), create the Olympic Rings (User-Defined Function) program skeleton with the sections shown in the table below. Name the program olympic_rings_function.py and save it in your Lesson 9 folder.

Program Section Notes

################################ PROLOG SECTION# olympic_rings_function.py# Draws the Olympic rings using Turtle Graphics.# Uses a user-defined function.# (today's date goes here)# (programmer names go here)# Possible future enhancements:# Unresolved bugs:###############################

This section contains important information about the program.

Notice that everything in this section is included as a Python comment.

You may not be able to complete this section before you code and test the program.

################################ ENVIRONMENT SETUP SECTION# Imports: turtle###############################

# code goes here

In this section, you’ll include the import statement that is always part of a Turtle Graphics program.

Copyright © 2009–2015 NAF. All rights reserved.

Page 6: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

################################ FUNCTION DEFINITION SECTION# User-defined functions: draw_ring()###############################

# code goes here

You haven’t included this section in prior programs.

In this program, you’ll include a user-defined function that does the drawing routines.

Notice that this section goes near the top of the program, right after the environment setup section, and not near or in the processing section. It is a good programming practice to keep this kind of code isolated from the main program logic.

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

# code goes here

In this section is setup information for the program.

Examples: code to set or initialize variables, and code to print general information to the user

In this program, you’ll include familiar statements like turtle = Turtle() and familiar built-in-functions like setup() and title().

################################ PROCESSING SECTION###############################

# code goes here

This section contains the main processing code.

Examples: branching and looping code

In this program, you’ll put in calls to the user-defined function that draws the rings.

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

# code goes here

In this program, you’ll put in code to hide the turtle and end the program.

Environment Setup SectionThis section of the program contains only one statement: the statement that imports the Turtle Graphics drawing routines. You have included this statement in all your Turtle Graphics programs. If you have forgotten what it is, look at the original Olympic Rings program you wrote in Lesson 2.

Write the statement in the space below.

Copyright © 2009–2015 NAF. All rights reserved.

Page 7: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Function Definition SectionThis section contains the drawing routine that will be called in the processing section for each of the five Olympic rings.

As you remember from the original Olympic Rings program, the drawing code for all five rings is almost exactly the same—only the values change. That is, the coordinates and pen color change as each ring is drawn, but the drawing code is identical.

Here is the code from the Lesson 2 Olympic Rings program to draw the first ring:

turtle.up()

turtle.goto(-100,0)

turtle.down()

turtle.color("blue")

turtle.circle(75)

A user-defined function makes it possible for you to avoid writing the same code over and over. If your user-defined function contains the drawing code, all you have to do to draw each ring is call the user-defined function and pass it the appropriate values (for example, the color).

Here is the draw_ring() user-defined function that you will include in this program:

# function definition statement

def draw_ring(xcoord,ycoord,ring_color,ring_radius,turtle):

# hide the movement of the turtle

turtle.up()

# move to the drawing location of the first ring

turtle.goto(xcoord,ycoord)

# show the movement of the turtle

turtle.down()

# set the color of the ring

turtle.color (ring_color)

# draw the ring

turtle.circle(ring_radius)

Here is an explanation of the draw_ring() user-defined function:

● As is true for all user-defined functions, this one starts with def, followed by the function name (in this case, draw_ring).

● Inside the parentheses after the function name are the function parameters (also called arguments).

● The parameters represent values, which are “passed” to the user-defined function every time it is called in the processing section of the program.

Copyright © 2009–2015 NAF. All rights reserved.

Page 8: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

● The information passed to this function are the x coordinate, the y coordinate, the color of the ring, the radius of the ring, and the name of the turtle.

● When you pass information to the user-defined function, Python makes sure you have the same number of parameters as you put in the function. If you try to pass more or fewer parameters, you will get an error!

● Notice that there is a (required) colon after the right parenthesis in the function definition statement.

● Notice that the statements that follow the colon are indented, which is the same convention you have used in branches and loops.

● When a user-defined function is called from a statement in the main processing section of the program, it goes through all of its statements, performing whatever actions are necessary, and then returns to the next statement in the main processing section.

● As is also true for built-in functions, a user-defined function can be called multiple times in a program.

Look back at the Olympic Rings program from Lesson 2 and find the code that draws the rings. Review and analyze each block of drawing code. In the table below, write the values that you think will need to be passed to the user-defined function when it draws the rings. Some of the information has already been filled in.

Ring Number and Color

xcoord ycoord ring_color ring_radius turtle

1 (blue) -100 "blue" turtle

2 (black)

3 (red)

4 (yellow)

5 (green)

Processing Initialization SectionIn this section, you need to include the same statements you used in the section of the original Olympic Rings program labeled set up the program except for the import statement, which in the new program is in the environment setup section.

Write the code for the processing initialization section below (hint: change the title of the drawing window to indicate that it contains a user-defined function):

Copyright © 2009–2015 NAF. All rights reserved.

Page 9: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Processing SectionFor the new Olympic Rings program, all you need in this section is a call to the user-defined function and the values of the variables in the user-defined function. You “call” a user-defined function just like you “call” a built-in function: by writing its name. Some functions require parameters, and some don’t. The one you are calling does.

How many times will you need to call the user-defined function draw_ring()?

How many values will you need to pass to the user-defined function every time you call it?

Where will you put the variable values you are passing to the user-defined function?

How will you separate the variable values?

Write the first call to the user-defined function draw_ring() in the space below.

Cleanup, Termination, and Exit SectionIn the final section of the program, you will hide the turtle and end the program just as you did in the original Olympic Rings program. In the space below, write the two statements you need to include.

Program ImplementationFollowing specific instructions from your teacher, code and run the Olympic Rings (User-Defined Function) program.

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

Copyright © 2009–2015 NAF. All rights reserved.

Page 10: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Student Resource 9.3

Reading: Sequences—Lists and Tuples

This presentation does the following:

• Reviews concepts already learned about sequences (strings, lists, and tuples)

• Explains the formal programming relationship among strings, lists, and tuples

• Provides examples of lists and tuples in Python

• Explains how sequences will be used in programming projects to come

Copyright © 2009–2015 NAF. All rights reserved.

Page 11: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Sequences are ordered collections of values, and strings are one type of sequence.

In many programming languages, sequences are called arrays.

You have used strings in many different programs in this course.

So far, you have not thought of strings as “ordered collections of values”; you have probably thought of them instead as whole strings or “words.” Strings are “immutable,” which means they cannot be changed.

In what sense could strings be thought of as collections of values?

Copyright © 2009–2015 NAF. All rights reserved.

Page 12: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Although in the firstname.py program you were interested only in the complete first name, Emily, in some instances you might be interested in the individual letters or characters in the name. In that case, it would be useful to split up the name and refer only to the character of interest (for example, the i).

Copyright © 2009–2015 NAF. All rights reserved.

Page 13: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

With indexing you can identify the individual letters or characters in a given string.

What is called positive indexing (moving from left to right in the string) begins with 0. Therefore, firstname[0] in the example is used to identify the E in Emily. (In mathematics, this is called a subscript, and you can read it as “firstname subzero.”)

The value of m in the string is firstname[1] or “firstname sub-one.”

If you were writing a program to play hangman and the mystery words were girls’ names, you might use indexing to identify the individual letters in the names.

Negative indexing (moving from right to left in the string) also exists in Python, but it is not used in this course. Negative indexing moves from right to left in the string, starting with -1 and, in this example, going through -5. (The index for the E in Emily would be firstname[-5].)

Copyright © 2009–2015 NAF. All rights reserved.

Page 14: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

In the game of hangman, you need to know the mystery word, the number and position of the letters in the word, and the user’s guess. When you play the game, you need to figure out whether the user’s current letter guess is in the mystery word and, if so, where in the word it is located.

Indexing is an important construct in the algorithm.

In the current scenario, the a (the user’s guess) occupies the second position in the word. That would translate to letters[1] and mystery_word[1].

If the mystery word were antelope, the guess of p occupies the seventh position in the word, which would translate to letters[6] and mystery_word[6].

Copyright © 2009–2015 NAF. All rights reserved.

Page 15: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Indexing with strings is useful in programming, but it is probably even more useful with lists, which are sequences of 0 or more values. Lists are always enclosed in square brackets ([ ]).

List indexes (that is, positive indexes) always begin with 0 and move from left to right, just like string indexes.

Lists are mutable, which means they can be changed.

The value of favorite_foods[1] is hamburgers.

Numbers and favorite_foods are lists because they are collections of information elements. Such collections are usually related in some way (which should be obvious here).

Lists can contain multiple data types; for example, both 20 and hamburgers could be in the same list.

Copyright © 2009–2015 NAF. All rights reserved.

Page 16: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

These collections of informational elements are all lists. The first might be times achieved in running 100 yards. The Shuffle Cards example might be the order of a list of 52 cards that have been shuffled (the range is 0 to 51). The my_pets example names types of pets. The word_length example could be used to initialize a variable that will contain a list of values to null.

These examples are all examples of lists that might change over time. For example, if the runner improves her time in the 100-yard dash, the next set of results might contain smaller numbers. If the snake should happen to eat the hamster, the list of pets will be different.

Therefore, it is appropriate that these sequences are lists.

Copyright © 2009–2015 NAF. All rights reserved.

Page 17: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Tuples are very similar to lists in Python, but they cannot be changed. They are used to hold constant data.

Python would give you an error message if you tried to code animal_words[1] = "fish".

The rank_string and suit_string tuple will always be the same for a standard deck of cards.

The animal words (that is, possible choices for the mystery words) may be altered by the programmer over time, but they will not change while the program is running.

One important difference between tuples and lists is that tuples are enclosed in parentheses (curved brackets) and lists are enclosed in square brackets ([ ]).

If you did a text art “library” for the hangman game (for example, one piece of text art in which only the figure's left arm is showing and another in which both arms are showing), you would probably make it a tuple, because it would not change during the game.

Note that in other programming languages, this method of defining constants is used frequently. Another example is PHP, which adds const as a prefix to the variable name.

Copyright © 2009–2015 NAF. All rights reserved.

Page 18: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

It is very important to use the correct kind of brackets (or parentheses) for lists and tuples. Tuples are always enclosed in parentheses (curved brackets) and lists in square brackets ([ ]). Incorrect usage will generate a syntax error in Python.

It is also important to note that indexing (of strings, lists, and tuples) is always done using square brackets ([ ]). An example is suit_string[3], which translates to spades.

Copyright © 2009–2015 NAF. All rights reserved.

Page 19: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

There are a number of functions that make sequences more powerful. Some functions can be used with all three kinds of sequences (strings, lists, and tuples), but not all can.

One example that can be used with all three is the test for membership, which means “is this element in this sequence?”

You will have a chance to use a number of these functions in the programming projects during the remaining lessons of this course.

Copyright © 2009–2015 NAF. All rights reserved.

Page 20: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Python has three kinds of sequences: strings, lists, and tuples.

Sequences are very powerful programming constructs, and they will play an important role in the remaining programs in this course.

One of the most common of the sequence operations is indexing (also called subscripting), which allows you to identify and operate on a single element in a collection of elements.

You will be using both lists and tuples in the very next program, which is called Define Cards. You will also use them in Shuffle Cards (in this lesson) and Hangman (in the next lesson).

Copyright © 2009–2015 NAF. All rights reserved.

Page 21: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Student Resource 9.4

Notes and Practice: Sequences—Lists and TuplesStudent Names:_____________________________________________________ Date:____________

Directions: While you are watching the presentation called “Sequences—Lists and Tuples,” take notes and then answer the questions in Part 1, below. Then design and code the program in Part 2.

Part 1: Notes and AnalysisSlide 3, “Strings can be ‘ordered collections of values’”: What are the values in the string "E m i l y"?

How is this string a collection?

How is the collection ordered?

Slide 4, “Individual letters are important in hangman”: What is an index?

What is the first subscript of an index?

Slide 5, “Here’s how indexing might work in hangman”: Write the algorithm steps with a mystery word of crocodile and a guess of e.

How would you handle a guess of o?

Slide 7, “Lists are ‘mutable’ sequences of values”: Write an index of song titles.

Slide 8, “Tuples are ‘immutable’ sequences of values”:

Copyright © 2009–2015 NAF. All rights reserved.

Page 22: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

What does immutable mean?

Slide 10, “Operations and functions…make sequences more powerful”: Given months = ("January", "February", "March"), then len(months) is what?

What is months?

How do you know?

Part 2: Independent Practice (Define Cards Program)Open Python IDLE and create a new program called define_cards.py. For this exercise, define_cards.py is an independently running program. Later in the lesson, you will convert this program to a user-defined function (also called define_cards) for the Shuffle Cards program.

Problem StatementWrite a Python program that defines and prints out the value of individual cards in a card deck as a number (0 to 51) plus a combination of rank and suit. For example, card 0 is ace of clubs, and card 51 is king of spades.

The output of your program should look like this:

The cards are:

0 ace of clubs

1 two of clubs

2 three of clubs

...

50 queen of spades

51 king of spades

The program uses two loops:

● One set of two for-loops (one inside the other) to build the value strings (e.g., ace of clubs) for all the cards in the deck

● One for-loop to print the card values to the Python shell

Copyright © 2009–2015 NAF. All rights reserved.

Page 23: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

RequirementsHere are the requirements and some programming hints:

● Name your program define_cards.py and save it in your Lesson 9 folder.

● Define (using variables) the rank and string values. Call the rank variable rank_string. Call the suit variable suit_string. Name the ranks ace, two, three, etc., in that order. Name the suits clubs, diamonds, hearts, and spades.

● Create a list called cards. Initialize it to null.

● Using a set of two for-loops (one inside the other), build the strings for all the cards in the deck. Make the outer loop the “suit-loop” (for example, for suit in range(4)) and the inner loop the “rank-loop.”

● In the inner loop, assign the value of the card string (that is, rank_string[rank] + " of " + suit_string[suit]) to the variable card_string.

● Still within the inner loop, append (using the append() built-in function) each card_string in turn to the end of the list of cards using the statement cards.append(card_string).

● Print an output label something like this:

The cards are:

● Create another for-loop to print the cards. Call the counter n. Print all 52 card numbers and values. You will need to print both n and cards[n]. Print them on the same output line.

Copyright © 2009–2015 NAF. All rights reserved.

Page 24: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Student Resource 9.5

Design and Coding: The Shuffle Cards ProgramStudent Names:_____________________________________________________ Date:____________

Directions: Write the design for the Shuffle Cards program and then code it.

Problem StatementWrite a Python program to simulate shuffling and dealing from a deck of cards.

Requirements and Program Design (Algorithm)General Requirements

● Open a new window in Python IDLE.

● Using a template that your teacher provides you (program_template.py), create the Shuffle Cards program skeleton with the sections shown in the table below. Name the program shuffle_cards.py and save it in your Lesson 9 folder.

Important Note: The program template shown as program sections in the following table is available as a Lesson 9 sample program under the name program_template.py.

Program Section Notes

################################ PROLOG SECTION# shuffle_cards.py# Simulate shuffling and dealing# from a deck of cards.# Uses multiple user-defined functions.# (today's date goes here)# (programmer names go here)# Possible future enhancements:# Unresolved bugs:###############################

This section contains important information about the program.

Notice that everything in this section is included as a Python comment.

You may not be able to complete this section before you code or test the program.

################################ 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: define_cards(),# create_deck(), shuffle_deck(),# deal_cards()###############################

In this program, you’ll define four functions: define_cards() (which will be almost identical to the define_cards.py program you have already written), create_deck(), shuffle_deck(), and deal_cards().

Copyright © 2009–2015 NAF. All rights reserved.

Page 25: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

# code goes here 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, you’ll put in a statement to initialize the card deck to null.

################################ PROCESSING SECTION# Branching code: none# Looping code: for-loops###############################

# code goes here

This section contains the main processing code.

In this program, you’ll put code in this section to shuffle the deck and deal the cards.

This program contains no branching code, but it has multiple for-loops.

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

# code goes here

In this program, you’ll put in a couple of informational messages to the user.

Environment Setup SectionWrite the statement to import the Python random number routines in the space below.

Function Definition Section (overview)This section contains four user-defined functions that simulate the setting-up process of a real-world game of cards.

The first function, define_cards(), defines the cards that make up the deck. It is almost identical to the define_cards.py program you have already written.

The next function, create_deck(), creates a list (in rigid sequence) of the 52 items that represent the 52 cards.

Then shuffle_deck() puts the 52 cards into a random order.

Finally deal_cards() returns (or “removes,” in real-world terminology) the top card from the deck and leaves the rest of the deck intact.

Function Definition Section (define_cards)To create this define_cards() function:

● Create the definition statement. Write it in the space below.

Hint: Definition statements always start with def plus the name of the function, plus any relevant parameter names inside the parentheses that always follow the function name. In this case, the parameter is n, which represents the value of the card (for example, ace of spades).

Copyright © 2009–2015 NAF. All rights reserved.

Page 26: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

● Copy the entire define_cards.py program to the appropriate location (below the definition statement you just created) in the shuffle_cards.py program.

● Delete any comments you put at the top of the program (for example, the program name).

● Delete the comments and code at the bottom of the define_cards.py program that label the output and print the card numbers.

● Insert a statement at the bottom of the define_cards() function in the shuffle_cards.py program that returns the entire list of cards to the calling function. The statement should look like this:

return cards[n]

Function Definition Section (create_deck)Next, write the create_deck() function to create a deck of cards with the numbers 0–51 so that you can later change the order of the cards using an existing method from random:

● Create the definition statement. The parameter for this function is deck. Write the statement in the space below.

● Create a for-loop using i as your counter. Your range value is the number of cards in a deck. The code in the for-loop appends each card number in turn (0 to 51) to the deck. Write the loop in the space below.

● Outside the loop, write a return statement (simply, return) to return control to the calling function in the main processing section.

Function Definition Section (shuffle_deck)This function shuffles the deck so that the cards are not in the original order. (If the cards were not shuffled, they would always be dealt in the original order, which would be too predictable for any card game.)

First, think about why you are doing this as a user-defined function. Why not put the code in the main processing section? After all, the deck is shuffled only once for each run of the program. (Hint: You could

Copyright © 2009–2015 NAF. All rights reserved.

Page 27: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

just as well put this in the main processing section, but we are thinking ahead. Suppose you wanted to create a Blackjack game using Python?)

Write the answer to this question in the space below: What are two reasons you want to do as much of your coding using functions as is possible and reasonable?

Fortunately, the Python random package has a shuffle() function, which you simply need to call. The parameter for this function is deck.

You should be pros at writing functions by now! Write the shuffle_deck() function in the space below. Hint: Don’t forget to put in a return statement to return control to the calling function in the main processing section.

Function Definition Section (deal_cards)After the program shuffles the cards, it “deals” the first 10 cards (that is, it “turns them over” to reveal the card faces). You need a function to do this.

Again, you are lucky: the Python random routines have a function to do this. It’s called pop(), and it “pops” one item in a list off the top or bottom of the list. Since it’s not considered fair to deal off the bottom of the deck, we’ll deal off the top.

In the space below, write your definition statement (the parameter is deck) and then a return statement that looks like this (the parameter 0 ensures we’re dealing off the top):

return deck.pop(0)

Processing Initialization SectionWrite the statement to initialize the deck to null. (Hint: The variable deck is a list. Be sure you are using the right kind of “parentheses” for lists.)

Write the answer to this question in the space below: Why are we putting this statement here instead of one inside the user-defined functions? (Hint: Look back to see where the variable deck is used.)

Copyright © 2009–2015 NAF. All rights reserved.

Page 28: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

Processing SectionIn this section, you need to create the deck, shuffle it, deal 10 cards off the top of the shuffled deck, and print the values (for example, queen of hearts) for the 10 cards as program output.

Follow these steps (write the code in the space that follows):

1. Write a statement to call the create_deck() user-defined function.

2. Write a statement to call the shuffle_deck() user-defined function.

3. Write an informational message to the user explaining what he or she is about to see (the 10 dealt cards).

4. Write a for-loop to deal the first 10 cards. You should have two statements within the loop: (1) a statement to call the deal_cards() user-defined function and assign the current value of deck to a variable called card and (2) a statement to print (using the define_cards() user-defined function) the current value of card.

5. Because you go through the loop 10 times, you will print out 10 string values, one by one, for your user to see.

6. What is happening here is that the program is matching up the card numbers in the deck (0 to 51 but in a shuffled, or random, order) with the values (for example, ten of diamonds) associated with the card numbers and then printing them out. The card numbers are not printed out, because presumably they would not be meaningful to a user.

Cleanup, Termination, and Exit SectionIn this section, you need to print out an informational message to your user. If you were the user instead of the programmer, what would you want to see at the end of the program? (Hint: The user might wonder: “Is the program finished? What do I do next?”)

Write your informational message(s) in the space below.

Copyright © 2009–2015 NAF. All rights reserved.

Page 29: curriculum.naf.orgcurriculum.naf.org/packaged/assets/downloads/technolog…  · Web viewNotes and Practice: Sequences—Lists and Tuples. Student Resource 9.5. Design and Coding:

AOIT Introduction to ProgrammingLesson 9 User-Defined Functions and Sequences

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

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

Copyright © 2009–2015 NAF. All rights reserved.