Python Language Loops
In general, statements are executed sequentially inwards Computer programming,
Programming languages supply diverse command structures that permit for more
complicated execution paths.
A loop disceptation allows us to execute a disceptation or grouping of statements multiple times.
Python programming linguistic communication provides ii loop structues,
1) piece loop
2) for loop to handgrip loop requirements...
---------------------------------
1) piece loop
It repeatedly executes statements piece status is true...
Syntax:
while (condition/expression):
statement(s);
Example one - Print one to x 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, too calculate sum, too Zero to quit from the loop
a=1;
sum=0;
print ("Enter a Number to add together to the sum: ");
print ("Enter 0 to quit.");
while a != 0:
impress ("Current Sum: ", sum);
a= float(input("Enter Number: "));
a=float(a);
amount += a;
print("Total Sum is: ", sum);
----------------------------------
3) Example 3: Print one to five Numbers inwards opposite 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 whatever sequence, such equally a listing or a string.
Syntax:
for iterating_var inwards sequence:
statement(s);
Example 1:
a= [2, 4, 6, 8, 10, 12, 14];
for num inwards a:
print(num);
Output:
2
4
6
8
10
12
14
------------------------
Example 2:
for num inwards range(5):
print(num);
output:
0
1
2
3
4
--------
Note: If you lot create postulate to iterate over a sequence of numbers, the built-in function range() comes inwards handy. It generates arithmetics progressions.
-----------------------------------
Note: nosotros tin utilisation conditional statements solely inwards our script, or loop statements only, or nosotros tin insert loops inwards Conditional statements too vice versa.
---------------------------