Week 3
Week 3
CS115
Introduction to Programming in Python
Week 3
2
THIS WEEK
▶ iteration
● while loops
● for loops
▶ string manipulation with for loops
▶ simple numerical programs
● guess and check algorithms
● approximate solutions
● bisection method
3
CONTROL FLOW: Iteration / Repetition
4
CONTROL FLOW: while LOOPS
5
Flow chart for iteration
7
CONTROL FLOW: for LOOPS
10
range(start, stop, step)
▶ The range function generates a list of numbers, generally used to
iterate with for loops
▶ The function has 3 parameters:
▶ start: starting number of the sequence
▶ stop: generate numbers up to but not including the stopping
value
▶ step: update/difference between each number in the
sequence.
▶ default values are start = 0 and step = 1 and optional
▶ loop until value is stop - 1
11
Examples: range function
mysum = 0
Output:
for i in range(5, 11, 2): 21
mysum += i
print(mysum)
mysum = 0
Output:
for i in range(7, 10):
24
mysum += i
print(mysum)
12
Examples: range function
x = 4 Output:
0
for i in range(x):
1
print(i) 2
3
x = 4 Output:
for i in range(0,x): 0
1
print(i) 2
3
13
14
15
For Loop Examples
▶ Write a Python program to input the status (F - Full-time, P-Part-time) and
the salary of 10 instructors and output:
● the number of full-time instructors.
● the average salary of all instructors.
▶ See: salary.py
▶ Write a Python program to input 12 temperature values (one for each month)
and display the number of the month with the highest temperature.
▶ See: temperatures.py
16
17
Choosing the Correct Type of Loop
▶ Choosing the right loop type makes your code more legible and can
also help prevent bugs
▶ Everything that can be written with a for loop can be written with a
while loop, but while loops can solve some problems that for loops
don't address easily
▶ In general, use for loops when you know the number of iterations you
need to do - e.g., 500 trials, one operation per character in a string,
or an action on every element in a list
▶ If you can describe the problem you're trying to solve in terms of each
or every element in an iterable object, use a for loop
▶ Using a for loop when possible will decrease the risk of writing an
infinite loop and will generally prevent you from running into errors
with incrementing counter variables
18
Nested Loops
▶ Nested Loop means a loop within another loop
▶ For each iteration of the outer loop is executed, the inner loop is
executed completely
for i in range(1, 6, 2):
Output:
i = 1 j = 6
i = 1 j = 3
i = 3 j = 6
i = 3 j = 3
i = 5 j = 6
i = 5 j = 3 19
A program that prints a triangle of stars
MAX_ROWS = 10
for row in range(1, MAX_ROWS + 1, 1):
for star in range(1, row+1, 1):
print(‘*’, end=' ')
print()
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
20
Nested for Loop
▶ See multiplicationTable.py
21
Nested for Loop - Stars
▶ Write a program to display the triangle of stars below.
▶ See: stars2.py
22
23
Examples: for loops and Strings
Output:
a
for c in 'abcdef': b
print(c) c
d
e
f
Output:
a
letters = 'abcdef'
b
for c in range(0, len(letters)): c
print(letters[c]) d
e
f
Examples: for loops and Strings
s = "abcdefgh"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u':
print("There is an ior u")
for char in s:
if char == 'i' or char == 'u':
print("There is an i or u")
Code Example – Strings and Loops
an_letters= "aefhilmnorsxAEFHILMNORSX" an_letters= "aefhilmnorsxAEFHILMNORSX"
word = input("I will cheer! Enter word: ") word = input("I will cheer! Enter word: ")
times = int(input("Energy level (1-10): ")) times = int(input("Energy level (1-10): "))
i = 0 for char in word:
while i < len(word): if char in an_letters:
char = word[i] print("Give me an " + char + "! " + char)
if char in an_letters: else:
print("Give me an " + char + "! " + char) print("Give me a " + char + "! " + char)
else:
print("Give me a " + char + "! " + char) print("What does that spell?")
i += 1 for i in range(times):
print(word, "!!!")
print("What does that spell?")
for i in range(times):
print(word, "!!!")
26
27
Exercise - What is Output?
s1 = "Bilkent u rock"
s2 = "i rule Bilkent"
if len(s1) == len(s2):
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("common letter")
break
28
What Happens when Code Executes?
▶ Python Tutor is a useful tool that can help you visualize
what happens during the program execution – the values
of variables and how they change while the program runs.
▶ It allows you to copy/paste your own code into an online
editor and trace the step by step execution of your
program.
▶ To visualize the code from the previous slide:
https://goo.gl/iZGsP4
29
Some Simple Numerical Programs
30
31
32
33
34
35
36
37
38
39
Terms of Use
➢ This presentation was adapted from lecture materials provided in MIT
Introduction to Computer Science and Programming in Python.
➢ Licenced under terms of Creative Commons License.
40