0% found this document useful (0 votes)
4 views106 pages

4-PythonIntroCourse Midterm Material

The document provides an overview of variables, constants, expressions, and statements in Python programming. It covers topics such as variable naming rules, data types, operator precedence, and conditional statements. Additionally, it explains how to handle user input and the importance of comments in code.

Uploaded by

fatima.n.marie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views106 pages

4-PythonIntroCourse Midterm Material

The document provides an overview of variables, constants, expressions, and statements in Python programming. It covers topics such as variable naming rules, data types, operator precedence, and conditional statements. Additionally, it explains how to handle user input and the importance of comments in code.

Uploaded by

fatima.n.marie
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

Variables, Expressions, and

Statements
‫اﻟﻣﺗﻐﯾرات‬
Constants
• Fixed values such as numbers, letters, and strings are called
“constants” - because their value does not change

• Numeric constants are as you expect


>>> print 123
• String constants use single-quotes (') 123
or double-quotes (") >>> print 98.6
98.6
>>> print 'Hello world'
Hello world
Variables
• A variable is a named place in the memory where a programmer can
store data and later retrieve the data using the variable “name”

• Programmers get to choose the names of the variables


• You can change the contents of a variable in a later statement
x = 12.2 x 12.2 100
y = 14
x = 100 y 14
Python Variable Name Rules
• Can consist of letters, numbers, or underscores (but cannot start
with a number)

• Case Sensitive
• Good: spam eggs spam23 _speed

• Bad: 23spam #sign var.12

• Different: spam Spam SPAM


Reserved Words

• You can NOT use reserved words as variable names / identifiers


and del for is raise assert elif
from lambda return break else
global not try class except if or
while
continue exec import pass
yield def finally in print
Statements

x=2 Assignment Statement


x=x+2 Assignment with expression
print x Print statement

Variable Operator Constant Reserved Word


Assignment Statements
• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the right hand
side and a variable to store the result

x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6).

0.6 0.6
x = 3.9 * x * ( 1 - x )
0.4

Right side is an expression. Once 0.936


expression is evaluated, the result
is placed in (assigned to) x.
x 0.936
A variable is a memory location
used to store a value. The value
stored in a variable can be updated x 0.6 0.93
by replacing the old value (0.6)
with a new value (0.93).

x = 3.9 * x * ( 1 - x )

Right side is an expression. Once


expression is evaluated, the result 0.93
is placed in (assigned to) the
variable on the left side (i.e. x).
Numeric Expressions
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication

• Asterisk is multiplication / Division

** Power
• Exponentiation (raise to a power) looks % Remainder
different from in math.
Numeric Expressions
>>> x = 2 >>> j = 23
>>> x = x + 2 >>> k = j % 5
+ Addition
>>> print x >>> print k
4 3 - Subtraction

>>> y = 440 * >>> print 4 ** * Multiplication

12 3 / Division

>>> print y 64
4R3 ** Power
5280 %
Remainder
>>> z = y / 1000 5 23 (Modulus)

>>> print z 20
5 3
Order of Evaluation
• When we string operators together - Python must know which one
to do first

• This is called “operator precedence”


• Which operator “takes precedence” over the others
x = 1 + 2 * 3 - 4 / 5 **
6
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power) Parenthesis
Power
Multiplicatio
• Multiplication, Division, and Remainder n
Addition
Left to Right
• Addition and Subtraction
x = 1 + 2 ** 3 / 4 * 5
Parenthesis
Power
Multiplicatio
n
Addition
Left to Right
x = 1 + 2 ** 3 / 4 * 5 1 + 2 ** 3 / 4 * 5
1+8/4*
5
Note 8/4 goes before 4*5 1+2*5
because of the left-right
rule.
Parenthesis 1 + 10
Power
Multiplicatio
n
Addition
Left to Right 11
Operator Precedence Parenthesis
Power
Multiplicatio
• Remember the rules -- top to bottom n
Addition
Left to Right
• When writing code - use parenthesis
• When writing code - keep mathematical expressions simple enough
that they are easy to understand

• Break long series of mathematical operations up to make them more


clear Exam Question: x = 1 + 2 * 3 - 4 / 5
Integer Division
>>> print 10 / 2
5
>>> print 9 / 2
4
• Integer division truncates >>> print 99 / 100
0
• Floating point division produces >>> print 10.0 / 2.0
floating point numbers 5.0
>>> print 99.0 /
100.0
0.99
This changes in Python
3.0
Mixing Integer and Floating Numbers in
Arithmetic Expressions
• When you perform an >>> print 99 / 100
0
operation where one
>>> print 99 / 100.0
operand is an integer and the
0.99
other operand is a floating
>>> print 99.0 / 100
point the result is a floating
0.99
point
>>> print 1 + 2 * 3 / 4.0 -
5
• The integer is converted to a -2.5
floating point before the >>>
operation
Some Data Types in Python
• Integer (Examples: 0, 12, 5, -5)

• Float (Examples: 4.5, 3.99, 0.1 )


• String (Examples: “Hi”, “Hello”, “Hi there!”)
• Boolean (Examples: True, False)
• List (Example: [ “hi”, “there”, “you” ] )
• Tuple (Example: ( 4, 2, 7, 3) )
Data Types
In C/C++:

int a;
• In Python variables, literals, and float b;
constants have a “data type” a=5
b = 0.43
• In Python variables are
“dynamically” typed. In some In Python:
other languages you have to
explicitly declare the type before a=5
you use the variable a = “Hello”
a = [ 5, 2, 1]
More on “Types”
• In Python variables, literals, and
constants have a “type” >>> d = 1 + 4
>>> print d
• Python knows the difference 5
between an integer number and a
string >>> e = 'hello ' +
'there'
>>> print e
• For example “+” means “addition” hello there
if something is a number and
“concatenate” if something is a concatenate = put together
string
Type Matters >>> e = 'hello ' + 'there'
>>> e = e + 1
• Python knows what “type” Traceback (most recent call last):
everything is File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
and 'int' objects
• Some operations are prohibited >>> type(e)
<type 'str'>
• You cannot “add 1” to a string >>> type('hello')
<type 'str'>
>>> type(1)
• We can ask Python what type <type 'int'>
something is by using the type() >>>
function.
Several Types of Numbers
>>> x = 1
• Numbers have two main types >>> type (x)
<type 'int'>
• Integers are whole numbers: -14, -2, 0, 1, >>> temp =
100, 401233 98.6
>>> type(temp)
<type 'float'>
• Floating Point Numbers have decimal >>> type(1)
parts: -2.5 , 0.0, 98.6, 14.0 <type 'int'>
>>> type(1.0)
• There are other number types - they are <type 'float'>
variations on float and integer >>>
>>> print float(99) / 100
Type Conversions 0.99
>>> i = 42
>>> type(i)
<type 'int'>
• When you put an integer and >>> f = float(i)
floating point in an expression >>> print f
the integer is implicitly 42.0
converted to a float >>> type(f)
<type 'float'>
• You can control this with the >>> print 1 + 2 * float(3) / 4 -
5
built in functions int() and float()
-2.5
>>>
String >>> sval = '123'
>>> type(sval)

Conversions <type 'str'>


>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() and TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
float() to convert between >>> type(ival)
strings and integers <type 'int'>
>>> print ival + 1
124
• You will get an error if the >>> nsv = 'hello bob'
string does not contain >>> niv = int(nsv)
numeric characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
User Input

• We can instruct Python to


pause and read data from
the user using the name = raw_input(‘Who are you?’)
raw_input() function print 'Welcome ', name

• The raw_input() function


returns a string Who are you? Chuck
Welcome Chuck
Converting User Input
• If we want to read a
number from the user, we inp = raw_input(‘Europe floor?’)
must convert it from a usf = int(inp) + 1
string to a number using a print “US floor: ”, usf
type conversion function

• Later we will deal with Europe floor? 0


