Python Loops

Python Loops, Python Control flow statements in Python, Python for loop, Python while loop, and Python nested loop structures.

Python Language Loops

In general, statements are executed sequentially in Computer programming,

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides two loop structures,

1. while loop
2. for loop to handle loop requirements…

1. while loop

It repeatedly executes statements while condition is true…

Syntax:

while (condition/expression):
statement(s);

Example 1 – Print 1 to 10 Numbers.

a=1;
while (a<=10):
print(a);
a=a+1;
Output:
1
2
3
4
5
6
7
8
9
10

Example 2: Read a Number, and calculate sum, and Zero to quit from the loop

a=1;
sum=0;

print (“Enter a Number to add to the sum: “);
print (“Enter 0 to quit.”);

while a != 0:
print (“Current Sum: “, sum);
a= float(input(“Enter Number: “));
a=float(a);
sum += a;
print(“Total Sum is: “, sum);

Example 3: Print 1 to 5 Numbers in reverse order…

val=5;
while (val >= 1):
print(val);
val = val-1;

Output:

5
4
3
2
1

Example 4: Print 1 to 10 Numbers in reverse order…

i=10;
while (i>=1):
print(i);
i=i-1;

Example 5: Print 1 to 10 Numbers except 4th Order

i=1;
while (i<=10):
if (i!=4):
print(i);
i=i+1;

2. for loop

for loop iterates over the items of any sequence, such as a list or a string.

Syntax:

for iterating_var in sequence:
statement(s);

Example 1:
a= [2, 4, 6, 8, 10, 12, 14];

for num in a:
print(num);

Output:
2
4
6
8
10
12
14
————————
Example 2:
for num in range(5):
print(num);

output:
0
1
2
3
4

Example 3: Print 1 to 10 Numbers

for num in range(1, 11):
print(num);

Example 4: Print 10 to 1 Numbers

for i in range(10, 0,-1):
print (i)

Example 5: Print 1 to 10 Numbers except 7th Number

for i in range(1, 11):
if (i !=7):
print (i)

Example 6: Print even numbers up to 10

for i in range(2, 11, 2):
print (i)

Note: If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions.

Note: we can use conditional statements only in our script, or loop statements only, or we can insert loops in Conditional statements and vice versa.

Python Syllabus

Step by Step Video Tutorial

Python Tutorial

Follow me on social media: