Python Loops

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);
———————————-
3) 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
———————————-
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
——–
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 Step by Step Tutorial

1) In Which sequence should We learn Python?

2) Introduction to Python

3) Download & Install Python

4) Variables and Data Types in Python

5) Python Operators

6) Python Conditional Statements

7) Python Loops…

8) String Handling in Python

9) Python Lists
——————————

(274)

You may also like...

Leave a Reply