SlideShare uma empresa Scribd logo
1 de 20
Control flow
Michael Ernst
UW CSE 140
Winter 2013
Repeating yourself

Making decisions
Temperature conversion chart
Recall exercise from previous lecture

fahr = 30
cent = (f-32)/9.0*5
print fahr, cent
fahr = 40
cent = (f-32)/9.0*5
print fahr, cent
fahr = 50
cent = (f-32)/9.0*5
print fahr, cent
fahr = 60
cent = (f-32)/9.0*5
print fahr, cent
fahr = 70
cent = (f-32)/9.0*5
print fahr, cent
print "All done"

Output:
30 -1.11
40 4.44
50 10.0
60 15.56
70 21.11
All done
Temperature conversion chart
A better way to repeat yourself:
for loop
Loop body
is indented

Execute the body
5 times:
• once with f = 30
• once with f = 40
• …

loop variable or
iteration variable

A list

Colon is
required

for f in [30,40,50,60,70]:
print f, (f-32)/9.0*5
print "All done"
Output:

Indentation
is significant

30 -1.11
40 4.44
50 10.0
60 15.56
70 21.11
All done
How a loop is executed:
Transformation approach
Idea: convert a for loop into something we know how to execute

1.
2.
3.
4.

Evaluate the sequence expression
Write an assignment to the loop
variable, for each sequence
element
Write a copy of the loop after each
assignment
Execute the resulting statements

for i in [1,4,9]:
print i

i = 1
print i
i = 4
print i
i = 9
print i

State of the
computer:

i: 1
9
4

Printed output:

1
4
9
How a loop is executed:
Direct approach
1. Evaluate the sequence expression
2. While there are sequence
elements left:
a)
b)

Assign the loop variable to the next
remaining sequence element
Execute the loop body

Current location in list

for i in [1,4,9]:
print i

State of the
computer:

i: 1
9
4

Printed output:

1
4
9
The body can be multiple statements
Execute whole body, then execute whole body again, etc.

for i in [3,4,5]:
print "Start body"
print i
print i*i

loop body:
3 statements

Convention: often use i or j as loop variable
This is an exception to the rule that
variable names should be descriptive

Output:
Start body
3
9
Start body
4
16
Start body
5
25

NOT:
Start body
Start body
Start body
3
4
5
9
16
25
Indentation is significant
• Every statement in the body must have exactly the same indentation
• That’s how Python knows where the body ends
for i in [3,4,5]:
print "Start body"
print i
Error!
print i*i
• Compare the results of these loops:
for f in [30,40,50,60,70]:
print f, (f-32)/9.0*5
print "All done"
for f in [30,40,50,60,70]:
print f, (f-32)/9.0*5
print "All done"
The body can be multiple statements
How many statements does this loop contain?
for i in [0,1]:
print "Outer", i
for j in [2,3]:
print " Inner", j
“nested”
loop body:
print " Sum", i+j
2 statements
print "Outer", i

What is the output?

loop body:
3 statements

Output:
Outer 0
Inner 2
Sum 2
Inner 3
Sum 3
Outer 0
Outer 1
Inner 2
Sum 3
Inner 3
Sum 4
Outer 1
Understand loops through the
transformation approach
Key idea:
1. Assign each sequence element to the loop variable
2. Duplicate the body
for i in [0,1]:
i = 0
print "Outer", i
print "Outer", i
for j in [2,3]:
for j in [2,3]:
print " Inner", j
print " Inner", j
i = 1
print "Outer", i
for j in [2,3]:
print " Inner", j

i = 0
print "Outer", i
j = 2
print " Inner", j
j = 3
print " Inner", j
i = 1
print "Outer", i
for j in [2,3]:
print " Inner", j
Fix this loop
# Goal: print 1, 2, 3, …, 48, 49, 50
for tens_digit in [0, 1, 2, 3, 4]:
for ones_digit in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
print tens_digit * 10 + ones_digit

What does it actually print?
How can we change it to correct its output?
Moral: Watch out for edge conditions (beginning
or end of loop)
Test your understanding of loops
Output:

Puzzle 1:
for i in [0,1]:
print i
print i

0
1
1

Puzzle 2:
i = 5
for i in []:
print i

Puzzle 3:

(no output)

Reusing loop variable
(don’t do this!)

for i in [0,1]:
print "Outer", i
for i in [2,3]:
print " Inner", i
print "Outer", i