bad input data US floor : 1
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary information
• Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = raw_input("Enter file:")
handle = open(name, "r") # This is a file handle
text = handle.read()
words = text.split()
String Operations
• Some operators apply to strings
>>> print 'abc' + '123‘
• + implies “concatenation” Abc123

• * implies “multiple concatenation” >>> print 'Hi' * 5


HiHiHiHiHi
• Python knows when it is dealing
with a string or a number and
behaves appropriately
Mnemonic Variable Names
• Since we programmers are given a choice in how we choose
our variable names, there is a bit of “best practice”

• We name variables to help us remember what we intend to


store in them (“mnemonic” = “memory aid”)

• This can confuse beginning students because well named


variables often “sound” so good that they must be keywords
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c=a*b
print x1q3p9afd print c

hours = 35.0
What is this rate = 12.50
code doing? pay = hours * rate
print pay
Exercise

Write a program to prompt the user for hours and


rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Summary
• Types (int, float, boolean, string, list, tuple, …)
• Reserved words
• Variables (mnemonic)
• Operators and Operator precedence
• Division (integer and floating point)
• Conversion between types
‫اﻟﺟﻣل اﻟﺷرطﯾﺔ ‪Conditions‬‬
x=5
Conditional Steps
Yes
X < 10 ?

Program:
print 'Smaller'
x=5
Yes if x < 10:
X > 20 ?
print
'Smaller‘
print 'Bigger'
if x > 20:
print 'Bigger'
print 'Finis' print 'Finis'
Comparison Operators
• Boolean expressions = an
expression that evaluates to
true or false < Less than
<= Less than or Equal
• Boolean expressions use == Equal to
comparison operators >= Greater than or Equal
evaluate to - True or False
> Greater than
!= Not equal
• Comparison operators look
at variables but do not Remember: “=” is used for assignment.
change the variables
x=5
Comparison
if x == 5 :
print 'Equals 5‘ Operators
if x > 4 :
print 'Greater than 4’

if x >= 5 :
print 'Greater than or Equal 5‘

if x < 6 :
print 'Less than 6'
Yes
X == 5 ?

x=5 No print 'Is 5'

if x == 5 : print 'Still 5'


print 'Is 5‘
print 'Is Still 5' print 'Third 5'
print 'Third 5’

The IF Statement
Indentation Rules
• Increase indent after an if statement or for statement (after : )
• Maintain indent to indicate the scope of the block (which lines are
affected by the if/for)

• Reduce indent to back to the level of the if statement or for


statement to indicate the end of the block

• Blank lines are ignored - they do not affect indentation


• Comments on a line by themselves are ignored w.r.t. indentation
Warning: Turn Off Tabs
• Most text editors can turn tabs into spaces - make sure to enable this
feature

• NotePad++: Settings -> Preferences -> Language Menu/Tab Settings


• TextWrangler: TextWrangler -> Preferences -> Editor Defaults
• Python cares a *lot* about how far line is indented. If you mix tabs
and spaces, you may get “indentation errors” even if everything looks
fine
This will save you
much unnecessary
pain.
increase / maintain after if or for
decrease to indicate end of block
blank lines and comment lines ignored
x=5
x=5
if x > 2 :
if x > 2 :
# comments
print 'Bigger than 2'
print 'Still bigger'
print 'Bigger than
print 'Done with 2'
2'
# don’t matter
for i in range(5) :
print 'Still bigger'
print i
# but can confuse you
if i > 2 :
print 'Bigger than
print 'Done with 2'
2'
# if you don’t line
print 'Done with i', i
# them up
Two Way
X=4
Decisions
• Sometimes we want to no yes
do one thing if a logical x>2
expression is true and
something else if the
print 'Not bigger' print 'Bigger'
expression is false

• It is like a fork in the


road - we must choose print 'All Done'
one or the other path
but not both
Two-way branch
X=4
using else :
x=4 no yes
x>2

if x > 2 :
print 'Smaller' print 'Bigger'
print 'Bigger'
else :
print
'Smaller' print 'All Done'

print 'All done'


yes
Nested x>1

Decisions no print 'More than one'

