Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Summary
Students will be introduced to programming for the first time. They will learn about computer science, computing for good, some of the potential outcomes of programming, and the definition of abstraction. Students will also be learning about program design.
Students must understand that stereotypes of computer programmers are not accurate and that 'coding' is something everyone can learn to do. Computing can be a creative expression and used for good.
Possible misunderstandings: The term NGO is used in the article Programming for Good: The Story of Code for India, without explicitly defining it as Non-Governmental Organization.
Abstraction is a tricky idea. Python allows us to describe what we want to do such as "print" and "input" because it provides the details that explain to the computer how to accomplish the task of taking many keypresses followed by a press of the Enter key to allow the computer to store the information we entered, and also knows how to take information stored in the computer's memory and cause it to appear as a series of recognizable dots on the screen using print. Computer programs use input, output, processing, and memory.
The design topics taught in the 2020-2021 session introduce both user interaction and user experience design.
Outcomes
Student computer usage for this lesson is: required
TEACHERS need to have the class and user accounts set up in Runestone to track student progress.
For the Students:
Note: If computer is not being used, students will need their own copies of the articles
[use the Presentation on Programming Python in Runestone]
Journal Entry: What are some ways that writing programs is a creative endeavor? [ slide 2]
Share answers with your elbow partner. Then share answers with the class.
Open Discussion: What are some ways you know that computing has been used for “good?” [ slide 3 ]
Go to Programming for Good: The Story of Code for India
http://www.attendly.com/programming-for-good-the-story-of-code-for-india/
Read articles or selected text in pairs, with alternating pairs each reading one article. Pairs of pairs get together to share what they read and what they got out of the article.
In pairs, answer the following questions:
Check for Understanding: Teams should share their answers to their instructor.
Have students sketch the computer hardware architecture diagram in Python for Everybody Chapter See https://books.trinket.io/pfe/01-intro.html#computer-hardware-architecture.
Explain that computer processes guide the flow of information that is input, processed, stored or output. The processor (CPU) uses short term memory for doing calculations and temporary storage and long term memory if needed. Have students sketch the computer components diagram above. Explain to students that they will learn to program to develop software using each of these components.
The program output is usually based on both input values and values already in memory. Watch the following video to see how this occurs.
Watch the video on how programs use input, processing, memory, and output to run programs. https://www.youtube.com/watch?v=BSTrWhAGta8
Read Computer Hardware architecture by Dr. Severance.
https://books.trinket.io/pfe/01-intro.html#computer-hardware-architecture
.
Have students go to the article Seven things you should know if you’re starting out programming at
http://www.theguardian.com/info/developer-blog/2011/oct/07/programming-developer-journalist
Pre-reading activities:
In pairs or groups of three, assign each group to read and summarize one of the seven programming principles in the article.
Check for Understanding: Each person should write a 140 character tweet on their topic, next class the group should share their findings with the class.
Getting Started (5 min)
Journal
Say: Online tools support collaboration by allowing programmers to share and provide feedback on ideas and document. Often this collaboration takes place online. What are some online tools you think programmers might use to collaborate?
Student share responses. Be sure that receiving feedback from both developers and users is discussed.
Guided Activities (40 min) Use the Program Design presentation in the Lesson 1 Resource folder.
Say: Success and failure are both about meeting criteria. To know if our efforts are a success, we need to know what the requirements are. So the first step of the design process is investigating the program requirements. In the development process, the design phase outlines how to accomplish a given program specification. Software developers typically organize the overall program into a collection of individual components or modules. Collectively, the component or modules meet the program's requirements.
Highlight: The users are important!
Highlight: Innovation is enhanced by group collaboration!
Jigsaw: In groups of four, read and discuss the four techniques for identifying requirements as listed by Hans Jonasson.
For each of the four techniques, use the Design Techniques table to list the techniques purpose, its advantages, and its limitations
Technique |
Purpose |
Advantage |
Disadvantage |
Say: User interaction design, at its heart, is all about satisfying the end-user’s needs and wants. The design may include brainstorming, storyboarding or even used interaction design as is this activity.
As a class, watch this short UI/UX Design Process video to see how many of the following design strategies are illustrated.
Investigate user interface design (UI) https://www.usability.gov/what-and-why/user-interface-design.html
Investigate user experience design (UX). User Interaction Foundation
On the board, have students list possible ways that an investigation can be performed and keep going until all of the following methods have been uncovered:
The rest of this unit will address techniques used in the development phase of a program.
Development is both iterative - with multiple rounds of testing and improvement - and incremental with development occurring in small testable steps.
Development then should include documentation throughout its development and support program testing throughout to meet the overall design requirements. Documention is important whether working individually or collaboratively. Documentaion includes comments stored within programs where supported by the programming language (not all languages support comments) and outside the program (such as in web pages).
True/False. For each of the following statements, work with an elbow partner to determine if the statements are true or false.
For the false statements, modify the statements so they are meaningful and true.
Program documentation describes the function and development of program segments.
Comments written in a program are read by the computer before the program can execute.
Program documentation is best done after the program is written and tested.
For efficiency reasons, program documentation should only be written when working in a collaborative program development environment.
If a programming environment does not support comments then none should be used.
Program documentation comments should be as terse as possible since they are internal notes to the developers.
Bookmark or store your these true statements for future reference.
Design requires a lot of effort throughout the programming project.
Write a short paragraph explaining to a new project manager the benefits of investing this time in the design process.
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
A program is expressed in a programming language.
The diagram below shows a circuit composed of two
Oral reading strategies such as "popcorn reading" where students take turns reading a paragraph and then pass the reading off to another student in the class, or other reading strategies such as students reading together quietly in pairs, can be used for longer texts.
Longer readings can be broken up by sections or paragraphs to speed the lesson up or keep students engaged.
Activity 1 could be assigned as homework from the day before as a step into this lesson to allow more time in class for the other readings:
Additional activity: Ask students to read the Preface (pages iii-iv) and Chapter 1 introduction and section 1.1 (pages 1-2) of Python for Everybody and answer these questions:
Students will use several different strategies for reading and writing responses based on their readings.
Classroom discussions and student responses (written and oral) will allow instructors to check for understanding.
Summative assessment will be included in Part 2 on the use of the PyCharm IDE.
Student handout filled in
Tweet from optional homework assignment
Progress recorded in Runestone for the General Introduction
Unit 2. Developing Programming Tools
Revision Date: Sep 08, 2019 (Version 3.0)Summary
PyCharm, an IDE for Python, will be introduced. Keywords, file, and variable naming conventions will be addressed.
Outcomes
Overview
Students will learn what an IDE (Integrated Development Environment) is and why it is good to use one when programming.
Students will be able to find, configure and use the PyCharm IDE to write, save, run, debug and retrieve their Python modules according to the requirements of their instructor.
Student computer usage for this lesson is: required
For the Students
Have students go to the article Seven things you should know if you’re starting out programming at
http://www.theguardian.com/info/developer-blog/2011/oct/07/programming-developer-journalist
Introduction to PyCharm
Teacher note: This may be a good time to have students configure the default Working Directory as shown in the Python and PyCharm Installation and Configuration Guide file in the lesson resources folder.
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
(from http://www.pythonforbeginners.com/basics/keywords-in-python)
Students are to:
Sample code (will throw an error)
# author = 'iam tester'
# date July 4, 2024
# name.py
name = 'Ima Tester'
age = 15
print (name + " is " + age + " years old.")
The above code will throw an error, because age
is an integer and needs to be expressed as a string OR concatenated using a comma (,)
.
name = 'Ima Tester'
age = 15
print (name,"is",age,"years old.")
Important notes about naming your files and variables:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
(from http://www.pythonforbeginners.com/basics/keywords-in-python)
Students can work in pairs, side by side, to help each other through each step of the process.
Checks for understanding throughout the entire process of learning to use the PyCharm IDE by using active participation in trying each step of the process and having students help their elbow partner when difficulties arise.
Assessment tasks:
Unit 2. Developing Programming Tools
Revision Date: Jan 05, 2020 (Version 3.0)Summary
This is the first day of a two-session lesson sequence with topics covered by mini-lectures, explorations, and practice exercises.
Outcomes
Overview
Students will provide a definition of "algorithm".
Students will identify the characteristics of describing algorithms in English, pseudocode, or a programming language.
Students will demonstrate an understanding that there are different algorithms for different situations, such as parallel processing for multiple CPUs.
Student computer usage for this lesson is: none
PowerPoint Slides for mini-lectures (AlgorithmsPseudocode1.pptx in the Lesson Resources folder)
Excel sheet summary for creating a 4-by-4 Magic Square (MagicSquare4by4.xls in the Lesson Resources folder)
(optional) 16 papers, each with a number from 1-16 on it for students to use when acting out the magic square.
–Small group, then large group, review of two previous homework assignments (students were assigned to use two sources to find definitions of "algorithm" and were assigned to write down the steps involved in a daily task – creating a peanut butter and jelly sandwich; getting to school; brushing teeth; completing homework; etc…) The definitions, sources, and algorithm steps were to have been entered into their journal.
- Have students consider solving problems alone or with others. Point out that some computers have more than one processor and an algorithm can be written to do 2 or more processes in parallel. Consider some complications that might arise in the simple algorithms that have been developed by students if there were multiple CPUs.
Say: In programming, a code statement is a part of program code that expresses an action to be carried out. Note that it is a single action. Each step of an algorithm is to be carried out on its own and exactly as written.
– Act out selected homework “steps of a daily task” to highlight the potential ambiguity of English instructions. While acting out the algorithm have students look for the three sufficient parts of any algorithm - steps done in sequence, steps selected if a condition is met and steps done that are repeated.
Algorithms that appear similar differ in that they yield different side effects or results. For many tasks however, more than one algorithm has been developed that accomplish the same tasks - though they may not be equivalent in some ways. For instance, some may be simpler, some may be faster, some may be more efficient but all may still be be correct in the sense of achieving the desired result.
– Review Understanding by Design (UBD)-style slide for “Algorithms and Pseudocode: Need to Understand / Important to Know or Do / Worth Being Familiar With” (slide 2 of AlgorithmsPseudocode1.pptx presentation in Lesson Resources folder).
Students join groups that have developed algorithms to accomplish the same task. Students are to exchange algorithms and determine:
Time permitting, the class creates a 4-by-4 Magic Square, as described in MagicSquare4by4.xls in Lesson Resources folder. Sixteen students should be chosen to represent the sixteen numbers, and physically move into the 16 spaces following the algorithm in this document. (This provides an example of a “simple” algorithm that solves a more complex problem; it also gets the students out of their seats and moving around).
Reflect: Would it be easier or harder for 2 people to work on this together? (multiple CPUs or parallel processing)
–In AlgorithmsPseudocode1.pptx (presentation in Lesson Resources folder), walk through “Main Ideas”; “Representing Algorithms”; and “Sequential Algorithms” slides, including pseudocode circle example.
"In your words" pair/share as the concept of what an algorithm is (and what is not an algorithm -- e.g. "sort the numbers") is developed.
Class-wide development of the graphical organizer should be facilitated with scaffolding to support students who are having difficulty with the concept.
The following "Checks for Understanding" could be used to guide the students towards the two learning objectives.
Objective: Students will be expected to learn to provide a definition of "algorithm".
Objective: Students will learn to identify the characteristics of describing algorithms in English, pseudocode, or in a programming language.
Students will research formal definitions of algorithms. These will be entered into their journals and pair-shared with a peer.
Students will write out the sequence of steps in one or more daily living tasks, such as "brushing their teeth" or "building a peanut butter and jelly sandwich." These will be entered into their jourmals and pair-shared with a peer. Selected solutions will be "acted out" in the classroom.
Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Pre-lesson Preparation
This is the second session on algorithms
Summary
During the second session, the students will use pseudocode to describe an algorithm.
Outcome
Overview
Students will write pseudocode using sequencing, selection, and iteration constructs.
Student computer usage for this lesson is: optional
Files in the Lesson Resources folder:
AlgorithmsPseudocode2.pptx : PowerPoint Slides for mini-lectures
Student Handout and Key for Matching Pennies Game
Student Handout for Rock Paper Scissors
Psuedocode Summary and Examples of common Algorithms.docx
Journal: Describe the algorithm of another student. Is there enough detail to allow somebody to follow the steps?
Walk through “Selection Statements”; “Iteration / Repetition” slides from the AlgorithmsPseudocode2 file in the Lesson Resources folder. Emphasize:
1. Whenever you need to store information, it must go into a variable. So think about what variables might be needed when you are creating your algorithm
2. Program steps are executed in the order they are listed from top to bottom.
3. Selection and Iteration statements require conditionals. Identify a conditional as something that returns a True or False answer. If selects the next statement to occur by answering the conditional question as being true or false. I have in the past pointed out the True and Then both start with T so TRUE always does the THEN, wherease Else and False both end with LSE, so when the answer if FALSE, you do the ELSE.
While continues to loop as long as the conditional answer is TRUE. When the conditional answer is false, the algorithm jumps to the statement after the End While.
4. Nearly all programming languages are equivalent in terms of being able to express any algorithm. Each has its own way to use variables, conditions and repetition which are needed for a solution to almost all algorithms. Clarity and readability are important considerations when expressing an algorithm in a natural language or a programming language
During powerpoint, guide students through the Game of Matching Pennies (a student working copy and a solution key is in the Master Teacher Resource folder for this lesson).
Students work in pairs to create and share their pseudocode. Use the Rock Paper Scissors hand out to have student pairs psuedocode Rock Paper Scissors. Your algorithm should play the game 10 times and count the number of times each player wins and the number of times they tie.
Students may create their algorithms form scratch or remix exisiting ones.
If there is time, have groups switch algorithms and critique the algorithm of the other group.
Walk through pseudocode syntax summary handout called Pseudocode Summary and Examples of common Algorithms.docx in Lesson Resources folder.
Students work through challenges and check their results against sample solutions.
Review slide: "Why we have leap years."
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
A flowchart is a way to visually represent an a...
A programmer completes the user manual for a vi...
An algorithm has been developed to compute the ...
Central High School keeps a database of informa...
Consider the code segment below. The code consi...
Consider the following code segment. A segment of
The algorithm below is used to simulate the res...
The question below uses a robot in a grid of sq...
Two lists, list1 and list2, contain the names o...
Assign students to create pseudocode for leap years.
Pairing of students and crossing pairs to form groups of four should be used for the set of exercises that are part of this lesson.
Think-Pair-Share
Students will write pseudocode for algebra / geometry formulas. These will be entered into their class notes.
Students will write pseudocode for determining if a year is a leap year. This will be entered into their journals.
Unit 2. Developing Programming Tools
Revision Date: Jan 12, 2020 (Version 3.0)Summary
Students learn simple Python programs and their structure, as well as the basics of debugging.
Programs can be developed to solve problems (to help people, organizations or society), for creative expression, to satisfy personal curiosity or to create new knowledge.
Additional outcomes beyond the original purpose of a program are possible.
Outcomes
Student computer usage for this lesson is: required
For the Students:
https://github.com/spyder-ide/spyder
http://interactivepython.org/runestone/static/thinkcspy/index.html
Jigsaw: Divide students up into 5 groups. Have each group prepare a creative presentation on one of the topics below with visuals or an active component (rap, song, dramatic reading, etc.) to convey the message of that section. Groups have 15 minutes to prepare a 2-minute presentation.
To minimize time spent debugging in support programming goals:
Journal: Use formative assessment Questions 1 - 3:
Set up your IDE and Python at home (if you can) or use an online Python IDE such as https://repl.it/languages/Python3 or ideone.com . Type up a simple "Hello World" program and get it to run. Bring in evidence that it works or write a few sentences about the issues you are having in trying to install it or write about your experience using an online IDE, or write out the code for Hello World without looking at any notes and report on how easy or hard it was to remember the details. (Be careful not to make any student feel awkward for lack of a home computer they are allowed to install softare on)
Collect handwritten notes or evidence that Python 3 is set up at home or the student is able to use https://repl.it/languages/Python3 or ideone.com. As students work on tutorial, address specific issues with students who had trouble with install.
Complete an introductory tutorial:
Runestone Ch. 1 http://interactivepython.org/runestone/static/thinkcspy/GeneralIntro/toctree.html
Develop the beginnings of a chat bot where the computer and user introduce themselves to each other. The computer asks a question, the user provides a response and the computer responds back again, including the user input within the response (see https://groklearning.com/csedweek/ for ideas). Extend: Give your chatbot a personality like a friend, grandfather, therapist, or child.
First discuss: How can additional desired outcomes happen independently of the original purpose of a program? (examples: a program like chatbot could help someone learn a new language, provide entertainment for a shut-in. Computer games can increase reflexes, logic skills, provide motivation for someone in physical therapy)
Answer Formative assessment Questions # 4 - 6:
4) Name several different input devices.
5) How do we comment a Python program? Why do we use comments?
6) In your journal, make a tree diagram, name the three types of errors, and give examples of each. Which type of error do you think is the hardest to detect and why?
Write code to introduce yourself. Display your name. Greet and ask for three interests. Display the three interests and give a reply like "That's interesting!" Print your code. Next day: Have students introduce one another by “running the code" of a classmate. If you cannot get PyCharm to install, use http://ideone.com/ or repl.it or create this program by hand on paper.
Suggested strategies:
In your journal, make a tree diagram, name the three types of errors, and give examples of each. Which type of error do you think is the hardest to detect and why?
Find the errors in an algorithm or in Python statements covered to date
Define what debugging is and give examples of the 3 categories of bugs (syntax, logic(semantic) and runtime)
Describe the differences between programming and debugging.
Unit 2. Developing Programming Tools
Revision Date: Jan 05, 2020 (Version 3.0)Pre-lesson Preparation
Create a table of values of all types and print a copy of them on the cardstock for each group. Cut the papers up into individual cards, so each value is on its own card. Place each group's cards in a plastic bag.
Summary
Students are introduced to basic programming vocabulary, including integers, floats, strings, values, and expressions. They will work through a set of guided notes and slides, and, then, be released to explore Python through an independent (or paired) exercise.
Outcomes
Overview
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Runestone: Values and Expressions
Write a reflection on the homework from last class to write code to introduce yourself. The program should:
Did you run into any errors?
Do you feel that you can easily write this kind of code?
Share results with an elbow partner.
Teacher Note: Ideally, students are paired with people they don't work with as frequently, in order to promote classroom culture.
Point out that Python is a high level programming language. It provides many tools that make it easy to build complex programs with little effort. Among these tools are the ability to store and retrieve values and evaluate (find the single value of) expressions. Python can evaluate - find the specific value of - variables, variables with operators like plus and times, and of functions.
Numeric values can be constants like an integer, retreived form numeric variables or calculated based on expressions that combine values or variables witharithemtic operators.
In order for the computer to execute the code, it must translate(compile) the Python statements into a lower level language that the particular computer can understand and process. A variety of different variable types is one of the abtractions that are available in a high level programming language, and the language must define how the data is both stored and manipulated for each kind of data. You do not need to understand HOW the implementation works in order to use variables in your program.
Refer to the PowerPoint called Values and Types in the Lesson Resources folder.
'.'
is a float (ie. 2.0)True
and False
(they must be capitalized!)Check for Understanding: Have students write an integer on their paper (check with their elbow partner that it is a number). Ask students to turn that integer into a float with the same numerical value. Talk about going the opposite direction (float to int).
(Example answers: int: 3 float: 3.0 or 3.00 or ...)
"hello"
+ "world"
= "helloworld"
"hello"
+ " world"
= "hello world"
"hello"
+ 2 produces an errorTrue
and False
(they must be capitalized!)i< j
i<=j
i>=j
i>j
i == j
i!= j
('='
means something else!)Teacher Note: See Differentiation for two variations of this activity.
Students are to complete the Lesson 2.9 Order of Operations in Runestone (https://runestone.academy/runestone/books/published/thinkcspy/SimplePythonData/OrderofOperations.html)
Students will complete the Exploration Questions worksheet which is found in the Lesson Resources folder and complete one of the two exercises below.
2 + 5
5 * 2
5 ** 2
5 / 2
5 % 2
5 + 2 * 4
5 * 2 - 3
"pay attention to details'
' " what's for lunch?", my partner asked'
"What's for lunch?", my partner asked"
Ideas for grouping students:
Group Activity Variations:
Checks for understanding are incorporated throughout the lesson.
Exit ticket questions are incorporated into lesson.
Unit 2. Developing Programming Tools
Revision Date: Jan 12, 2020 (Version 3.0)Summary
Students will learn to manipulate variables and value assignments through an activity in which they must become the variable. By the end of the lesson, they will have identified variables as memory locations. They will also assign, copy, and destroy values in order to perform a swap algorithm and visualize Python's manipulation of variables and values in memory.
Outcomes
Overview
Student computer usage for this lesson is: none
For the Students:
Optional:
For the Teacher:
team1 = "Miami Heat"
team2 = "Washingon Wizards"
temp = team1
team1 = team2
team2 = temp
What is a variable? What are some things in your life that change often?
See slides in Lesson Resources Folder for a guided introduction.
Disposable cups, index cards, names for variables on strings (to hang around students' necks)
tree
, because the word tree
has no relevance to your age.)team1
because we’re talking about sports teams. Put the name around the student’s neck to indicate they have become the variable team1. This student has now become team1
, and should not respond to any other names! Note: A variable name will never have quotes around it - that would indicate that it is a string (i.e., a type of value rather than a variable's name). Variables can be identified (loosely) by words or letters that are not in quotes and are not keywords (for, if, else, etc.).team1
. Because we have never used this variable before, we are initializing it - putting something in this box (memory location) for the first time. On the board, write team1 = "Miami Heat"
team1
is the same as the Washington Wizards; it is only where were are currently keeping that team. Write “Miami Heat” on a notecard and put it into the cup.team1
and "Miami Heat", this time using team2
and "Washington Wizards".team1
and team2
?team1
and team2
to swap their values. Key point: when we access a variable and put its value in the place of another variable, that value is being copied. By doing so, however, any previous value in the variable is lost. temp
.temp
.)temp
variable, so the variables do not overwrite one another.temp
(named so because we will not be using it very long). Write temp = team1
on the board. Notice that in this assignment, it looks like we are setting a variable equal to another variable. Instead, we are setting the variable temp
equal to the value inside the variable team1
. This means that the value is copied to a second location.temp
.temp
cup.team1
. Write team1 = team2
on the board.team2
and copy the text from the notecard onto a new one. Move to team1
and replace the previous notecard with this new one.team1
. Rip up the notecard or throw it in the trash.team2 = temp
by following the same process. Look at the code written on the board and ask a student to walk us through each step.
CFU: Why did we create the variable temp
?
(Because variables overwrite the values of one another, and if we were to just set team2 = team1
we would lose one of the values.)
Students should notice:
In reality, Python actually has a "shortcut syntax" that allows us to make this swap in one step. It looks like this:
a,b = b,a
If we wanted to swap the values in team1
with team2
, we would simply have to write:
team1,team2 = team2, team1
Here, Python is doing exactly what we were doing. It is internally creating a variable (which has no name but serves the same purpose as our temp
variable), using it as a place holder, and then completing the swap.
To assign a value to a variable in Python we use the equal sign such as age = 15. On the exam produced by the College Board an arrow is used to indicate assignment.
Using the syntax on the College Board's exam reference sheet, an arrow “←” is used so the same assignment is written age ← 25.
Why would the makers of Python build in this function? What other uses does it have?
A version of this worksheet can be found in the Lesson Resources folder, titled "Swap to the Top".
Give students a list of games that have been played by the teams on the board, and the resultant new ranking. Have them create a piece of code that will reorganize the teams into the correct ranking. (They can assume that the variables team1
... team13
already exist and have been initialized to the Friday ranking.) Give them the option of doing so through the use of manipulatives, or on their own paper.
Discuss: All computer programs can be broken down into smaller, simpler steps. By developing components, testing to be sure they are correct and combining them you can create complex, correct programs. Did students get a feeling for systematic development, and how to trace a program one step at a time to verify correctness? Distribute Exit Ticket in Lesson Resources Folder which asks students to figure out the values of variables hello and goodbye after the code in each exercises been executed.
What is the difference between a variable in a math class and in a computer science class? What is the difference between a float and an integer? Why would you use one instead of the other?
Continue working on "Swap to the Top" worksheet.
Create a 3 column ‘one-pager’. In the left column, create a copy of the code from the activity (a swap algorithm) including team1
, team2
, and temp
that performs the complete swap. In the middle column, write steps that occur in the code (Step 1: Initialize variable and assign the value). In the third column, the students should draw a visual of what that looks like in terms of disposable cups and index cards. (They can just write the variable name on the cup, rather than drawing in a person as well.)
Checks for Understanding are embedded in the lesson. They are also shared below.
What is the type of “Miami Heat”?
(“Miami Heat" is a string. We know this because it has quotes around it .)
What is the difference between a value and a variable?
(Values can be stored in variables. The content of a variable can change to different values, but its name will always be the same because the name is just an identifier of a location in memory.)
Think-Pair-Share: A value is only safe (and not lost to the world of cyberspace) if it is in a variable. A variable can only hold one value at a time. How can we swap values between team1 and team2?
(various answers)
Why did we create the variable temp
?
(Because variables overwrite the values of one another, and if we were to just set team2 = team1,
we would lose one of the values.)
Task: Create a piece of code that will rearrange the ranking of the teams in order to reflect the outcome of previous games. (Independent Practice)
Unit 2. Developing Programming Tools
Revision Date: Jan 11, 2020 (Version 3.0)Summary
Students will learn how programs can solve problems using the various types of conditional statements in Python programs.
Decisions in programs are made using conditional statements.
Outcomes
How are comparison operators and Boolean expressions used with conditional statements?
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Reference Texts:
Online interpreters:
Think of a decision you make in your daily life and how you make the decision. In your journal, write about your decision and the process you use to decide.
Teaching note: take a few minutes to have students share responses (whole class, elbow partners, small groups).
==, !=, <, >, >=, <=
Includes AND, OR, and NOT
Say: The College Board’s exam reference sheet uses:
Example: Type various combinations of Boolean values (True / False) with Boolean operators (not, and, or) into the IDE (PyCharm)
Suggested Activity: What’s in the box?
Materials: Two small opaque containers, one small item for each container, two post-it notes.
Set-Up Directions: Set up the activity before the class arrives, following the directions below:
if numofGreen > numofBlack:
open green box
else:
open black box
Activity Directions:
Show the example from How to Think Like a Computer Scientist text (ActiveCode:6 (ch05_4)) or a similar example. Briefly demonstrate how to read flowcharts while showing the example from How to Think Like a Computer Scientist. Point out that the API (https://docs.python.org/3/library/) is always available as a language reference to help translate from algorithms/flowcharts into code. The API describes many tools to make it easier to create programs and is an important tool for all programmers.
If desired an if-else statement that returns boolean values can be replaced by the conditional expression or vice versa.
Instead of:
if (x < y):
return True
else:
return False
we could use:
return x < y
Define: A code segment refers to a collection of program statements that are part of a program.
Have students answer the following questions:
1. What will be printed by the following code segment?
x=15
if x==25:
print ('Pizza is yummy')
else:
print ('My teacher is awesome')
2. What will be printed by the following code segment?
x=35
y=52
if x!=25 and y==52:
print ('Pizza is yummy')
else:
('My teacher is awesome')
Suggested Coding Example:
n = input('Please enter your password: ')
if n=='P@s5w0d':
print ('Welcome, correct user!')
else:
print ('Incorrect, try again')
Say: The College Board’s exam reference sheet uses if and if-else statements like Python except it uses curly braces to indicate the block of statements controlled by if or if-else statements.
IF(condition)
{
}
IF(condition)
{
}
ELSE
{
}
1 Complete the following Runestone Activities
2 If/else practice problem: In the IDE, write a program that will prompt a user to enter a value for a food item. Evaluate the variable food.
If the value of food
is equal to “potato salad,” display “In Stock”. If the value of food
is not equal to “potato salad,” display “Not in Stock”.
Test your program with the following values for food:
pizza
popcorn
potato salad
Thinking about conditional execution, answer the following questions.
Alternate Instructional Strategy for Guided Practice :
Alternate Instructional Strategy for Journal: Interactive Journaling
Unit 2. Developing Programming Tools
Revision Date: Jul 22, 2019 (Version 3.0)Pre-lesson preparation
Students must have an understanding of using conditional statements, and have completed all the assignments from Lesson 2-8.
Summary
Students will learn how programs can solve problems using nested and chained conditional statements in Python programs.
Outcomes
Overview
Students must know that conditional statements can be used inside of other condtional statements using nested and chained conditional statements.
Vocabulary:
Student computer usage for this lesson is: required
In the Lesson Resources Folder:
Reference Text:
Project Ideas:
In your journal, write what will be displayed by the following code segment. How do you know your answer is correct?
x=2500
if x < 1000:
print(“small number”)
else:
print(“big number”)
Show physical representation using real life example by revisiting the box example from previous lesson:
Materials: Four small opaque containers, four small items, two opaque containers big enough to fit two small opaque containers, Six post it notes to label each container with a color
Set Up Directions: Set up the activity before the class arrives following the directions below:
if numofBlue > numofIndigo
if numofRed > NumofOrange
open red box
else
open orange box
else
if numofYellow > NumofGreen
open yellow box
else
open green box
The Activity Directions
Demonstrate the coding process of the example below.
Guided Activity 1 - Coding Example: Write a program that evaluates a variable "age" and displays a group age category (you are not an adult, you are a senior citizen or you are an adult.)Suggested Instructional Strategy - Think Aloud - model your thought process for solving this problem. Include comments in your code.
age = 18
if age < 18:
print(“you are not an adult”)
else:
if age is > 65:
print(“you are a senior citizen”)
else:
print(“you are an adult”)
Write a program that prompts the user for their age and displays their age category ( you are not an adult, you are a senior citizen or you are an adult.) If they are older than 200 display a message that reads "humanly impossible".
age = int(input("How old are you"))
if age < 18:
print("you are not an adult")
elif age > 200:
print("humanly impossible")
elif age >= 65:
print("you are a senior citizen")
else:
print("you are an adult")
Assign students random numbers from 0 - 250. Have students decide what group they belong to (child, adult, senior citizen, not human) and explain why they made their choice. *** You could have students physically move into the groups, hold up a sign with their answer or answer quietly in their journal.
***Note
It is recommended that:
All partners should be actively involved in the program development. For example, you may choose to employ Pair Programming, in which one partner “drives” (types and uses the mouse) while the other “navigates” (reviews and helps to guide what the driver is doing), with the partners changing roles every 20 minutes. Another method of collaboration is for each partner to develop pieces of the program, combine those pieces, and provide frequent feedback to each other during the development process.
-The College Board Computer Science Principles, Performance Assessment ©2014
Thinking about Nested and Chained Conditional Statements, answer the following questions:
Extensions
Homework
Alternate Instructional Strategy:
Alternate Instructional Strategy: Interactive Journaling
Students will create a collaborative program demonstrating concepts introduced in this two part lesson. Students will be assessed using a rubric and will reflect on their learning in their journal
Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Summary
In this lesson, students will be introduced to the concepts of iteration and for
loops.
Outcomes
Overview
Note: Turtle graphic examples in this lesson work with the community version of the PyCharm IDE and Python 3.4.1.
Students must understand that programs use the concept of iteration to perform repeated tasks.
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Required materials:
Useful additional resources:
Discuss with the school’s AP Testing Coordinator before presenting to students.
Schools exam registration policies and procedures
AP Exam fees, fee policies, and fee reductions
Confirm that students have joined the MY AP class section.
Show the AP Exam Registration presentation.
Give student’s time to register for the exam.
Verify that students can see the date and time of their exam in the class section view in My AP.
Journal: Think about events in your life that require a repeated action. They could be something simple such as eating a bowl of cereal. List two events in your life that require an action to be repeated. What is the action? What prompts the need for the action to happen? How often does the action happen?
Note: Students will extend their reflections later in the lesson.
Materials: 5-10 objects that can be stacked (lego, duplo blocks, plastic cups…)
The activity: Place the objects on a table.
1.Say: “At the conclusion of this activity, all of the objects will be stacked.”
Chose one object to begin with.
2. Say: “I will start with this object and I will continue to stack until there are no single objects left on the table. How many times do you think I will stack an object? Why?”
3. Ask: "Are there any single objects on the table?”
Students should answer yes. Stack one object on your beginning object
4. Ask “ Are there any single objects on the table?”
Students should answer yes. Stack one more object on your started stack. Continue to ask if there are any single objects on the table until the stack is completed and there are no more single objects on the table. Keep a tally of how many times you repeated the process.
5. Ask: “How many times did we repeat the process? Did your prediction match the result?"
6. Explain to the students how the activity represents the concept of iteration and continue into the discussion of iteration.
Computers are used in assembly lines and other places with lots of repetition because they can be almost perfectly accurate thanks to sensors that can be calibrated to the millimeter, and without needing to take a break.
Choose one of the events you wrote about in your previous journal entry. Take a moment to write the pseudocode for the repetitive action associated with that event.
Note: Check for understanding while students are working.
Example: Eating a slice of pizza:
While pizza on plate
pick up from plate
take a bite
place on plate
bite is consumed
loop
This guided activity introduces students to for
loops using turtle graphics.
(See handout in Lesson Resources folder: Turtle Graphics Guided Activity: The for loop)
Give students the following code stem. Have the students alter the code to perform the listed tasks.
Code Stem:
import turtle # Allows us to use the turtles library
window = turtle.Screen() # Creates a window to display graphics
bob = turtle.Turtle() # creates a turtle named bob
#Write your code here
window.exitonclick() # Exits the window when clicked
1. Have the turtle draw a triangle using a turtle
2. Now that you know how to add turtles and program them to draw lines repeatedly, use your imagination and creative ability to create your own picture using multiple for
loops and turtles.
Journal: In your journal summarize the process you used to create your picture. What problems did you encounter? What concepts do you need clarified?
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
Consider the following code segment, which uses...
The following question uses a robot in a grid o...
Students can be given a copy of the guided activity handout to follow along.
a variety of checking for understanding techniques
quick quizzes
peer review
interactive journaling
Students will use for loops and turtle graphics to create graphic representations of iteration. They modify a code stem using turtle graphics to:
1. draw a triangle
2. draw a picture using multiple for loops and turtles.
Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Summary
Students continue learning about iteration by using while
loops and nested iteration. Students work through a guided tutorial on while
loops and learn more turtle graphics features. They also have the opportunity to utilize the pair programming model to facilitate collaboratively writing programs using for
loops, while
loops, and turtle graphics. Throughout the lesson, students are given the opportunity to use their journal as a reflective tool.
Outcomes
while
loops. for
and while
loops can be written (nested) inside of other for
and while
loops.Outline
for
and while
loops with turtle graphicswhile
loops. for
and while
loops can be written (nested) inside of other for
and while
loops.Student computer usage for this lesson is: required
In the Lesson Resources folder:
Other:
What will be displayed at the end of this program?
y=0
for x in range (0, 8):
y += 1
print (y)
Define the Pair Programming Model: As the name implies, pair programming is where two programmers share one computer. One programmer codes while the other observes the code as it is typed in. The two programmers switch roles frequently. Common models such as pair programming exist to facilitate collaboration.
Introduce the Activity:
Solutions to both programs are in the slideshow.
Open Repeat Loops.ppt in the Teacher Resourses.
Say: The College Board’s exam reference sheet uses REPEAT loops instead of for and while loops. The REPEAT n TIMES { } executes the block of statements n times.
The College Board's REPEAT UNTIL(condition) { } structure executes the block of statements without ending until the Boolean expression condition evaluates to true. If the condition never evaluates to true the loop coninue indefinitely (called an infinite loop).
In the REPEAT UNTIL(condition), the Condition is evaluated before the loop body is executed so if the condition evaluates to true the loop body is never execued.
Ask: Which of the two REPEAT loops is most like the Python for loop and which is most like the Python while loop?
Display the example REPEAT loops questions in the slideshow, one at a time. Give the students a moment to determine the answer, then prompt students for his/her response "How many chose Answer A?" Then do the same for B, C, D. Then give correct answer (answer is in the Notes section of the ppt).
Journal: In your journal, summarize the process that you used with your partner to create the collaborative project. How did each partner contribute? Did you have any differences, if so, how did you resolve them? Was there any benefits to working in a pair ie able to identify programming and/or algorithm errors?
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
A summer camp offers a morning session and an a...
The code segment below uses the procedure IsFound
The figure below shows a robot in a grid of squ...
The figure below shows a robot in a grid of squ...
The procedure Draw (length, direction) is used to
Various checking-for-understanding techniques:
Quick quizzes
Peer review
Interactive journaling
Students will work collaboratively to develop a program that uses nested iteration and turtle graphics.
Unit 2. Developing Programming Tools
Revision Date: Jan 12, 2020 (Version 3.0)Summary
In Python, a function is a named sequence of statements that belong together. In this lesson, students learn why functions are used, how they are used, and how they are defined.
Outcomes
Overview
Source
Students will work extensively with the online version of How to Think Like a Computer Scientist (HTLACS) hosted by Runestone Interactive.
Students will understand the purpose of functions and how they allow a program to be built and maintained in a modular way.
Predictable Misunderstandings:
- students often think that functions (or any code) written will run. They don't connect that it must be called in order to be run.
- students often think that functions have access to variables that they don't have access.
Student computer usage for this lesson is: required
Other:
Point out: Data values can be stored in simple variables, lists of items, or standalone constants and can be passed as input to, or output from, procedures.
Say: The exam reference sheet uses the name PROCEDURE instead of the Python word function. It provides:
Say: The entire exam reference sheet will be given to students when they take the end of course exam.
.
Homework: Students should read Python for Everybody Chapter 4: Sections 4.7, 4.8 and 4.9. Complete Exercises 2 and 3.
Answer the following questions:
Students should be paired through this exercise since paired discussion is used for formative assessment. Question can be provided to students through a variety of formats including production of a Google form or using student response systems.
Three suggested strategies are:
After Activity D, have students compare results with their elbow partners. Discuss any unresolved issues. This strategy can be used after any check for understanding.
After Activity F, ask students to suggest a rule for creating functions that would help avoid this error.
Students work alternately between the web site, partners, and the whole group. Teachers are to monitor student responses to the questions following each activity to be sure that students are addressing the key content within each activity.
Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Summary
This is the third session of a three-session lesson sequence with four topics covered by mini-lectures, explorations, and practice exercises.
Outcomes
Overview
An algorithm is more than just a sequence of steps: levels of abstraction are crucial to the working of algorithms, and sequencing, iteration, and other control structures are ubiquitous.
There are various ways of implementing the algorithm - running sequentially or parts running in parallel.
Student computer usage for this lesson is: optional
In Lesson Resources folder:
[Optional topic] Wikipedia article on Conway date algorithm.
Access to Youtube videos of people and Lego Robots solving Rubik's cubes.
Videos:
https://www.youtube.com/watch?v=X0pFZG7j5cE and /or
https://www.youtube.com/watch?v=_d0LfkIut2M
https://www.youtube.com/watch?
One or more Rubik's cubes.
Links to PDF copies of youcandothecube's solution to Rubik's cube (also copied into the Lesson Resources folder):
You Can Do the Rubik's Cube
Daily Homework Review
Go to this link: https://playtictactoe.org/ to demonstrate an online Tic Tac Toe game
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
A programmer wrote the program below. The program
Consider the following program code. The block ...
In the program below, y is a positive integer (...
Programs I and II below are each intended to ca...
Two grids are shown below. Each grid contains a...
For the optional activity (Conway Algorithm), some students may have difficulty adding and subtracting dates to translate from a known day-of-the-week to another day in the same month. A chart on the wall, or a current calendar, could be a help.
Some students who are strong in other areas will have difficulty with the spatial aspects of manipulating a cube while retaining an orientation that will let them complete the steps of one of the sub-algorithms without errors. They may need to be paired with another student or the instructor until they master the technique of holding the cube fixed while rotating a face.
The notation of face turning (e.g. R versus R' or L versus L') can be confusing. Having the students practice with an empty jar with a lid can help. Orient the lid up (U), down (D), left (L), right (R), front (F), or back (B). The hand movement to screw the lid on is the same hand movement needed to perform the non-accented face turn. The hand movement needed to screw the lid off is the same as the accented turn (U', D', L', R', F', B').
Variation for class that does not have Rubik's cubes: Use the images from the Solution Guide: www.youcandothecube.com
Online rubik's cube solver:
The following "Checks for Understanding" could be used to guide the students towards the three learning objectives.
Objective: SWBAT translate sample pseudocode into a Python function.
Objective: SWBAT recognize layers of abstraction for solving a Rubik's cube.
SWBAT to identify sequencing, selection, and iteration elements in a problem solution.
Students will translate prior pseudocode into Python routines. They will recognize if their programs work correctly.
Students will deconstruct one of the Rubik's cube solution stages. These analysis results will be shared and critiqued.
Unit 2. Developing Programming Tools
Revision Date: Jan 05, 2020 (Version 3.0)Summary
In the first portion of this lesson, students continue their inquiry into the properties of functions, with a focus on communication to and from other functions. In the lab portion of the lesson, students develop three Python modules using both Runestone Interactive and their Python IDE. Students use their own functions to perform calculations and draw a variety of polygons and a circle using turtle graphics.
Outcomes
Overview
Session 1
Session 2
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Other:
Teaching Note:
Use of a format such as Google forms is sugggested for collecting student responses to the questions for each activity. It is important to keep this portion of the class moving so students have enough time for the labs. Have students work with partners during their program development so they will have someone to share their progress with. Use a timer and have students briefly share their progress roughly every 10 minutes. This will not only help them understand an iterative development process, but also gives students practice with a collaborative development style.
power
inside the function?power
given that value?drawSquare
, drawTriangle
, and drawOctagon
, along with main module code that calls each function.drawPolygon
function code and finish implementing the drawPolygon
function.drawCircle
function in Finally a Circle (the second half of the Lessons from a Triangle lab).
Iterative development works by developing, then sharing, programs at many points during the development process. Students should work in pairs as they create their programs and share the work through various completion stages.
Students who are completing projects quickly should be introduced to the Python turtle API at (https://docs.python.org/3.4/library/turtle.html). Students can investigate and implement such methods as fill
, speed
and others as described by the API documentation.
Check for understanding by assessing student performance on the Runestone Interactive questions. Students should first try to resolve any difficulties with their partners and groups.
Students should be able to make suggestions for creating and using functions.
Identify and address any areas discovered that students have been unable to come to a consensus understanding.
Have students reflect on the pair programming process as prompted in the lesson.
Create functions that receive parameters, perform calculations using those parameters, and return a value.
Write a function to return the slope and y-intercept of a function of the line through two points.
Write functions to create a variety of polygons and a circle.
Unit 2. Developing Programming Tools
Revision Date: Sep 08, 2019 (Version 3.0)Summary
Students will use the online book Python for Everybody to complete a two-session guided lab in which they will explore the use of strings in Python.
Outcomes
Students will be able to:
len
function to get the number of characters in a string[m:n]
find
method and slicingOverview
Session 1:
Session 2:
for
and while
loops. Students must decide which loop structure is appropriate, based on the nature of a program's requirements.Student computer usage for this lesson is: required
In the Lesson Resources folder:
Other:
find
method for Python 3.4 can be found at:Journal Question: What is a string?
stringtester.py
to test code as they go though the lesson.Section 6.1: A string is a sequence
Section 6.2: Getting the length of a string using len
len
function, which returns the number of characters in a string. Explain that empty spaces between words and punctuation also count as characters. Remind students of previous lessons concerning ASCII values for all characters, including blank spaces and punctuation.fruit
variable from the previous sample, have students return the number of characters using the len
function.IndexErrors:
that the length of the string and the highest index value in that same string are not the same value. The length of the string banana
is 6; the index values are numbered from 0 to 5, inclusive.len
, then have students type the sentence into the console in PyCharm to check their answers.Section 6.3: Traversal through a string with a loop
while loop and incrementing the index value of each character.
Journal Question: Explain why the length of a string is one digit higher than the highest index value of the same string.
word = "alphabet"
index = 0while index < len(word):
letter = word[index]
print (letter)
index = index + 1
index += 1
in place of index = index + 1
.stringtester.py
file used to test the code that they created during the last lesson. Section 6.3: Traversal through a string with a loop continued
Sample solution:
fruit = "watermelon"
length = len(fruit)
index = length - 1
while index >= 0:
letter = fruit[index]
print(letter)
index -= 1
for
loop instead of a while
loop to traverse a string.for
loop to traverse a string.while
loop than a for
loop to traverse a string and share their ideas. Expect answers such as “it is easier to make a for
loop” and “it is harder to move backwards through a for
loop than a while
loop.”char
in the example is used as a variable and is not a keyword in Python. It can be replaced with another word or letter. Have students use x
instead of char
in their sample for
loop code to test this concept. This is an opportunity to have a discussion about using meaningful variable names so they have self-documenting code. Section 6.4: String slices
[n:m]
syntax to indicate returning a string from the nth character to the mth character, not including the mth character.print(fruit[0:3]) # returns app because a is in the 0th position and the second p is in the 2nd position.
# The slice goes to ‘p’ not including the ‘p’.
print(fruit[:3]) # Still returns app because a is in the 0th position.
# Leaving the first index blank begins the slice at the beginning of the string,
# and the second p is in the 2nd position.
# The slice goes to ‘p’ not including the ‘p’.
print(fruit[3:]) # Returns le because l is in the 3rd position.
# Leaving the second index blank ends the slice at the end of the string.
print(fruit[:]) # Returns apple because n begins at zero and m goes to the end of the string.
fruit
is a string, what does fruit[:]
mean?Section 6.10: Parsing strings
find
method and apply slicing in this section.find
method. Explain that the find
method returns the position at which the substring we are searching for begins.find
method without error.message = 'Meet me at the clock tower @ 7:00 a.m.'
atSign = message.find('@')
print (atSign)
This code sample returns 27
, indicating that the @ sign is at index value 27 in the string.
Journal: How are string functions used in everyday life? (search engines to find information quickly, school databases to look up student information, many more). How much more efficient is a computer at looking through millions of strings of data compared to a human? Extension: what if you were looking for a particular face in a crowd in a video, how could computational tools enhance that process?
Students can work in pairs while new concepts are introduced and practiced.
One advanced student could be assigned to be the "checker" for each row and have them raise a flag or something similar when they have checked off everybody in their row as having one small group of programming exercises complete and correct. Possibly offer a token prize to the winning row.
For example, after Section 6.3, the following exercise could be assigned:
Code checks for understanding and concept checks for understanding are provided with each new function, method, or concept introduced.
Summative coding assessment:
Sample answer code:
name = 'Pat Miller'
space = name.find(' ')
firstName = name[0:space]
print (firstName)
It is recommend that a 10-question multiple choice quiz that requires students to evaluate code samples from these lessons, determining the output or possible outcomes when the code is run be developed.
Unit 2. Developing Programming Tools
Revision Date: Jun 11, 2020 (Version 3.0)Summary
This lesson answers the question "What is a list and what can I do with one?". Students will find the answer to this question by exploring list operations and methods, as well as investigating how lists are modeled in real-world situations.
Outcomes
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Other:
Journal:
Solicit some responses. Point out that different lists contain different kinds of information.
Say: In programming, we use data collections like lists for much the same reason as you use lists. A list is a sequential collection of data values that can be referenced using a single name and each value in the list is identified by an index. In some other programming languages, lists can be referred to by different names, such as an array. Today we are going simulate the way Python implements lists.
Optional: Review the string commands. Use the Lists.docx found in the Lesson Resources folder.
See the file called LinkyListy Role Play in the Lesson Resources folder. Note: You can change student names to students within your class.
Create a human “list of students”. See the file called LinkyListy Role Play in the Lesson Resources folder. Note: The directions below are an example. Change student names to students within your class.
Create a List of students by starting with an empty list and modify the list by following program below.
Designate a section of the board or a poster to act as the console/printer for output and a volunteer student to act as the printer driver.
Designate an area at the front of the room for the computer memory (and future students).
As students are called by the program, have each student come up to stand in front of the room where memory resides.
Have each student point to the student that follows them to form a linked list as they come to the front.
LinkyListy Role Play Program:
students = []
students.append('Joe')
students.append('Pat')
students.append('Alea')
students.append('Marta')
print(students)
#add additional commands to append or insert 4 or 5 more students
print(students)
print(len(students))
print(students[3])
students.reverse()
print(students)
print('David' in students)
students.sort()
print(students)
more = ['Tom', 'Laverne']
students = students + more
print(students)
pets = ['fish'*3,'dog']
del students[1]
del students[2:4]
students.insert(0, 'Jennifer')
students = students + pets
print(students)
print(students.index('Marta'))
1.2.2 Check for understanding:
Ask students to give an example and then explain the effect of several of the List methods. For example, students.append(“Zoe”) would add Zoe to the end of the list of students. students.insert(4, “Larry”) would add Larry at index position 4 and slide everyone else down one slot. This could be done as a placemat activity. Use different colored markers for each student to write the example. Turn placement and ask the next student to explain the effect.
Notes:
list: len(students)
print(students[2])
List Membership (in, not in): print(“Mary” in students)
Concatenation and repetition (+ *):Make a list of more Python commands on sentence strips. On back of the sentence strip, write the output or trace of the statement after it has executed onto the back of the card. Have one student hold the deck of cards and cycle through them. Ask students to read a card and predict the output. Meanwhile, students who are in the list will change positions to demonstrate the behavior within the list. The holder of the card provides feedback or congratulatoins in checking the correctness of classmate's responses.more = ["Tom", "Laverne"]
students = students + more
pets =['fish'*3,'dog']*2 # creates a list of ['fishfishfish','dog','fishfishfish','dog']
del students[2], del students[2:4]
stu = students.pop(2)
, stuLast = students.pop()
. The pop method pops (deletes and returns) an element at a given index or the last element if no index is provided.Say:
aList ← [value1, value2, value3,...] creates a new list that contains the values value1, value2, value3, and … at indices 1, 2, 3, and … respectively and assigns it to aList. |
aList ← [ ] creates a new empty list and assigns it to aList. |
aList ← bList assigns a copy of the list bList to the list aList. |
APPEND(aList, value) increases the length of aList by 1, and value is placed at the end of aList. |
REMOVE(aList, i) removes the item at index i in aList and shifts to the left any values at indices greater than i. The length of aList is decreased by 1. |
LENGTH(aList) evaluates to the number of elements currently in aList. |
List traversal - all elements: FOR EACH item IN aList { <block of statements> } The variable item is assigned the value of each element of aList sequentially, in order, from the first to last. |
Discussion: How are lists the same and how are they different from Strings?
Have the students do the Runestone lab activities for Lists to reinforce the above concepts. (http://interactivepython.org/runestone/static/thinkcspy/Lists/toctree.html)
Demonstrate that lists are mutable with the following activity
None
for the empty stalls.Discuss what kind of information can be acquired when a program processes data.
Describe some possible tables, diagrams, text, or other visual tools that could be used to communicate insight and knowledge gained from data.
Homework
Create a list of 5 students that contain the students' name, age, and hair color. Use a loop to extract the information for each student and print it out.
Teacher Note: Consider using the YumYumCupcake problem (see Formative Assessment) as part of tomorrow's opening exercises.
The first of two sessions creating and traversing lists in Python and EarSketch.
Discuss: Lists are collections of values combined into a single entity. What are some lists or other data collections used by music apps? How do the lists make the programs more appealing to their users?
Say: Today we will be learning to implement lists like those we acted out or use in our music apps.
Modify EarSketch Asg. 6.2 by adding a fourth music clip to the drums list. Modify the call to the makebeat function so it always uses the last music clip in drums. Test your program by adding a fifth music clip to drums.
The second of two sessions creating and traversing lists in Python and EarSketch.
Say: Lists are collections of values combined into a single entity. The collections of data in our lists yesterday were unchanging and we learned to access individual elements of the lists. Today we will use Python to add elements to a list and to obtain a part or slice of a list while the program is running.
Show the video: List appending and slicing.
Modify EarSketch Asg. 6.4 by adding another music clip to the clips list. Discuss with an elbow partner how the pan and vol lists change to correspond to the addition of the music clip. Make the appropriate changes to these lists in EarSketch Asg. 6.4.
In this session, we will review two topics required by the Create Performance Task - User Input and User Defined Functions
Say, we review defining our own custom functions. Once defined, we can use them like any other function.
The fundamental approach to solving large programming problems is breaking them down into small function definitions and then calling those functions to solve the original complex problem. You will use the strategy of breaking a problem down into smaller parts and implementing each part separately throughout your programming experience.
7. Chapter Seven: Defining Your Own Functions
Today we will define functions to respond to user input with dynamic lists in EarSketch.
Brainstorm some ways a user of an EarSketch program might want to affect the output produced by an Easketch program.
Choose either topic from the brainstormed list or the sample provided in User Input and Programmer Defined Functions below for students to implement. If you choose to implement suggestions brainstormed by students you may want to provide User Input and Programmer Defined Functions as an example.
Say: The exam reference sheet operations on lists include means of accessing and assigning values to a list and procedures for inserting, appending and removing list values.
Say: Students will have a copy of the entire exam reference sheet while they take the end of course exam from the College Board. The exam reference sheet also includes the FOR EACH item IN aList { }.
Have students move the user input section to a fourth user defined function. Students are to describe the algorithm used in their user input function in their own words.
Questions in the AP Classroom Question Bank may be used for summative purposes.
Sixty of the 80 questions are restricted to teacher access. The remaining 20 questions are from public resources.
Questions are identified by their initial phrases.
Two grids are shown below. Each grid contains a...
Consider the following program, which is intended
In the program below, the initial value of x is 5
The code fragment below is intended to display ...
The code fragment below is intended to display ...
yumYumCupcakes = ["chocolate mousse" *3, "vanilla creme", "strawberry fluff", "chocolate mousse"*2].
Have a customer purchase a vanilla creme cupcake if there are any, check how many chocolate mouse cupcakes are in the display case, bake some more, and add them in. Drop one cupcake on the floor and throw it away.Paired programming: Make a zoo of animals and demonstrate the use of at least 6 different list operations and methods. Try to make a story with your code.
Unit 2. Developing Programming Tools
Revision Date: Jul 22, 2019 (Version 3.0)Summary
To conclude the unit, students will complete a small project as well as a written assessment. The project requires students to parse text and search through lists or words to find a specific characteristic. The assessment covers integers, strings, booleans, loops, if statements, and lists.
Outcomes
Overview
Students should synthesize concepts from the previous lessons to create their first project in PyCharm. This lesson also pushes a student to think about how to design a function, and the relationship between algorithms and functions.
What are the key elements we need to think about when designing a function?
Student computer usage for this lesson is: required
In the Lesson Resources folder:
'is_palindrome'
that inputs a word and determines whether that word is a palindrome. If it is, return True
, otherwise return False
.'is_palindrome'
.Students work individually on the Word Play and Assessment which are found in the lesson resource folder.
Allow students to continue working to the end of class on their projects; have individual check-ins with students to make sure that they are on track and have a clear idea of what they need to complete the following day.
Option to allow students to complete Word Play with partners to promote collaboration, then complete the written assessment individually.
Teacher will monitor the progress of the students on each of the programs in Word Play.
Written assessment (see google drive)
Project Assessment (see google drive for project and rubric)