PYTHON
Lesson controls with
8 loop
statement
loop statement
In Python, a loop statement is a control flow
structure that allows you to execute a block of
code repeatedly based on certain conditions.
main types of loop statement
for loop
The for loop in Python is used to iterate over a
sequence (such as lists, tuples, strings, or ranges)
or any iterable object.
It iterates over each item in the sequence or
iterable and executes the block of code for each
item.
for loop
Let’s code a for loop statement
To create a for loop statement, you need to use
this syntax
Here is an example
The button control serves as the output to show
the for loop statement
for loop
•Here is an example of the code
for loop
When this code is executed, it produce this result
while loop
The while loop in Python is used to repeatedly
execute a block of code as long as a specified
condition is true.
It continues iterating as long as the condition
remains true.
while loop
Let’s code a while loop statement
•To create a while loop statement, you need to use
this syntax
while loop
•Here is an example
We initialize ito 0 before the loop starts.
After each iteration, we increment the value of i by 1 (i += 1). This
step is crucial to avoid an infinite loop and to ensure that the loop
eventually terminates.
With i += 1, the loop variable i will be incremented by 1 in each
iteration, ensuring that the loop runs exactly 5 times. Each iteration
of the loop will create and pack a button into the root window.
while loop
•Here is an example of the code
while loop
When this code is executed, it produce this result
do/while loop
Python doesn't have a built-in do/while loop like
some other programming languages.
However, you can simulate its behavior using a
while loop with a condition that's always true
initially.
It executes the code block at least once before
checking the loop condition for subsequent
iterations.
do/while loop
The most common technique to emulate a do-while
loop in Python is to use an infinite while loop with
a break statement wrapped in an if statement that
checks a given condition and breaks the iteration
if that condition becomes true
do/while loop
•Here is an example
We use a while True loop, which will continue indefinitely until
explicitly stopped.
Inside the loop, we create and pack a button into the root window.
We increment the loop variable i by 1 in each iteration.
We check if i is greater than or equal to 7. If it is, we break out of
the loop using the break statement, thus terminating the loop. This
effectively simulates the behavior of a do/while loop, as the loop
body is executed at least once before the condition is checked.
do/while loop
•Here is an example of the code
do/while loop
When this code is executed, it produce this result