x = 42
yes
if x > 1 : x < 100

print 'More than one' no


if x < 100 : print 'Less than 100'

print 'Less than 100'

print 'All done'


print 'All Done'
Chained
Conditionals yes
x<2 print 'Small'
if x < 2 :
no
print 'Small'
yes
elif x < 10 :
x<10 print 'Medium'
print no
'Medium'
else : print 'LARGE'
print 'LARGE'
print 'All done'
print 'All Done'
Chained if x < 2 :
Conditional print 'Small'
elif x < 10 :
# No Else print 'Medium'
x=5 elif x < 20 :
if x < 2 : print 'Big'
print 'Small' elif x< 40 :
elif x < 10 : print 'Large'
print elif x < 100:
'Medium' print 'Huge'
else :
print 'All done' print
Multi-way Puzzles
Which will never print? if x < 2 :
print 'Below 2'
if x < 2 : elif x < 20 :
print 'Below 2' print 'Below 20'
elif x >= 2 : elif x < 10 :
print 'Two or more' print 'Below 10'
else : else :
print 'Something print 'Something
else' else'
The try / except Structure

• You surround a dangerous section of code with try and except.


• If the code in the try works - the except is skipped
• If the code in the try fails - it jumps to the except section
astr = 'Hello Bob‘ $ python notry.py Traceback (most
istr = int(astr) recent call last): File "notry.py", line 2,
print 'First‘ in <module> istr =
istrastr = '123‘ int(astr)ValueError: invalid literal for
istr = int(astr) int() with base 10: 'Hello Bob'
print 'Second', istr
astr = 'Hello Bob' When the first conversion fails - it
try: just drops into the except: clause and
istr = int(astr) the program continues.
except:
istr = -1
Output:
print 'First', istr First -1
Second 123
astr = '123'
try:
When the second conversion
istr = int(astr) succeeds - it just skips the except:
except: clause and the program continues.
istr = -1
try / except astr = 'Bob'

print 'Hello'
astr = 'Bob'
try:
print 'Hello' istr = int(astr)
istr =
int(astr) print 'There'
print 'There'
except: istr = -1
istr = -1
print 'Done', istr Safety net
print 'Done', istr
Sample try / except
rawstr = raw_input('Enter a number:')

try:
ival = int(rawstr)
except: Enter a number:42
ival = -1 Nice work

if ival > 0 : Enter a number:fourtytwo


print 'Nice work’ Not a number
else:
print 'Not a number’
Exercise

Write a pay computation program that gives the


employee 1.5 times the hourly rate for hours worked
above 40 hours (and regular 1.0 rate for less than 40
hours)

Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15
Exercise

Rewrite your pay program using try and except so


that your program handles non-numeric input
gracefully.
Enter Hours: 20
Enter Rate: nine
Error, please enter numeric input

Enter Hours: forty


Error, please enter numeric input
Summary
• Comparison operators == <= >= > < !=

• Logical operators: and or not

• Indentation
• One Way Decisions
• Two way Decisions if : and else :
Functions ‫اﻟﻌﻣﻠﯾﺎت‬
Stored (and reused) Steps
def
hello(): Program:
print 'Hello' Output:
print 'Fun' def hello():
print 'Hello' Hello
hello() print 'Fun' Fun
hello() Zip
print “Zip” print 'Zip‘ Hello
hello() Fun
hello()
We call these reusable pieces of code “functions”.
Python Functions
• There are two kinds of functions in Python
• Built-in functions that are provided as part of Python - raw_input(),
type(), float(), max(), min(), int(), str(), …

• Functions (user defined) that we define ourselves and then use


• We treat the built-in function names like reserved words (i.e. we avoid
them as variable names)
Function Definition

• In Python a function is some reusable code that takes arguments(s) as


input does some computation and then returns a result or results

• We define a function using the def reserved word


• We call/invoke the function by using the function name, parenthesis
and arguments in an expression
Argument

