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

[CreativeProgramming]Lecture6_Iteration in Python

The document provides an overview of iteration in Python, focusing on loops such as 'while' and 'for', along with the 'range()' function. It explains the syntax and usage of these loops, including examples and comparisons between definite and indefinite iterations. Additionally, it outlines exercises for practical application, including summing even numbers, countdowns, and FizzBuzzWoof implementation.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

[CreativeProgramming]Lecture6_Iteration in Python

The document provides an overview of iteration in Python, focusing on loops such as 'while' and 'for', along with the 'range()' function. It explains the syntax and usage of these loops, including examples and comparisons between definite and indefinite iterations. Additionally, it outlines exercises for practical application, including summing even numbers, countdowns, and FizzBuzzWoof implementation.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Creative Programming

Spring 2025
CUL1122 Lecture #06
Iteration in Python
Today

• Python Loops
• Syntax for Using the while Loop
❖range() and for Loop
▪ Syntax of the range() Function
▪ Steps to Use range() Function
▪ range() Examples
▪ for Loop with range() Function
❖for loop vs. while loop

3
Three Control Flows in a Computer Program: Iteration

1. Sequencing 2. Selection 3. Iteration


In-order Execution Conditional Execution Repeated Execution

Code 1 Code
If expression If expression
is True Expression is False If expression
is True
Expression
Code 2
Code 1 Code 2

If expression
Code 3 is False

4
The while Loop in Python

❖A while loop begins with ‘while,’ includes a condition, and ends with a
colon.
❖During each iteration:
▪ 1) The loop condition is checked.
▪ 2) If the condition is True, the code block inside the loop is executed.
▪ 3) Otherwise, the script leaves the The while Loop False
loop and proceeds to the next line while Condition: 1) Cond
of code. Code Block True
2) Code Block

3) …
5
while Loop Explained with an Example

❖Printing ‘Thank you!’ 1,000 times.

Initialization
count = 0
Condition
while count < 1000:
Loop Body print(‘Thank you!’)
(Code Block) Increment
count = count + 1

6
Terminating the Loop Immediately

❖The Python break statement immediately terminates a loop entirely.


❖In the example below, you can exit the loop when i becomes 1,000.
i=0
Iteration
while True: # This loop runs infinitely True
Always True
print(i)
print i
i=i+1 # Increment i by 1
if i == 1000: # Exit the loop when i reaches 1,000 i=i+1
break # Terminate the loop
False
i == 1000
True
break
7
Syntax of the range() Function

❖The built-in function range() generates a sequence of numbers within a


specified range.
❖The syntax for the range() function is as follows:
range(start, stop[, step])

▪ This function requires a stop value, while the start and step values are optional.
❖Parameters
Name Description Default Value
start Specifying the initial value of the sequence. 0
stop Denoting the end value of the sequence (exclusive). N/A
step Defining the increment between consecutive numbers in the sequence. 1
8
range() Function Method #1: range(stop)

❖The most basic way to use the range() function is by specifying only the
end value, denoted as range(stop).
❖When using this form, the range() function automatically starts from 0,
increments by 1, and ends at stop - 1.
❖For example, to print the first 6 numbers starting from 0, you would use
the following code:
range(6)
for i in range(6): 0 0 1 2 3 4 5 6
print(i) sequence
start stop
▪ In this case, the default values are start = 0 and step = 1.

9
range() Function Method #2: range(start, stop)

❖You can also use the range() function by specifying both the start and
stop values, denoted as range(start, stop).
▪ This method is useful when you want the sequence to start from a value other
than 0.
❖When you provide two arguments to range(), it produces integers
starting from the start value up to, but not including, the stop value.
❖For example, to print numbers from 10 to 15, you would use the
following code:
range(10, 16)
for i in range(10, 16): 10 10 11 12 13 14 15 16
print(i) sequence
start stop
10
range() Function Method #3: range(start, stop, step)

❖You can use the range() function with start, stop, and step parameters
to specify increments.
❖When all three arguments are provided, the function creates a
sequence starting from the start value, incrementing by the step value,
and stopping before reaching the stop value.
❖For example, to print multiples of 5 from 10 to 35, you can use the
following code with a step value of 5:
range(10, 40, 5)
for i in range(10, 40, 5): 10 10 15 20 25 30 35 40
print(i) sequence
start stop

11
Syntax for a for Loop

❖In Python, a for loop executes a block of code or statements repeatedly


for a fixed number of times.
❖A for loop typically follows this structure:
for item in iterable:
code block # Code block to be executed for each item in the iterable
# You can access the current item using the variable ‘item’

❖Here’s a breakdown of the components:


Name Description
for This keyword signals the start of the loop.
item This is a variable that represents the current item in the iteration. You can
choose any valid variable name here.
12
Syntax for a for Loop

❖Here’s a breakdown of the components:


Name Description
in This keyword is used to specify the iterable object over which the loop will
iterate.
iterable This is the collection of items that the loop will iterate over. It can be a list,
tuple, dictionary, string, or any other iterable object in Python.
: The colon denotes the end of the loop header and the start of the indented
code block.
Code This block of code executes for each item in the iterable, indicated by
block consistent indentation. You can access the current item using the loop
variable (e.g., item) and perform operations accordingly.