inner
loop
body

outer
loop
body

Outer 0
Inner 2
Inner 3
Outer 3
Outer 1
Inner 2
Inner 3
Outer 3
The range function
A typical for loop does not use an explicit list:
The list
for i in range(5): [0,1,2,3,4]
… body …
Upper limit
(exclusive)

range(5) = [0,1,2,3,4]
Lower limit
(inclusive)

range(1,5) = [1,2,3,4]
step (distance
between elements)

range(1,10,2) = [1,3,5,7,9]
Decomposing a list computation
• To compute a value for a list:
– Compute a partial result for all but the last element
– Combine the partial result with the last element

Example: sum of a list:
[ 3, 1, 4, 1, 5, 9, 2, 6, 5 ]
List z
List y
List c
List b
List a

sum(List a) = sum(List a) + 5
sum(List b) = sum(List c) + 6
…
sum(List y) = sum(List z) + 3
sum(empty list) = 0
How to process a list:
One element at a time
• A common pattern when processing a list:
result = initial_value
# Sum of a list
for element in list:
result = 0
result = updated result for element in mylist:
result = result + element
… use result

• initial_value is a correct result for an empty list
• As each element is processed, result is a
correct result for a prefix of the list
• When all elements have been processed,
result is a correct result for the whole list
Examples of list processing
• Product of a list:
result = 1
for element in mylist:
result = result * element

result = initial_value
for element in list:
result = updated result

• Maximum of a list:
result = mylist[0]
for element in mylist:
result = max(result, element)

The first element of the
list (counting from zero)

• Approximate the value 3 by 1 + 2/3 + 4/9 + 8/27 + 16/81 + …
= (2/3)0 + (2/3)1 + (2/3)2 + (2/3)3 + … + (2/3)10
result = 0
for element in range(11):
result = result + (2.0/3.0)**element
Making decisions
• How do we compute absolute value?
abs(5) = 5
abs(0) = 0
abs(-22) = 22
Absolute value solution
If the value is negative, negate it.
Otherwise, use the original value.
val = -10

if val < 0:
result = - val
else:
result = val
print result

val = -10

if val < 0:
print - val
else:
print val
The if body can be any statements
# height is in km
# height is in km
if height > 100:
if height > 100:
50:
Execution gets here only
then
print "space"
if height > 100:
print "space"
if “height > 100” is false
clause
else:
elifprint "space"
height > 50:
Execution gets here only
if height > 50:
else:
print "mesosphere"
if “height > 100” is false
t print "mesosphere"
elifprint "mesosphere"
height > 20:
AND “height > 50” is true
else:
else:
print "stratosphere"
else
clause
if height > 20:
else:height > 20:
if
print "troposphere"
print "stratosphere"
t print "stratosphere"
e
else:
else:
e print "troposphere"
print "troposphere"
troposphere
0

10

20

stratosphere
30

40

mesosphere
50

60

70

space
80

90

100

km
above
earth
The then clause or the else clause
is executed
if is_prime(x):
y = x / 0
else
y = x*x

Mais conteúdo relacionado

Mais procurados

CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE
CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE
CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE 0586umer
 
Limit aljabar ukb coba2 kelas 11
Limit aljabar ukb coba2 kelas 11Limit aljabar ukb coba2 kelas 11
Limit aljabar ukb coba2 kelas 11Amphie Yuurisman
 
Algebra 2 warm up 5.6.13
Algebra 2 warm up 5.6.13Algebra 2 warm up 5.6.13
Algebra 2 warm up 5.6.13Ron_Eick
 
関数プログラミングことはじめ in 福岡
関数プログラミングことはじめ in 福岡関数プログラミングことはじめ in 福岡
関数プログラミングことはじめ in 福岡Naoki Kitora
 
Equation of straight line
Equation of straight lineEquation of straight line
Equation of straight lineNadeem Uddin
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchartIamPe Khamkhum
 
Composition Of Functions
Composition Of FunctionsComposition Of Functions
Composition Of Functionssjwong
 
The Ring programming language version 1.5.3 book - Part 19 of 184
The Ring programming language version 1.5.3 book - Part 19 of 184The Ring programming language version 1.5.3 book - Part 19 of 184
The Ring programming language version 1.5.3 book - Part 19 of 184Mahmoud Samir Fayed
 
