Unit 2. Developing Programming Tools
Revision Date: Jul 27, 2017 (Version 2.1.1)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.
Outcomes
Overview
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.
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 class
Note to the teacher: This lesson comes immediately after the practice Explore performance task. To provide more time for sharing and discussion, you may want to assign the reading and questions from Activity 1 as homework in addition or instead of the optional homework.
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 schetch 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.
This could be review from a previous computer class. If it is new to students assign one or both of the following.
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
Before dividing the students into groups for the next activity, it is important to address the paragraph at the beginning of the reading, which mentions the "coder stereotype" and includes a parenthetical note that the author believes this stereotype to be (largely) accurate. Explain that because of the breadth of application areas of computing in today’s world, this stereotype is not an accurate view of the diverse field of computing – there are a wide variety of people in computing and a wide variety of applications of computing education. See videos at http://mcwic.github.io/htmlblocks/computerscientistlibrary.html#top
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.
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: Jul 27, 2017 (Version 2.1.1)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.
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 17, 2017 (Version 2.1.1)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.
– Act out selected homework “steps of a daily task” to highlight the potential ambiguity of English instructions.
– 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).
– 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: Jul 27, 2017 (Version 2.1.1)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.
Things to stress with your students:
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. 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.
3. 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.
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. 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."
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: Jul 26, 2017 (Version 2.1.1)Summary
Students learn simple Python programs and their structure, as well as the basics of debugging.
Outcomes
Overview
Session 1:
Session 2:
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.
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
Explore a simple Python program together. [ 10 minutes]
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: Jul 26, 2017 (Version 2.1.1)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. In order for the computer to process 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)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 will complete the Exploration Questions worksheet which is found in the Lesson Resources folder.
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 22, 2017 (Version 2.1.1)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.
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: Jul 27, 2017 (Version 2.1.1)Summary
Students will learn how programs can solve problems using the various types of conditional statements in Python programs.
Outcomes
Overview
Decisions in programs are made using conditional statements.
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
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 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.
Check for understanding: Have students answer to 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')
Give the students the practice problem from Independent Activity 1 below. Have the students answer the following questions:
food
variable contains the following values?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 27, 2017 (Version 2.1.1)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: Jul 27, 2017 (Version 2.1.1)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:
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?
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: Jul 26, 2017 (Version 2.1.1)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 practice 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)
Have students work together to complete a coding activity that uses while
loops, for
loops, and/or nested iteration. Ideally, the students should design this program from scratch. They should think about a problem to be solved, describe it as an algorithm, and select the appropriate iteration structure. It is important to emphasize that the workload must be shared and each individual must make a contribution to the project within each group. Have students document an iterative design process: start with a general idea, break it into subparts, try it out, redesign, change and refine until you have explored a variety of creative options. The reflection journal at the end will comment on the group dynamics and problem solving used to create a positive group work environment.
Journal: In your journal, summarize the process that you used with your classmates to create the collaborative project. What was your original plan or algorithm? How did you use selection and iteration? What problems did you encounter? How did each group member contribute? What was the quality of the group dynamics? What concepts need to be clarified? How would these programs be changed if they were for widespread distribution rather than for personal use?
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: Jul 27, 2017 (Version 2.1.1)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:
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: Jan 16, 2017 (Version 2.1.1)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.
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
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: Jul 27, 2017 (Version 2.1.1)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: Jul 27, 2017 (Version 2.1.1)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: Jul 26, 2017 (Version 2.1.1)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
Overview
Session 1
Session 2
Student computer usage for this lesson is: required
In the Lesson Resources folder:
Other:
Review the string commands. As they enter the class, hand students a copy of the Warm-Up Get Ready for Lists.docx that is found in the Lesson Resources folder.
Discuss: What is a list? (A sequential collection of Python data values; each value is identified by an index.)
See the file calld 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'))
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: print(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.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.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.
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: Aug 19, 2016 (Version 2.1.1)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)