0% found this document useful (0 votes)
42 views

Week 3

This document discusses iteration and simple numerical programs in Python. It covers while and for loops, including examples of each. While loops repeat until a condition is no longer true. For loops iterate over a sequence, such as a range of numbers or characters in a string. Nested loops are discussed, where one loop is contained within another. Examples are provided of using loops to solve problems involving guessing games, calculating averages, and manipulating strings and numbers.

Uploaded by

Neural Proje
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)
42 views

Week 3

This document discusses iteration and simple numerical programs in Python. It covers while and for loops, including examples of each. While loops repeat until a condition is no longer true. For loops iterate over a sequence, such as a range of numbers or characters in a string. Nested loops are discussed, where one loop is contained within another. Examples are provided of using loops to solve problems involving guessing games, calculating averages, and manipulating strings and numbers.

Uploaded by

Neural Proje
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/ 40

ITERATION,

SIMPLE NUMERICAL PROGRAMS

CS115
Introduction to Programming in Python

Week 3

Slides are mostly adapted from MIT Open Courseware


1
LAST WEEK

▶ string object type


▶ string manipulations
▶ branching and conditionals
▶ indentation

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

▶ Repetition statements allow us to execute a


statement multiple times
▶ Often they are referred to as loops
▶ Python has two kinds of repetition statements:
▶ while loops
▶ for loops

4
CONTROL FLOW: while LOOPS

▶ <condition> evaluates to a Boolean

▶ if <condition> is True, do all the steps inside the while code


block

▶ check <condition> again

▶ repeat until <condition> is False

5
Flow chart for iteration

▶ Test is a boolean expression


▶ As long as Test is True, Loop Body is executed
▶ If Test is False, execution resumes at the code following
the statement
6
While Loop Examples
▶ Write a Python script that does the following. Assume you deposit 10000TL into a
bank account, output the number of years it takes to double the original
investment, assuming a yearly interest rate of 15%.
▶ See: investment.py
▶ In a biology experiment a microorganism population doubles every 10 hours. Write a
Python program to input the initial number of microorganisms and output how long
(days and remaining hours) it will take to have more than 1000000 organisms.
▶ See: biology.py
▶ Write a Python script that inputs positive integers until a negative value is input.
The program should output the average of the values input.
▶ See: average.py
▶ Write a Python guessing game program. The program should generate a random int
between 1 and 10. The user has 3 guesses to guess correctly. The program should
output an appropriate message if the user guesses correctly/does not guess
correctly.
▶ See: while_game.py

7
CONTROL FLOW: for LOOPS

▶ range function generates a sequence of integers


▶ Each time through the loop, <variable> takes a value from
that sequence
▶ The first iteration, <variable> starts at the first value in the
sequence
▶ The next iteration, <variable> gets the next value in the
sequence
▶ Example (print “hello” 100 times): 8
9
for loop Example
▶ Example (print “hello” 100 times):
for i in range(100):
print(‘hello’)

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

▶ Write a Python guessing game program. The program should generate a


random int between 1 and 10. The user has 3 guesses to guess correctly. The
program should output an appropriate message if the user guesses
correctly/does not guess correctly.
▶ See: game.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):

for j in range(6, 0, -3):

print("i = " + str(i) + "\tj = " + str(j))

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

▶ The following code segments do the same thing


▶ The second one is more “pythonic”

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

You might also like