Python Programming Language
In Python, the for loop is used to run a block of code for a certain number of times.
Flowchart representation _ Python For Loop
Syntax of FOR statement
for variable in range(startvalue, endvalue +1, increment/decrement value):
for loop: To iterate/repeat over a sequence of elements or statements
range() function: The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified number.
startvalue: Initial value
endvalue+1: one more then the final value
increment/decrement value : The number by which the loop variable will increase/decrease.
The value by default is 1
Explain the purpose of a loop in programming. Provide an example where using a loop is beneficial.
A loop in programming serves the purpose of repeating a set of instructions or statements multiple times.
It allows automating repetitive tasks, making code more concise and efficient. One common scenario
where loops are beneficial is when iterating through a collection of data, such as a list or array.
For example, consider the task of printing numbers from 1 to 5. Without a loop, we would need to write
five print statements. However, using a loop, like a FOR loop in Python, the code becomes more compact
and readable:
pythonCopy code
for i in range(1, 6):
print(i)
This loop iterates through the range of numbers from 1 to 5 and prints each number. Thus, loops simplify
code structure and enhance maintainability by reducing redundancy.
Examples
Q1. WAP to print any welcome message 10 times on the screen.
for a in range (1,11):
print(“Welcome everyone!!”)
Q2. WAP to print first 20 natural numbers on screen.
for a in range (1,21):
print(a)
Q3. WAP to print even numbers between 2 to 50.
for a in range (2,52,2):
print(a)
Q4. WAP to accept 50 numbers from the user and print it’s total sum.
sum=0
for a in range(1,51,1):
num=input(“enter a number”)
sum=sum+num
print(“The sum of 50 numbers is”, sum)