1 arrays and sorting
1 arrays and sorting1 arrays and sorting
1 arrays and sortingnotshoaib
 
Plotting points in rectangular coordinate system
Plotting points in rectangular coordinate systemPlotting points in rectangular coordinate system
Plotting points in rectangular coordinate systemAnirach Ytirahc
 
2.4 multiplication of real numbers 1
2.4 multiplication of real numbers 12.4 multiplication of real numbers 1
2.4 multiplication of real numbers 1bweldon
 

Mais procurados (20)

Basic practice of R
Basic practice of RBasic practice of R
Basic practice of R
 
CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE
CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE
CDMA - USE WALSH TABLE TO GENERATE CHIP SEQUENCE
 
Oct27
Oct27Oct27
Oct27
 
Limit aljabar ukb coba2 kelas 11
Limit aljabar ukb coba2 kelas 11Limit aljabar ukb coba2 kelas 11
Limit aljabar ukb coba2 kelas 11
 
Bisection method
Bisection methodBisection method
Bisection method
 
Binary search
Binary searchBinary search
Binary search
 
Numerical Method for UOG mech stu prd by Abdrehman Ahmed
Numerical Method for UOG mech stu prd by Abdrehman Ahmed Numerical Method for UOG mech stu prd by Abdrehman Ahmed
Numerical Method for UOG mech stu prd by Abdrehman Ahmed
 
Algebra 2 warm up 5.6.13
Algebra 2 warm up 5.6.13Algebra 2 warm up 5.6.13
Algebra 2 warm up 5.6.13
 
関数プログラミングことはじめ in 福岡
関数プログラミングことはじめ in 福岡関数プログラミングことはじめ in 福岡
関数プログラミングことはじめ in 福岡
 
12 doloops
12 doloops12 doloops
12 doloops
 
Equation of straight line
Equation of straight lineEquation of straight line
Equation of straight line
 
133467 p1a9
133467 p1a9133467 p1a9
133467 p1a9
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
Composition Of Functions
Composition Of FunctionsComposition Of Functions
Composition Of Functions
 
Pa1 flow chart
Pa1 flow chartPa1 flow chart
Pa1 flow chart
 
The Ring programming language version 1.5.3 book - Part 19 of 184
The Ring programming language version 1.5.3 book - Part 19 of 184The Ring programming language version 1.5.3 book - Part 19 of 184
The Ring programming language version 1.5.3 book - Part 19 of 184
 
1 arrays and sorting
1 arrays and sorting1 arrays and sorting
1 arrays and sorting
 
Plotting points in rectangular coordinate system
Plotting points in rectangular coordinate systemPlotting points in rectangular coordinate system
Plotting points in rectangular coordinate system
 
2.4 multiplication of real numbers 1
2.4 multiplication of real numbers 12.4 multiplication of real numbers 1
2.4 multiplication of real numbers 1
 
4 chap
4 chap4 chap
4 chap
 

Destaque

Prototyping is an attitude
Prototyping is an attitudePrototyping is an attitude
Prototyping is an attitudeWith Company
 
50 Essential Content Marketing Hacks (Content Marketing World)
50 Essential Content Marketing Hacks (Content Marketing World)50 Essential Content Marketing Hacks (Content Marketing World)
50 Essential Content Marketing Hacks (Content Marketing World)Heinz Marketing Inc
 
10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer ExperienceYuan Wang
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanPost Planner
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 

Destaque (6)

Application
ApplicationApplication
Application
 
Prototyping is an attitude
Prototyping is an attitudePrototyping is an attitude
Prototyping is an attitude
 
50 Essential Content Marketing Hacks (Content Marketing World)
50 Essential Content Marketing Hacks (Content Marketing World)50 Essential Content Marketing Hacks (Content Marketing World)
50 Essential Content Marketing Hacks (Content Marketing World)
 
10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience10 Insightful Quotes On Designing A Better Customer Experience
10 Insightful Quotes On Designing A Better Customer Experience
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media Plan
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 

Semelhante a 03 control

Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Ziyauddin Shaik
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88Mahmoud Samir Fayed
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3Paul Brebner
 
358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5sumitbardhan
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptxAzharFauzan9
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptxIvanZawPhyo
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshopBAINIDA
 
Stanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programmingStanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programmingYu-Sheng (Yosen) Chen
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersSheila Sinclair
 