big = max('Hello
world')

Function name

>>> big = max('Hello world')


>>> print big
>>> w
>>> tiny = min('Hello world')
>>> print tiny
>>>
Max Function
A function is some
>>> big = max('Hello world') stored code that we
>>> print big use. A function takes
>>> ‘w’ some input and
produces an output.

“Hello world” max() ‘w’


(a string) function (a string)
Type Conversions >>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)
• When you put an integer and <type 'int'>
floating point in an expression >>> f = float(i)
the integer is implicitly >>> print f
converted to a float 42.0
>>> type(f)
<type 'float'>
• You can control this with the >>> print 1 + 2 * float(3) / 4 -
built in functions int() and float() 5
-2.5
>>>
String >>> sval = '123'
>>> type(sval)

Conversions <type 'str'>


>>> print sval + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
• You can also use int() and TypeError: cannot concatenate 'str' and 'int'
>>> ival = int(sval)
float() to convert between >>> type(ival)
strings and integers <type 'int'>
>>> print ival + 1
124
• You will get an error if the >>> nsv = 'hello bob'
string does not contain >>> niv = int(nsv)
numeric characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Building our Own Functions
• We create a new function using the def keyword followed by the
function name, optional parameters in parenthesis, and then we add a
colon.

• We indent the body of the function


• This defines the function but does not execute the body of the
function
def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'
print "I'm a lumberjack, and I'm okay." print
print_lyrics(): 'I sleep all night and I work all day.'
x=5
print 'Hello'

def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.' Hello
Yo
print 'Yo' 7
x=x+2
print x
Definitions and Uses

• Once we have defined a function, we can call (or invoke) it as many


times as we like

• This is the store and reuse pattern


x=5
print 'Hello'

def print_lyrics():
print "I'm a lumberjack, and I'm okay."
print 'I sleep all night and I work all day.'

print 'Yo'
print_lyrics() Hello
x=x+2 Yo
print x I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Arguments
• An argument is a value we pass into the function as its input when we
call the function

• We use arguments so we can direct the function to do different kinds


of work when we call it at different times

• We put the arguments in parenthesis after the name of the function


