[go: up one dir, main page]

0% found this document useful (0 votes)
2 views17 pages

Week 5

The document covers the concept of iteration in Python, specifically focusing on for loops, which allow for definite repetition through a known number of iterations or a fixed sequence of values. It explains the syntax of for loops, the use of the range function, and provides examples and practice exercises for implementing loops with various data types. Additionally, it introduces the break statement, the random package for generating random values, and demonstrates how to control output formatting with the print function's end parameter.
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)
2 views17 pages

Week 5

The document covers the concept of iteration in Python, specifically focusing on for loops, which allow for definite repetition through a known number of iterations or a fixed sequence of values. It explains the syntax of for loops, the use of the range function, and provides examples and practice exercises for implementing loops with various data types. Additionally, it introduces the break statement, the random package for generating random values, and demonstrates how to control output formatting with the print function's end parameter.
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/ 17

Week 5

Ranges and iteration (for loops).


Iteration/Repetition
Repetition statements allow us to execute statements repeatedly.
Repetition statement are also called loops.
There are two types of repetition in Python: for and while, we will focus on
repetition with for loops.
for loops are used for definite repetition:
• Number of iterations is known - e.g., 500 trials.
• To iterate through a fixed sequence of values - e.g. all characters in a
string, all items in a list, all values in a range.

2
Repetition with for loops
The syntax of a for loop is as follows:

for variable in <sequence>:


#statement(s) to execute
#statement(s) to execute

For loops use indentation to specify which statements will be repeated.
Indented statements are repeated once for each value in the given sequence.
Each time the loop executes the next value in the sequence will be assigned (bound) to
the variable with the given name.
Sequences include: strings, ranges, lists, dictionaries, tuples.
We will discuss each sequence in detail.
3
Sequence: 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. Default value 0.

• stop: generate numbers up to but not including the stopping value.

• step: update/difference between each number in the sequence. Default


value 1.

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

letters = 'abcdef' Output:


a
for i in range(0, len(letters)): b
c
print(letters[i]) d
e
f
9
Let’s Practice!

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

The break statement is used to immediately exit whatever loop it is in.

Break skips remaining statements in code block.

Break exits only the containing loop.

for <var> in <sequence>:


if <condition>:
break
else:
#do something

11
Examples with break statements

mysum = 0 Output:

for i in range(5, 11, 2): sum of values = 5

mysum += i

if mysum == 5:

break

mysum += 1

print('sum of values =',mysum)

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!

Write a Python guessing game program.


• The program should generate secret random integer between 1 and 10.
• The user has 3 guesses to guess correctly.
• The program should output an appropriate message if the user guesses
correctly and wins the game or does not guess correctly and loses the
game.

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.

By default, the end value is a newline character.

For example, the statements:


print( ‘hello’ ) outputs hello\n
print( ‘goodbye’ )
goodbye\n
You can change this to a different string, by setting the end parameter:
print( ‘hello’, end=‘*’ ) outputs
hello*goodbye*
print( ‘goodbye’, end=‘*’ )

print( ‘hello’, end=‘ ’ ) outputs


hello goodbye ,
print( ‘goodbye’, end=‘ ’ ) 16
Printing outputs on same line – end parameter
Script for num in range(3): for num in range(3): for num in range(3):
print(num) print(num, end='/') print(num, end='/’)
print('')
print('-----’) print('-----’) print('-----’)
print('*****’) print('*****’) print('*****’)

Output 0 0/1/2/----- 0/1/2/


1 ***** -----
2 *****
-----
*****

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!

Modify the for_squares.py program to print the squares of 1 to 10 on a single


line, separated by a single space.

Sample run:
1 4 9 16 25 36 49 64 81 100
See: for_squared_print.py

18

You might also like