13
Using the for Loop with the range() Function

❖You can use a for loop to iterate over a sequence of numbers generated
by the range() function.
❖The loop variable acts as an iterator that sequentially takes on each
value generated by the range() function as the loop progresses.
❖Let’s explore how to utilize a for loop with the range() function to
display the odd numbers from 1 to 12:
▪ 1) Iteration through the sequence: The range() function generates a number
sequence starting from the initial value up to, but not including, the stop value.
range(1, 12, 2)
for counter in range(1, 12, 2): 1 1 3 5 7 9 11 12
print(counter)
start sequence stop
14
Using the for Loop with the range() Function
▪ 2) counter represents each element: In each iteration of the loop, counter takes
on the value of each element in the sequence generated by range().
➢For example, in the previous example, during the first iteration, counter will be 1; during
the second iteration, counter will be 3; and so on, until it reaches 11 on the sixth
iteration.
▪ 3) Accessing elements in the sequence: Within the loop block, you can use the
variable counter to access elements in the generated sequence or perform
operations based on those elements.

15
Looping Through a String with a for Loop

❖In Python, when you use a for loop with a string, it iterates over each
character in the string, one at a time.
❖You can process each character individually or perform operations on
each character.
❖For instance, the variable char represents each character in the string,
and you can print each character using the print() function.
my_string = ‘Hello, world!’
# Iterate over each character in the string using a for loop
for char in my_string:
print(char)
16
Looping Through a List with a for Loop

❖In Python, when you use a for loop with a list, it iterates over each
element in the list, one at a time.
❖This method is useful for performing operations on each element of the
list or processing the elements individually.
❖Inside the loop, the variable item represents each element in the list.
You can print each element using the print() function.
my_list = [1, 3, 5, 7, 9]
# Iterate over each element in the list using a for loop
for item in my_list:
print(item)
17
for Loop vs. while Loop

❖In programming, there are two types of iteration: definite and indefinite.
❖Definite iteration involves specifying the number of times a designated
block of code will be executed when the loop starts.
❖Using a for loop for a specific number of iterations:
attempts = 0
for i in range(5): # Allow five attempts
password = input(‘Enter your password: ‘)
if password == ‘password123’:
print(‘Access granted!’)
break
else:
print(‘Incorrect password. Try again!’)
attempts = attempts + 1
18
for Loop vs. while Loop

❖Using a while loop for a specific number of iterations:


max_attempts = 5
attempts = 0
while attempts < max_ attempts: # Allow five attempts
password = input(‘Enter your password: ‘)
if password == ‘password123’:
print(‘Access granted!’)
break
else:
print(‘Incorrect password. Try again!’)
attempts = attempts + 1

19
for Loop vs. while Loop

❖On the other hand, indefinite iteration doesn’t specify the number of
loop executions in advance.
❖Instead, the designated block is executed repeatedly as long as a
condition is met.
❖The while loop is primarily used for indefinite iteration.
print(‘Using a while loop to allow for unlimited attempts:’)
while True: # Allow infinite attempts
password = input(‘Enter your password: ‘)
if password == ‘password123’:
print(‘Access granted!’)
break
20
Lab 6
Today

❖1) Summing Even Numbers


❖2) Countdown
❖3) Displaying a Movie Snack Menu
❖4) Password Check
❖5) Number Guessing
❖6) FizzBuzzWoof Implementation (Assignment #1)
❖7) Identifying Primes in a Range

22
Exercise #1: Summing Even Numbers

❖ Create a script that calculates the sum of even numbers between 1 and
20 using both for and while loops.

23
Exercise #2: Countdown

❖Create a script that counts down using both a for loop and a while loop.
▪ Each countdown should start from 10 and end with “Blast off!” after reaching 1.

24
Exercise #3: Displaying a Movie Snack Menu

❖Create a script that displays a list of movie snacks.


▪ Iterate over a range using the range() function as well as the enumerate()
function.

25
Exercise #4: Password Check

❖Create a script that uses a for loop to prompt for passwords.


▪ Limit the number of attempts to a maximum of 3.
▪ If the maximum number of attempts is reached without entering the correct
password, display an “Access denied” message.

26
Exercise #5: Number Guessing

❖Create a script that plays a number guessing game.


▪ The correct number is between 1 and 100, and the player is allowed at most 7
attempts.

27
Exercise #6: FizzBuzzWoof Implementation

❖Create a FizzBuzzWoof script that iterates over integers from 1 to 110


and follows these rules:
▪ Print “Fizz”, “Buzz”, or “Woof” for numbers divisible by 3, 5, or 7, respectively.
▪ If a number is divisible by more than one of these, combine the corresponding
words (e.g., 15 → “FizzBuzz”, 21 → “FizzWoof”, 35 → “BuzzWoof”, 105 →
“FizzBuzzWoof”).
▪ If none of the conditions apply, print the number itself.
… 9 10 11 12 13 14 15 16 …
Fizz Buzz 11 Fizz 13 Woof FizzBuzz 16

28
Exercise #7: Identifying Primes in a Range

❖Create a script that finds prime numbers within a user-defined range.


▪ After printing the prime numbers within the range, also print the total count of
prime numbers found.

29
수고하셨습니다!

30

You might also like