Day6-Facilitation Guide (Loops)
Day6-Facilitation Guide (Loops)
Loops
Index
I. Recap
II. Flow Control
III. While Loop
IV. Infinite Loops
V. Break and Continue Statements
I. Recap
In our last session we learned:
● Functions:Functions are blocks of reusable code that perform specific tasks or
operations. They are a fundamental concept in programming and play a crucial
role in organizing and modularizing code.
● Built-in Functions:Built-in functions that are readily available for use without
needing to import any external modules. These functions are part of the Python
standard library and cover a wide range of tasks.
● Type Conversion Functions: Type conversion (also known as type casting)
using various built-in functions to change the data type of a value or variable.
● Mathematical Functions:Python provides a wide range of mathematical
functions through the built-in math module.Which help us to perform different
mathematical operations.
● User defined functions:User-defined functions in Python allow you to create
your own functions to perform specific tasks or operations. You can define a
function using the def keyword, specify a name for the function, provide
parameters (if needed), and define the code that the function will execute.
Try this:
Please check the code and predict the output if we enter brand MK
In this session we are going to understand flow control,while loop,break and continue
statements.
Note:
● There is no switch statement in Python. (Which is available in C and Java)
● There is no do-while loop in Python.(Which is available in C and Java)
● goto statement is also not available in Python. (Which is available in C)
In our last session we already understood about conditional statements.In this session
we are going to discuss transfer statements and iterative statements.
In this figure:
condition is an expression or a boolean (true/false) value.
The loop will continue executing as long as this condition evaluates to True.
The code inside the while block is executed repeatedly as long as the condition remains
true.
Here's a simple example in Python that uses a "while" loop to count from 1 to 5:
count = 1
while count <= 5:
print(count)
count += 1 # Increment count by 1 in each iteration
In this example, the while loop continues to execute as long as count is less than or
equal to 5. It prints the value of count in each iteration and increments count by 1 until
the condition becomes false, at which point the loop terminates.
It's important to be cautious when using "while" loops to avoid creating infinite loops
(loops that never terminate). To prevent this, you should ensure that the condition
eventually becomes false. Typically, you update a variable inside the loop so that the
condition changes over time, eventually leading to the loop's termination.
Try this:
Please check the code and predict the output.
i=1
while True:
print('Hello', i)
i=i+1
while condition:
# Code
if some_condition:
break # Exit the loop prematurely if necessary
The break statement is used to exit the loop if a specific condition is met, providing an
escape mechanism to prevent the loop from running indefinitely.
Try this:
n=2
while n <= 10:
if n%2==0:
print(n)
n = n+1
Here are a few common reasons for unintentional infinite loops and how to avoid them:
● Incorrect Loop Conditions: Infinite loops often happen due to incorrect loop
conditions that never evaluate to False. For example:
while True:
# Code that never modifies the loop condition
To avoid this, make sure your loop conditions have an exit condition that will
eventually be met.
● Missing Increment (or Decrement): If you forget to update a variable inside the
loop, the loop may never exit. For example:
count = 0
while count < 5:
# Code
In this case, count remains 0, and the loop never exits because it doesn't
increment.
To fix this, ensure that the loop variable is updated inside the loop, so the
condition can eventually become false.
● Logic Errors: Sometimes, your loop's logic may contain errors that prevent the
loop from reaching an exit condition. Carefully review your loop's logic to identify
any issues.
Here's an example of an infinite loop with a break statement to demonstrate how it can
be used to prevent an infinite loop:
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break # Exit the loop when 'q' is entered
else:
print("You entered:", user_input)
In this example, the loop keeps running until the user enters 'q,' at which point the break
statement is executed to exit the loop.
To avoid infinite loops, always ensure that your loop conditions have a way to become
False or that you have a clear exit strategy using statements like break. Testing your
code thoroughly and reviewing your logic is essential to catch and prevent infinite loop
bugs.
The `break` statement:The `break` statement is a control flow statement used in many
programming languages to exit a loop prematurely, even if the loop's condition has not
been met. It is typically used to terminate a loop when a specific condition is satisfied.
Here's how the `break` statement works:
● Inside a Loop: The `break` statement is placed within a loop, such as a `for` or
`while` loop.
● Condition Check: At some point in the loop's execution, a condition is checked.
If this condition evaluates to `True`, the `break` statement is executed.
● Exiting the Loop: When the `break` statement is encountered, the loop is
immediately terminated, and control flow moves to the first statement after the
loop.
The primary purpose of the `break` statement is to provide a way to exit a loop early
when a specific condition is met, without having to complete all iterations of the loop.
This is particularly useful when you want to stop a loop as soon as you've achieved the
desired outcome.
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
break # Exit the loop when 'q' is entered
else:
print("You entered:", user_input)
In this example, the `while` loop runs indefinitely until the user enters 'q.' When 'q' is
entered, the `break` statement is executed, causing the loop to terminate, and the
program continues with the next statement after the loop.
The `break` statement can also be used in `for` loops, `switch` statements (in some
languages), and other control flow structures to achieve similar functionality. It's a
powerful tool for controlling the flow of your program and is commonly used for
implementing exit conditions in loops.
● Loop Continues: The loop's condition (or the loop control variable) is
re-evaluated, and the loop proceeds with the next iteration, skipping the code
that follows the continue statement for the current iteration.
The primary purpose of the continue statement is to skip over certain iterations of a
loop when a specific condition is met, without terminating the entire loop. This allows
you to control which iterations should execute certain code and which ones should be
skipped.
Here's a simple example using the continue statement in a while loop to print all
even numbers between 1 and 10 while skipping odd numbers:
i=1
while(i<=10):
if i % 2 != 0:
i=i+1
continue # Skip odd numbers
print(i)
i=i+1
In this example, the continue statement is used to skip odd numbers. When i is an odd
number, the continue statement is executed, and the loop proceeds to the next value of
i without printing anything. When i is an even number, the print(i) statement is
executed.
The continue statement is a useful tool for controlling the flow of your loop and can be
handy when you want to apply certain conditions to determine whether to execute
specific code within the loop or to skip certain iterations based on certain criteria.
Output:
2. Find the average of 5 numbers using while loop
p=5
sum = 0
count = 0
while p > 0:
count += 1
f = int(input("Enter the number "))
sum += f
p -= 1
average = sum/count
print("Average of given Numbers:",average)
Output:
i=1
while i <= 10:
mul = i*n
i += 1
print(mul)
Output:
Exercise chatGPT
Use GPT to write a program:
1.Hi! Can you take 10 integers from the keyboard using a while loop and print their
average value on the screen without exception.
After the ILT, the student has to do a 30 min live lab. Please refer to the Day 6 Lab
doc in the LMS.