Roles of Variables with Examples in Python ® © 2014 Project Lead The Way, Inc.Computer Science and Software Engineering.

Slides:



Advertisements
Similar presentations
Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Roles of Variables with Examples in Scratch
Introduction to Computing Science and Programming I
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Arrays. Memory organization Table at right shows 16 bytes, each consisting of 8 bits Each byte has an address, shown in the column to the left
Computer Science 1620 Loops.
Loops – While, Do, For Repetition Statements Introduction to Arrays
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Chapter 1 Program Design
 Pearson Education, Inc. All rights reserved Arrays.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
2015 Pre-Release Practice Click the button to try a random exam-style question. Click on the reveal button to check your answer.
Software design and development Marcus Hunt. Application and limits of procedural programming Procedural programming is a powerful language, typically.
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Python quick start guide
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Introduction to Python
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
Introduction to Programming Workshop 2 PHYS1101 Discovery Skills in Physics Dr. Nigel Dipper Room 125d
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
If statements while loop for loop
CIS 234: LOOPS Adapted from materials by Dr. Donald Bell, 2000 (updated April 2007)
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
ICOM 4035 – Data Structures Lecture 3 – Bag ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
Visual Basic Programming
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Research Topics in Computational Science. Agenda Survey Overview.
Role of variables. Fixed value Description: A variable without any calculation and not changed thereafter; for example we may need to remember the number.
Loops & List Intro2CS – week 3 1. Loops -- Motivation Sometimes we want to repeat a certain set of instructions more than once. The number of repetitions.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
IS2802 Introduction to Multimedia Applications for Business Lecture 4: JavaScript, Loops, and Conditional Statements Rob Gleasure
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Computer Program Flow Control structures determine the order of instruction execution: 1. sequential, where instructions are executed in order 2. conditional,
For Loop GCSE Computer Science – Python. For Loop The for loop iterates over the items in a sequence, which can be a string or a list (we will discuss.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Loop Structures.
CS 115 Lecture 8 Structured Programming; for loops
CSC 108H: Introduction to Computer Programming
Topics Introduction to Repetition Structures
Lecture 07 More Repetition Richard Gesick.
Arrays, For loop While loop Do while loop
Chapter (3) - Looping Questions.
T. Jumana Abu Shmais – AOU - Riyadh
Topics Sequences Introduction to Lists List Slicing
For loops Taken from notes by Dr. Neil Moore
Topics Sequences Introduction to Lists List Slicing
Comparing Python and Java
While Loops in Python.
Class code for pythonroom.com cchsp2cs
COMPUTING.
Introduction to Computer Science
Presentation transcript:

Roles of Variables with Examples in Python ® © 2014 Project Lead The Way, Inc.Computer Science and Software Engineering

A variable role is the reason we are using the variable. Variables always remember data for later use. But why are we trying to remember something? What Are Variable Roles?

Certain reasons for using a variable come up over and over. Eight roles cover 90% of the variable use by first-year programmers. What Are Variable Roles?  Fixed  Most recent  Accumulator  Aggregator  Stepper  Walker  Best-so-far  One-way flag

Quick Summary  Fixed Assigned once  Most recent Assigned unpredictably  Accumulator Running total  Aggregator Running list  Stepper Predetermined sequence of values  Walker Elements of iterator  Best-so-far Record holder  One-way flag Won’t reset flag until after iteration

Roles say why we are using the variable. Roles are not syntax. Syntax is whether the variable is a parameter of a function, an index, a return value, is being assigned to, etc. Roles can each have various types; roles are different than type. Types include int, string, list, tuple. What Are Variable Roles?

Create a single place to tweak a number used throughout a program. Low maintenance! Make code easier to read: No wondering “why subtract 20 here?” Make it easy to add features: User decides on the constant. Variable Role: Fixed Why use a fixed variable?

Pattern: Assigned at the head of a program or at the head of a code block. That means you see it on the left of the single equal sign, the assignment operator. Used in any way later but never assigned again. Convention suggests all caps. Variable Role: Fixed def calculate_total(bill): LOCAL_TIPPING_CUSTOM = 0.15

Retrieve or calculate once, use multiple times Remember state of a process Remember user input until needed Embed explanation Debug by printing Pattern: Appears on left of assignment and then in a variety of syntax Variable Role: Most-Recent Why use a most recent variable? length = raw_input(‘How many feet? ’) length = int(length)*12

To keep a running total or cumulative value – could be multiplication, addition, net,... Syntax: 1.Assigned to initial value before loop, 2.Assigned with *= or += inside of loop 3.Result used after loop Variable Role: Accumulator Why use an accumulator variable?

Variable Role: Accumulator Pattern: Initialize-Accumulate-Report accumulator = 0 # initialize for element in iterable: # accumulate accumulator += worth(element) print(accumulator) # report/use

To collect items and remember them all separately Common pattern: 1.Initialize to empty collection before a loop, 2.Append element to aggregate during iteration 3.The aggregate is used during or after the loop Variable Role: Aggregator Why use an aggregator variable?

Variable Role: Aggregator Pattern: Initialize-Aggregate-Report aggregator = [] # initialize for element in iterable: if condition_met_by(element): # append aggregator.append(element) how_many = len(aggregator) # report/use

Iterate a specific number of times Know that 5 th or 7 th or n th iteration is being executed Move forward a specified chunk of memory Represent integers – for factorials, e.g. Common syntax: Variable Role: Stepper Why use a stepper variable? for stepper in range(100): do_something()

Refer to members of a collection during iteration Common Patterns: As an element in a Python or Java™ iterator As an index of an array in Java/C/Python Variable Role: Walker Why use a walker variable? for walker in range(len(humans)): do_something_with(humans[walker]) for walker in humans: do_something_with(walker)

To remember the record holder while iterating across many opportunities to set the record Frequent pattern: 1.Initialize to worst-possible value before loop, 2.During iteration, compare something to best-so-far and maybe assign a new record. 3.After loop, best-so-far used as the true record-best from all iterations. Variable Role: Best-So-Far Why use a best-so-far variable?

# Start with a record that will be beat. tallest = 40 for person in group: # Check for record breaker. if person.height > tallest: # Set the new record! tallest = person.height # report/use print(‘Tallest person:’,tallest) Variable Role: Best-So-Far Pattern: Initialize Check & Set Record Report

To remember whether any of several opportunities meet a single condition. Common pattern: 1.“Clear” the flag (initialize) to say the opportunity has not yet been met. 2.Check for condition with each iteration and “raise” flag if true. 3.Flag is not cleared during iteration. 4.After loop, check if flag was raised during the iterations. Variable Role: One-Way Flag Why use a one-way-flag variable?

Variable Role: One-Way Flag Pattern: Initialize to clear flag Check & Raise Flag Report # Initialize with lowered flag pirate = False for song in storage: # Check for flag-raising condition if is_stolen(song): # Raise the flag pirate = True # report/use if pirate: warn_or_prosecute_pirate()