## Debug School

rakesh kumar

Posted on • Updated on

# Python:Loops

1.How to iterate or display the each value of number where data type is number using for loop
2.How to iterate the each value of number where data type is number using for loop
3.How to print the each letter of string with if-else statements using for loop
4.How to print even and odd no in tuples
5.How to iterate through a sequence of items using range() method in list data type using for loop
6.How to display the each value of tuple using indexing function for loop(for iterator in range(len(tuple_)))

``````for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
``````

display a prime no in number data type using for loop
display a multiplication number data type using for loop

for Loop
Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.

Syntax of the for Loop

for value in sequence:

`````` { code block }
``````

In this case, the variable value is used to hold the value of every item present in the sequence before the iteration begins until this particular iteration is completed.

Loop iterates until the final item of the sequence are reached.

Code
Python program to show how the for loop works

Creating a sequence which is a tuple of numbers

numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

*variable to store the square of the number *
square = 0

Creating an empty list

squares = []

Creating a for loop

``````for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)
``````

Output:

``````The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
``````

Using else Statement with for Loop
As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.

Only if the execution is complete does the else statement comes into play. It won't be executed if we exit the loop or if an error is thrown.

Here is a code to better understand if-else statements.

Code

P*ython program to show how if-else statements work*

string = "Python Loop"

``````# Initiating a loop
for s in a string:
# giving a condition in if block
if s == "o":
print("If block")
# if condition is not satisfied then else block will be executed
else:
print(s)
``````

Output:

``````P
y
t
h
If block
n

L
If block
If block
p
``````

Python program to show how to use else statement with for loop

``````# Creating a sequence
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)

# Initiating the loop
for value in tuple_:
if value % 2 != 0:
print(value)
# giving an else statement
else:
print("These are the odd numbers present in the tuple")
``````

Output:

``````3
9
3
9
7
These are the odd numbers present in the tuple
``````

The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be characterized as being "slow." It does provide in, len, and getitem actions, but it is not an iterator.

The example that follows will make this clear.

Code

Python program to show the working of range() function

``````print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))
``````

Output:

``````range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
``````

To iterate through a sequence of items, we can apply the range() method in for loops. We can use indexing to iterate through the given sequence by combining it with an iterable's len() function. Here's an illustration.

Code

Python program to iterate over a sequence with the help of indexing

``````tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")

# iterating over tuple_ using range() function
for iterator in range(len(tuple_)):
print(tuple_[iterator].upper())
``````

Output:

``````PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
``````

Using else Statement with while Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.

Code

Python program to show how to use else statement with the while loop

counter = 0

`````` Iterating through the while loop
while (counter < 10):
counter = counter + 3
print("Python Loops") # Executed untile condition is met
Once the condition of while loop gives False this statement will be executed
else:
print("Code block inside the else statement")
``````

Output:

``````Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
``````

Continue Statement
It returns the control to the beginning of the loop.

Code

Python program to show how the continue statement works

Initiating the loop

``````for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
``````

Output:

``````Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
``````

Break Statement
It stops the execution of the loop when the break statement is reached.

Code

Python program to show how the break statement works

Initiating the loop

``````for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)
``````

Output:

``````Current Letter:  P
Current Letter:  y
Current Letter:  t
Current Letter:  h
Current Letter:  o
Current Letter:  n
Current Letter:
``````

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.

Code

Python program to show how the pass statement works

``````for a string in "Python Loops":
pass
print( 'Last Letter:', string)
``````

Output:

``````Last Letter: s
``````

Python While Loop Example
Here we will sum of squares of the first 15 natural numbers using a while loop.

Code

Python program example to show the use of while loop

num = 15

`````` initializing summation and a counter for iteration
summation = 0
c = 1

while c <= num: # specifying the condition of the loop
# begining the code block
summation = c**2 + summation
c = c + 1    # incrementing the counter

print the final sum
print("The sum of squares is", summation)
``````

Output:

``````The sum of squares is 1240
``````

Prime Numbers and Python While Loop
Using a while loop, we will construct a Python program to verify if the given integer is a prime number or not.

Code

``````num = [34, 12, 54, 23, 75, 34, 11]

def prime_number(number):
condition = 0
iteration = 2
while iteration <= number / 2:
if number % iteration == 0:
condition = 1
break
iteration = iteration + 1

if condition == 0:
print(f"{number} is a PRIME number")
else:
print(f"{number} is not a PRIME number")
for i in num:
prime_number(i)
``````

Output:

``````34 is not a PRIME number
12 is not a PRIME number
54 is not a PRIME number
23 is a PRIME number
75 is not a PRIME number
34 is not a PRIME number
11 is a PRIME number
``````

Multiplication Table using While Loop
In this example, we will use the while loop for printing the multiplication table of a given number.

Code

``````num = 21
counter = 1
we will use a while loop for iterating 10 times for the multiplication table
print("The Multiplication Table of: ", num)
while counter <= 10: # specifying the condition
ans = num * counter
print (num, 'x', counter, '=', ans)
counter += 1 # expression to increment the counter
``````

Output:

``````The Multiplication Table of:  21
21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210
``````

Python While Loop with List
We will use a Python while loop to square every number of a list

Code

Python program to square every number of a list

`````` initializing a list
list_ = [3, 5, 1, 4, 6]
squares = []
programing a while loop
while list_: # until list is not empty this expression will give boolean True after that False
squares.append( (list_.pop())**2)
print the squares
print( squares )
[36, 16, 1, 25, 9]
``````

Python While Loop Multiple Conditions
We'll need to recruit logical operators to combine two or more expressions specifying conditions into a single while loop. This instructs Python on collectively analyzing all of the given expressions of conditions.

We can construct a while loop with multiple conditions in this example. We have given two conditions and a and keyword, meaning until both conditions give boolean True, the loop will execute the statements.

Code

``````num1 = 17
num2 = -12

while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
num1 -= 2
num2 += 3
print( (num1, num2) )
``````

Output:

``````(15, -9)
(13, -6)
(11, -3)
``````

We can also group multiple logical expressions in the while loop, as shown in this example.

Code

``````num1 = 9
num = 14
maximum_value = 4
counter = 0
while (counter < num1 or counter < num2) and not counter >= maximum_value: # grouping multiple conditions
print(f"Number of iterations: {counter}")
counter += 1
``````

Output:

``````Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3
``````

Example 3

``````n=2
while 1:
i=1;
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i));
i = i+1;
choice = int(input("Do you want to continue printing the table, press 0 for no?"))
if choice == 0:
break;
n=n+1
``````

Output:

``````2 X 1 = 2

2 X 2 = 4

2 X 3 = 6

2 X 4 = 8

2 X 5 = 10

2 X 6 = 12

2 X 7 = 14

2 X 8 = 16

2 X 9 = 18

2 X 10 = 20

Do you want to continue printing the table, press 0 for no?1

3 X 1 = 3

3 X 2 = 6

3 X 3 = 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
``````

Do you want to continue printing the table, press 0 for no?0

Code

Python code to show example of continue statement

``````looping from 10 to 20
for iterator in range(10, 21):

If iterator is equals to 15, loop will continue to the next iteration
if iterator == 15:
continue
otherwise printing the value of iterator
print( iterator )
``````

Output:

``````10
11
12
13
14
16
17
18
19
20
`````` Some More Examples      