Module 8 Loops
Module 8 Loops
Condition:
Give chocolate to friend,
if available in Plate
Types
while
for
while loop
The while loop executes a block of code as long as a
specified condition is true. It continuously checks the
condition before each iteration and stops when the
condition becomes false.
Syntax:
while condition:
# Code block to be executed repeatedly
while loop
for loop
A for loop is a way to repeat a block of code for each item in a
collection (like a list) or for a specific range of numbers.
Syntax:
for variable in range(start, stop, step):
# Code block to be executed for each variable
for loop
for loop for Sequence
The for loop is used to iterate over a sequence (such as a
list, tuple, string, or dictionary) and execute a block of
code for each item in the sequence.
Syntax:
for item in sequence:
# Code block to be executed for each item
Example:
Nested loops
Nested loops refer to the situation where one
loop is placed inside another loop. This allows
you to execute a set of instructions repeatedly
Syntax:
for outer_var in outer_sequence:
# Code block of the outer loop
for inner_var in inner_sequence:
# Code block of the inner loop
Nested loops
Break
If during the execution of the loop Python
interpreter encounters break, it immediately
stops the loop execution and exits out of it.
Syntax:
while condition:
# Code block inside the loop
if some_condition:
break # Exit the loop if the condition is met
Break
Continue
Continue statement is used to skip the rest
of the current iteration in a loop and move
to the next iteration immediately.
Syntax:
while condition: # Code block inside the loop
if some_condition:
continue #skip this iteration
Continue
Problems On
Loops +
Strings +
Numbers +
Decision Making
Print numbers from 1 to N
Take a positive integer N as input and print all the numbers from
1 to N.
Sample Input: N=5
Sample Output: 1
2
3
4
5
Calculate the sum of N natural numbers
Take a positive integer N as input and calculate the sum of the
first N natural numbers.
Sample Input: N=5
Sample Output: 2
4
6
8
10
Print odd numbers from 1 t num
Take a positive integer N as input and print all the odd numbers
from 1 to N.
Sample Input: N = 10
Sample Output: 1
3
5
7
9
Multiplication table of a number
Take a positive integer N as input and print the multiplication
table of N from 1 to 10.
Sample Input: Sample Output:
N=3 Multiplication table of 3:
3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Calculate the factorial of a number
Take a positive integer N as input and calculate its factorial (N!).