Beginning Programming in Python
Fall 2019
Agenda
- More Control Flow
- For Loops and List Iteration
- Nested Loops
- Break Statement
- Continue Statement
- Some Examples of Control Flow
For loops
0
Advanced issues found▲
-
The for loop is "syntactic sugar", that is it combines the concept of looping (like the while loop) with the idea of iterating, either using a counter or elements in a sequence, such as a Python list.
-
You can always create equivalent code using a while loop and additional variables, but 'for' is often more convenient.
# While loop version
i = 0
while(i < 10):
print("i is: " + str(i))
i = i + 1
# The for loop version
for i in range(10):
# Range returns an iteratable sequence
# from 0 (inclusive) to 10 (exclusive)
print("i is: " + str(i))
Examples of for loops
# Range can do all sorts of fancy iterations
for i in range(9, -1, -1): # Backwards
print("i is: " + str(i))
# Jumping two steps at a time
for i in range(0, 10, 2):
print("i is: " + str(i))
# For loops also allow iteration over sequences, such as lists:
# Note: we'll cover lists in detail later
for color in [ "pink", "yellow", "blue", "green" ]:
print("My favorite color is now " + color)
An aside example of list
nesting loops
0
Advanced issues found▲
-
We saw nested conditionals, we can also nest loops.
-
While loops, for loops and other control flow elements can all be nested together.
# Example of nested for loops
for i in range(4):
for j in range(4):
print("The values are, i: " + str(i) + " j: " + str(j))
# This may mess with you, but it is just the logical extension
# of the ideas we've covered.
Break & Continue
-
Break:
- Jumps out of a block
-
Continue:
- Jumps to the beginning of the block
i = 1
while True:
print(i)
i = i + 1
if i > 10:
break
i = 0
while True:
print(i)
i = i + 1
if i < 5:
continue
if i >= 10:
break
Example 1: break
Example 2: Continue
5 minutes break!
Counting digits
Example
Collatz 3n+1 sequence
Example
SQRT function approximation
Example
x_{n+1} = \frac{1}{2}(x_n + \frac{a}{x_n})
x = \sqrt{a} \ a > 0
x \approx x_n
x = 3 \\
x = \frac{(3 + \frac{49}{3})}{2} \approx 9.67 \\
x = \frac{(9.67 + \frac{49}{9.67})}{2} \approx 7.36 \\
x = \frac{(7.36 + \frac{49}{7.36})}{2} = 7.008 \\
...
putting it all together
Zybooks chapters covered
- Chapter 5 - sections 5.4 through 5.10
Lecture 4 challenge
Questions?
CSE 20 - Lecture 4
By Narges Norouzi
CSE 20 - Lecture 4
- 1,687