Semelhante a 03 control (20)

Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Arrays and its properties IN SWIFT
Arrays and its properties IN SWIFTArrays and its properties IN SWIFT
Arrays and its properties IN SWIFT
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
07012023.pptx
07012023.pptx07012023.pptx
07012023.pptx
 
06.Loops
06.Loops06.Loops
06.Loops
 
The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30The Ring programming language version 1.4 book - Part 7 of 30
The Ring programming language version 1.4 book - Part 7 of 30
 
The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88The Ring programming language version 1.3 book - Part 18 of 88
The Ring programming language version 1.3 book - Part 18 of 88
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3
 
358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5358 33 powerpoint-slides_5-arrays_chapter-5
358 33 powerpoint-slides_5-arrays_chapter-5
 
Sorting
SortingSorting
Sorting
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Introduction to Kotlin.pptx
Introduction to Kotlin.pptxIntroduction to Kotlin.pptx
Introduction to Kotlin.pptx
 
01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx01 Introduction to Kotlin - Programming in Kotlin.pptx
01 Introduction to Kotlin - Programming in Kotlin.pptx
 
Iteration
IterationIteration
Iteration
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Stanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programmingStanford splash spring 2016 basic programming
Stanford splash spring 2016 basic programming
 
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And EngineersAnswers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
Answers To Selected Exercises For Fortran 90 95 For Scientists And Engineers
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 

