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

Day6-Facilitation Guide (Loops)

The document is a facilitation guide for a Day 6 session on loops in programming, covering topics such as flow control, while loops, infinite loops, and break and continue statements. It includes a recap of previous lessons on functions, type conversion, and mathematical functions, along with practical coding examples and exercises. Additionally, it emphasizes the importance of avoiding infinite loops and provides guidelines for using break and continue statements effectively.

Uploaded by

durga prasad
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 views10 pages

Day6-Facilitation Guide (Loops)

The document is a facilitation guide for a Day 6 session on loops in programming, covering topics such as flow control, while loops, infinite loops, and break and continue statements. It includes a recap of previous lessons on functions, type conversion, and mathematical functions, along with practical coding examples and exercises. Additionally, it emphasizes the importance of avoiding infinite loops and provides guidelines for using break and continue statements effectively.

Uploaded by

durga prasad
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/ 10

Day 6- Facilitation Guide

Loops
Index

I. Recap
II. Flow Control
III. While Loop
IV. Infinite Loops
V. Break and Continue Statements

(1.50 hrs) ILT

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

brand=input("Enter Your Favorite Brand:")


if brand=="AB":
print("It is children's brand")
elif brand=="AC":
print("It is not that much kick")
elif brand=="MK":
print("Buy one get Free One")
else :
print("Other Brands are not recommended")

In this session we are going to understand flow control,while loop,break and continue
statements.

II. Flow Control


Flow control describes the order in which statements will be executed at runtime. Flow
control statements are divided into three categories in Python.

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.

III. While loop


A "while" statement is a control flow statement used in many programming languages to
create a loop. It allows you to repeatedly execute a block of code as long as a specified
condition is true. Here's the basic structure of a "while" statement:
Syntax:
while condition:
# Code to be executed while the condition is true

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

Here's a common pattern used to avoid infinite loops:

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:

Predict the output of the following code:

n=2
while n <= 10:
if n%2==0:
print(n)
n = n+1

IV. Infinite Loops


An infinite loop is a loop that runs indefinitely without terminating under normal
circumstances. Infinite loops can be problematic because they can consume all
available CPU resources, causing your program or system to become unresponsive.
They are usually unintentional and considered a bug in your code.

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.

V. Break and Continue statements

The break Statement


Using the break statement within a loop allows you to exit the loop prematurely when a
certain condition is met. While break can be a useful tool, relying on it too heavily can
lead to hard-to-maintain code. Be cautious when using break to exit loops and ensure
that it's used sparingly and appropriately.

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.

Here's a simple example using a break statement in a `while` loop in Python:

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.

The continue Statement


The continue statement is a control flow statement used in many programming
languages to skip the current iteration of a loop and proceed to the next iteration. It is
typically used inside loops, such as for and while loops, to control the flow of
execution within the loop.

Here's how the continue statement works:

● Inside a Loop: The continue statement is placed within a loop.

● Execution Skipping: When the continue statement is encountered, the current


iteration of the loop is immediately terminated, and control flow moves to the next
iteration of the loop (if there are more iterations to be executed).

● 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.

Let's do more looping:


1. Write a program to find greatest common divisor (GCD) or highest common
factor (HCF) of two numbers.

# Input two numbers from the user


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Find the minimum of the two numbers


min_num = min(num1, num2)

# Initialize variables to store the GCD/HCF and the current divisor


gcd = 1
divisor = 1

# Use a while loop to find the GCD/HCF


while divisor <= min_num:
if num1 % divisor == 0 and num2 % divisor == 0:
gcd = divisor
divisor += 1

# Display the GCD/HCF


print(f"The GCD/HCF of {num1} and {num2} is {gcd}")

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:

3. Find the multiples of a number using while loop

n = int(input("Enter an integer: "))

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.

You might also like