big = max('Hello
world')
Argument
def greet(lang):
Parameters if lang == 'es':
print 'Hola'
elif lang == 'fr':
print 'Bonjour'
• A parameter is a variable else:
which we use in the print 'Hello‘
function definition that is a
“handle” that allows the greet('en')
code in the function to Hello
access the arguments for a greet('es')
particular function Hola
invocation. greet('fr')
Bonjour
Return Values
• Often a function will take its arguments, do some computation and
return a value to be used as the value of the function call in the calling
expression. The return keyword is used for this.

def greet():
return "Hello " Hello Glenn
Hello Sally
print greet(), "Glenn"
print greet(), "Sally"
def greet(lang):
Return Value if lang == 'es':
return 'Hola '
elif lang == 'fr':
return 'Bonjour '
• A “fruitful” function is one else:
that produces a result (or a return 'Hello '
return value)
print greet('en'),'Glenn'
• The return statement ends Hello Glenn
the function execution and print greet('es'),'Sally'
“sends back” the result of Hola Sally
the function print greet('fr'),'Michael'
Bonjour Michael
Arguments, Parameters, and Results
>>> big = max( 'Hello world‘ )
Parameter
>>> print big
>>> w
def max(inp):
blah
blah ‘w’
for x in y:
Argument blah
blah Result
return ‘w’
Multiple Parameters / Arguments
• We can define more than def addtwo(a, b):
one parameter in the added = a + b
function definition return added

• We simply add more x = addtwo(3, 5)


print x
arguments when we call the
8
function

• We match the number and


order of arguments and
parameters
Void Functions

• When a function does not return a value, we call it a "void" function


• Functions that return values are "fruitful" functions
• Void functions are "not fruitful"
Functions – Code Reuse
• Organize your code into “paragraphs” - capture a complete thought
and “name it”

• Don’t repeat yourself - make it work once and then reuse it


• If something gets too long or complex, break up logical chunks and put
those chunks in functions

• Make a library of common stuff that you do over and over - perhaps
share this with your friends...
The range() function
• range() is a built-in function x = range(5)
that allows you to create a print x
sequence of numbers in a [0, 1, 2, 3, 4]
range
x = range(3, 7)
print x
• Very useful in “for” loops [3, 4, 5, 6]
which are discussed later in
the Iteration chapter x = range(10, 1, -2)
print x
• Takes as an input 1, 2, or 3 [10, 8, 6, 4, 2]
arguments. See examples.
Modules and the import statement
• A program can load a module import math
file by using the import radius = 2.0
statement area = math.pi * (radius ** 2)
12.5663706144
• Use the name of the module math.log(5)
1.6094379124341003
• Functions and variables
names in the module must be import sys
qualified with the module sys.exit()
name. e.g. math.pi
Summary
• Functions
• Built-In Functions:
• int(), float(), str(), type(), min(), max(), dir(), range(), raw_input(),…
• Defining functions: the def keyword
• Arguments, Parameters, Results, and Return values
Loops and Iteration
n=5 Repeated Steps
No Yes
n>0? Program: Output:

print n n=5 5
while n > 0 : 4
print n 3
n = n -1
n=n–1 2
print 'Blastoff!' 1
print n Blastoff!
print 'Blastoff' 0
Loops (repeated steps) have iteration variables that
change each time through a loop. Often these
iteration variables go through a sequence of numbers.
n=5
An Infinite Loop
No Yes
n>0?

print 'Lather' n=5


while n > 0 :
print 'Rinse' print 'Lather'
print 'Rinse'
print 'Dry off!'

print 'Dry off!'

What is wrong with this loop?


n=0
Another Loop
No Yes
n>0?

print 'Lather' n=0


while n > 0 :
print 'Rinse' print 'Lather'
print 'Rinse'
print 'Dry off!'

print 'Dry off!'


What does this loop do?
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop

while True:
> hello there
line = raw_input('> ')
hello there
if line == 'done' :
> finished
break
finished
print line
> done
print 'Done!'
Done!
while True: No Yes
True ?
line = raw_input('> ')
if line == 'done' :
....
break
print line
print 'Done!' break

...

print 'Done'
http://en.wikipedia.org/wiki/Transporter_(Star_Trek)
Using continue in a loop
• The continue statement ends the current iteration and jumps to the
top of the loop and starts the next iteration

while True:
> hello there
line = raw_input('> ')
hello there
if line[0] == '#' :
> # don't print
continue
this
if line == 'done' :
> print this!
break
print this!
print line
> done
print 'Done!'
Done!
No
True ? Yes
while True:
line = raw_input('> ') ....
if line[0] == '#' :
continue
if line == 'done' : continue
break
print line
...
print 'Done!'

print 'Done'
Indefinite Loops

• While loops are called "indefinite loops" because they keep going until
a logical condition becomes False

• The loops we have seen so far are pretty easy to examine to see if
they will terminate or if they will be "infinite loops"

• Sometimes it is a little harder to be sure if a loop will terminate


Definite Loops
• Quite often we have a list of items of the lines in a file - effectively a
finite set of things

• We can write a loop to run the loop once for each of the items in a
set using the Python for construct

• These loops are called "definite loops" because they execute an exact
number of times

• We say that "definite loops iterate through the members of a set"


A Simple Definite Loop
for i in [5, 4, 3, 2, 1] : 5
print i 4
print 'Blastoff!' 3
2
1
Blastoff!
A Simple Definite Loop
friends = ['Joseph', 'Glenn', 'Sally'] Happy New Year: Joseph
for friend in friends : Happy New Year: Glenn
print 'Happy New Year: ', friend Happy New Year: Sally
print 'Done!' Done!
A Simple Definite Loop
No
Yes
Done? Move i ahead for i in [5, 4, 3, 2, 1] : 5
print i 4
print 'Blastoff!' 3
print i
2
1
Blastoff!

print 'Blast off!'


Definite loops (for loops) have explicit iteration
variables that change each time through a loop. These
iteration variables move through the sequence or set.
The range() function (revisited)
• range() is a built-in function x = range(5)
that allows you to create a print x
sequence of numbers in a [0, 1, 2, 3, 4]
range
x = range(3, 7)
print x
• Very useful in “for” loops [3, 4, 5, 6]
which are discussed later in
the Iteration chapter x = range(10, 1, -2)
print x
• Takes as an input 1, 2, or 3 [10, 8, 6, 4, 2]
arguments. See examples.
A Simple Definite Loop iterating
over a range 7
6
for i in range(7, 0, -1) : 5
print i 4
print 'Blastoff!' 3
2
1
Blastoff!
Looking at in
• The iteration variable
“iterates” though the
sequence Five-element sequence
Iteration variable
• The block (body) of code is
executed once for each for i in [5, 4, 3, 2, 1] :
value in the sequence print i

• The iteration variable


moves through all of the
values in the sequence
Anatomy of a Loop
Set some variables to initial
values
for thing in data:
• The trick is “knowing” something Look for something or
about the whole loop when you do something to each
are stuck writing code that only entry separately, updating
sees one entry at a time a variable.

Look at the variables.


Looping through a Set
Before
9
41
print 'Before'
12
for thing in [9, 41, 12, 3, 74, 15] :
3
print thing
74
print 'After'
15
After
Counting in a Loop
Before 0
zork = 0
19
print 'Before', zork
2 41
for thing in [9, 41, 12, 3, 74, 15] :
3 12
zork = zork + 1
43
print zork, thing
5 74
print 'After', zork
6 15
After 6

To count how many times we execute a loop we introduce a counter


variable that starts at 0 and we add one to it each time through the loop.
Summing in a Loop
zork = 0
Before 0
print 'Before', zork
99
for thing in [9, 41, 12, 3, 74, 15] :
50 41
zork = zork + thing
62 12
print zork, thing
65 3
print 'After', zork
139 74
154 15
After 154

To add up a value we encounter in a loop, we introduce a sum variable that


starts at 0 and we add the value to the sum each time through the loop.
Finding the Average in a Loop
count = 0
Before 0 0
sum = 0
199
print 'Before', count, sum
2 50 41
for value in [9, 41, 12, 3, 74, 15] :
3 62 12
count = count + 1
4 65 3
sum = sum + value
5 139 74
print count, sum, value
6 154 15
print 'After', count, sum, sum / count
After 6 154 25
An average just combines the counting and sum patterns
and divides when the loop is done.
Filtering in a Loop

print 'Before'
for value in [9, 41, 12, 3, 74, 15] :
if value > 20: Before
print 'Large number',value Large number 41
print 'After' Large number 74
After

We use an if statement in the loop to catch / filter the


values we are looking for.
Search Using a Boolean Variable
found = False Before False
print 'Before', found False 9
for value in [9, 41, 12, 3, 74, 15] : False 41
if value == 3 : False 12
found = True True 3
print found, value True 74
print 'After', found True 15
After True

If we just want to search and know if a value was found - we use a variable that starts
at False and is set to True as soon as we find what we are looking for.
Finding the smallest value
smallest = None
print 'Before' Before
for value in [9, 41, 12, 3, 74, 15] : 99
If smallest is None : 9 41
smallest = value 9 12
elif value < smallest : 33
smallest = value 3 74
print smallest, value 3 15
print 'After', smallest After 3

We still have a variable that is the smallest so far. The first time through the
loop smallest is None so we take the first value to be the smallest.
The "is" and "is not" Operators
• Python has an "is" operator that
smallest = None can be used in logical
print 'Before' expressions
for value in [3, 41, 12, 9, 74, 15] :
if smallest is None :
smallest = value • Implies 'is the same as'
elif value < smallest :
smallest = value • Similar to, but stronger than ==
print smallest, value
print 'After', smallest
• 'is not' also is a logical operator
Summary
• While loops (indefinite)
• Summing in loops
• Infinite loops
• Averaging in loops
• Using break
• Searching in loops
• Using continue
• Detecting in loops
• For loops (definite)
• Largest or smallest
• Iteration variables

You might also like