03 control

  • 1. Control flow Michael Ernst UW CSE 140 Winter 2013
  • 3. Temperature conversion chart Recall exercise from previous lecture fahr = 30 cent = (f-32)/9.0*5 print fahr, cent fahr = 40 cent = (f-32)/9.0*5 print fahr, cent fahr = 50 cent = (f-32)/9.0*5 print fahr, cent fahr = 60 cent = (f-32)/9.0*5 print fahr, cent fahr = 70 cent = (f-32)/9.0*5 print fahr, cent print "All done" Output: 30 -1.11 40 4.44 50 10.0 60 15.56 70 21.11 All done
  • 4. Temperature conversion chart A better way to repeat yourself: for loop Loop body is indented Execute the body 5 times: • once with f = 30 • once with f = 40 • … loop variable or iteration variable A list Colon is required for f in [30,40,50,60,70]: print f, (f-32)/9.0*5 print "All done" Output: Indentation is significant 30 -1.11 40 4.44 50 10.0 60 15.56 70 21.11 All done
  • 5. How a loop is executed: Transformation approach Idea: convert a for loop into something we know how to execute 1. 2. 3. 4. Evaluate the sequence expression Write an assignment to the loop variable, for each sequence element Write a copy of the loop after each assignment Execute the resulting statements for i in [1,4,9]: print i i = 1 print i i = 4 print i i = 9 print i State of the computer: i: 1 9 4 Printed output: 1 4 9
  • 6. How a loop is executed: Direct approach 1. Evaluate the sequence expression 2. While there are sequence elements left: a) b) Assign the loop variable to the next remaining sequence element Execute the loop body Current location in list for i in [1,4,9]: print i State of the computer: i: 1 9 4 Printed output: 1 4 9
  • 7. The body can be multiple statements Execute whole body, then execute whole body again, etc. for i in [3,4,5]: print "Start body" print i print i*i loop body: 3 statements Convention: often use i or j as loop variable This is an exception to the rule that variable names should be descriptive Output: Start body 3 9 Start body 4 16 Start body 5 25 NOT: Start body Start body Start body 3 4 5 9 16 25
  • 8. Indentation is significant • Every statement in the body must have exactly the same indentation • That’s how Python knows where the body ends for i in [3,4,5]: print "Start body" print i Error! print i*i • Compare the results of these loops: for f in [30,40,50,60,70]: print f, (f-32)/9.0*5 print "All done" for f in [30,40,50,60,70]: print f, (f-32)/9.0*5 print "All done"
  • 9. The body can be multiple statements How many statements does this loop contain? for i in [0,1]: print "Outer", i for j in [2,3]: print " Inner", j “nested” loop body: print " Sum", i+j 2 statements print "Outer", i What is the output? loop body: 3 statements Output: Outer 0 Inner 2 Sum 2 Inner 3 Sum 3 Outer 0 Outer 1 Inner 2 Sum 3 Inner 3 Sum 4 Outer 1
  • 10. Understand loops through the transformation approach Key idea: 1. Assign each sequence element to the loop variable 2. Duplicate the body for i in [0,1]: i = 0 print "Outer", i print "Outer", i for j in [2,3]: for j in [2,3]: print " Inner", j print " Inner", j i = 1 print "Outer", i for j in [2,3]: print " Inner", j i = 0 print "Outer", i j = 2 print " Inner", j j = 3 print " Inner", j i = 1 print "Outer", i for j in [2,3]: print " Inner", j
  • 11. Fix this loop # Goal: print 1, 2, 3, …, 48, 49, 50 for tens_digit in [0, 1, 2, 3, 4]: for ones_digit in [1, 2, 3, 4, 5, 6, 7, 8, 9]: print tens_digit * 10 + ones_digit What does it actually print? How can we change it to correct its output? Moral: Watch out for edge conditions (beginning or end of loop)
  • 12. Test your understanding of loops Output: Puzzle 1: for i in [0,1]: print i print i 0 1 1 Puzzle 2: i = 5 for i in []: print i Puzzle 3: (no output) Reusing loop variable (don’t do this!) for i in [0,1]: print "Outer", i for i in [2,3]: print " Inner", i print "Outer", i inner loop body outer loop body Outer 0 Inner 2 Inner 3 Outer 3 Outer 1 Inner 2 Inner 3 Outer 3
  • 13. The range function A typical for loop does not use an explicit list: The list for i in range(5): [0,1,2,3,4] … body … Upper limit (exclusive) range(5) = [0,1,2,3,4] Lower limit (inclusive) range(1,5) = [1,2,3,4] step (distance between elements) range(1,10,2) = [1,3,5,7,9]
  • 14. Decomposing a list computation • To compute a value for a list: – Compute a partial result for all but the last element – Combine the partial result with the last element Example: sum of a list: [ 3, 1, 4, 1, 5, 9, 2, 6, 5 ] List z List y List c List b List a sum(List a) = sum(List a) + 5 sum(List b) = sum(List c) + 6 … sum(List y) = sum(List z) + 3 sum(empty list) = 0
  • 15. How to process a list: One element at a time • A common pattern when processing a list: result = initial_value # Sum of a list for element in list: result = 0 result = updated result for element in mylist: result = result + element … use result • initial_value is a correct result for an empty list • As each element is processed, result is a correct result for a prefix of the list • When all elements have been processed, result is a correct result for the whole list
  • 16. Examples of list processing • Product of a list: result = 1 for element in mylist: result = result * element result = initial_value for element in list: result = updated result • Maximum of a list: result = mylist[0] for element in mylist: result = max(result, element) The first element of the list (counting from zero) • Approximate the value 3 by 1 + 2/3 + 4/9 + 8/27 + 16/81 + … = (2/3)0 + (2/3)1 + (2/3)2 + (2/3)3 + … + (2/3)10 result = 0 for element in range(11): result = result + (2.0/3.0)**element
  • 17. Making decisions • How do we compute absolute value? abs(5) = 5 abs(0) = 0 abs(-22) = 22
  • 18. Absolute value solution If the value is negative, negate it. Otherwise, use the original value. val = -10 if val < 0: result = - val else: result = val print result val = -10 if val < 0: print - val else: print val
  • 19. The if body can be any statements # height is in km # height is in km if height > 100: if height > 100: 50: Execution gets here only then print "space" if height > 100: print "space" if “height > 100” is false clause else: elifprint "space" height > 50: Execution gets here only if height > 50: else: print "mesosphere" if “height > 100” is false t print "mesosphere" elifprint "mesosphere" height > 20: AND “height > 50” is true else: else: print "stratosphere" else clause if height > 20: else:height > 20: if print "troposphere" print "stratosphere" t print "stratosphere" e else: else: e print "troposphere" print "troposphere" troposphere 0 10 20 stratosphere 30 40 mesosphere 50 60 70 space 80 90 100 km above earth
  • 20. The then clause or the else clause is executed if is_prime(x): y = x / 0 else y = x*x

Notas do Editor

  1. You can tell what this means, but the computer cannot
  2. There are multiple ways to correct it.
  3. Question: why don’t we ever accidentally print “mesosphere” when height is 220? “height &gt; 50” is true in that case.
  4. I hate this example. Come up with a real-world example where one branch always fails but isn’t always executed.