Week 5
Week 5
2
Repetition with for loops
The syntax of a for loop is as follows:
4
Examples of for loops with ranges
x = 4 Output:
0
for i in range(x):
1
print(i) 2
3
x = 4 Output:
0
for i in range(0,x):
1
print(i) 2
3
5
Examples of for loops with ranges
Practice: write a program to display the squares of all numbers from 1 to 10.
Output:
for i in range(1,11):
print(i ** 2)
See: for_squares.py
6
Examples of for loops with ranges
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)
7
Let’s Practice!
1. Write a Python program to input the favorite ice cream (C - Chocolate, V - Vanilla)
and the age of 5 customers and output:
● the number of customers preferring chocolate flavor.
● the average age of all customers.
See: example_iceCream.py
2. 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: example_temperatures.py
8
Examples of for loops with strings
Output:
a
for ch in 'abcdef': b
c
print(ch)
d
e
f
1. Write a Python program to input a sentence from the user, and count and
display the number of vowels in the sentence.
See: example_sentence01.py
2. Modify the program above to use a range to represent the indexes, instead of
iterating through the string.
See: example_sentence02.py
10
break STATEMENT
11
Examples with break statements
mysum = 0 Output:
mysum += i
if mysum == 5:
break
mysum += 1
13
Random Package
A Python package is a collection of functions that allow you to perform actions without writing
your own code.
Python includes functionality for generating random values in the random package.
To access the functions in the package, you must import the containing package.
Syntax:
import random
num = random.randint(1,10)
The function randint generates a random value between the two values, inclusive.
The function random() generates a random floating point value between 0 and 1 (exclusive).
14
Let’s Practice!
See: example_game.py
15
Printing outputs on same line
The print() function has a parameter called the end parameter whose value
determines what will be placed at the end of the printed statement.
Samples Output
for num in range(1, 25, 5): 1 6 11 16 21
print(num, end=" ")
for num in range(10, 1, -1): 10|9|8|7|6|5|4|3|2|
print(num, end="|")
for num in range(15, 3, -3): 15 | 12 | 9 | 6 |
print(num, end=" | ") 17
Let’s Practice!
Sample run:
1 4 9 16 25 36 49 64 81 100
See: for_squared_print.py
18