CSE 160 Section 2
Loops and Range!
TA1 & TA2
CSE 160
CSE 160: Section 2
Logistics
CSE 160: Section 2
Homework: Practical Tips
CSE 160: Section 2
DiffChecker Example
Problem 1 solution follows:
Root 1: ____
Root 2: ____
Problem 1 solution follows:
Root 1 : ____
Root 2 : ____
CSE 160: Section 2
DiffChecker Example
Problem 1 solution follows:
Root 1: ____
Root 2: ____
Problem 1 solution follows:
Root 1 : ____
Root 2 : ____
CSE 160: Section 2
Lecture Review: Range
CSE 160: Section 2
Range
Example: range(0, 6, 2) loops through 0 → 2 → 4
Equivalent to: range(0, 5, 2)
CSE 160: Section 2
Lecture Review: Loops
CSE 160: Section 2
Loops
for i in range(1, 4):
print(i)
CSE 160: Section 2
Loops
or number of times loop is repeated
CSE 160: Section 2
Nested Loops Overview
CSE 160: Section 2
Nested Loops
Example:
for i in range(0, 3):
for j in range(0, 2):
print(i)
CSE 160: Section 2
Nested Loops
for i in range(0, 3):
for j in range(0, 2):
print(i)
CSE 160: Section 2
Nested Loops
Example:
for i in range(0, 3):
for j in range(0, 2):
print(i)
CSE 160: Section 2
Boolean Zen
num = 0
if num == 2:
is_two = True
else:
is_two = False
num = 0
is_two = num == 2
Without boolean zen:
With boolean zen:
CSE 160: Section 2
Section Handout Problems
CSE 160: Section 2
Ranges and Loops
2. Write a for loop that will print the result of multiplying 3 by the numbers 8 through 12.
The example solution is two lines long. Your output should read:
24
27
30
33
36
CSE 160: Section 2
Ranges and Loops
2. Possible solutions appear below:
for value in range(8, 13):
print(3 * value)
for value in range(24, 37, 3):
print(value)
*You’ll learn about lists soon!
for value in [8, 9, 10, 11, 12]:
print(3 * value)
CSE 160: Section 2
Nested Loops
3. What is the output printed by the following program?
sum = 0
for i in range(1, 4):
for j in range(1, 4):
sum = sum + i
print(sum)
Answer: Python Tutor
CSE 160: Section 2
Ranges and Loops
4. What is the output printed by the following program?
for value in range(1, 6, 2):
print(value + value ** 2)
CSE 160: Section 2
Ranges and Loops
4. What is the output printed by the following program?
for value in range(1, 6, 2):
print(value + value ** 2)
Output:
2
12
30
CSE 160: Section 2
Additional Practice Problems
CSE 160: Section 2
Nested Loops
5. What is the output printed by the following program?
for i in range(1, 4):
for j in range(1, 4):
print(i + j)
Answer: Python Tutor
CSE 160: Section 2
Ranges and Loops
6. What is the output printed by the following program?
for value in range(1, 4):
print(value + value ** 2)
CSE 160: Section 2
Section Code:
CSE 160: Section 2
Looking ahead: Functions, Lists, and Nested Lists
Be sure to remember the Section Code!
CSE 160: Section 2