Showing posts with label Python: Loops. Show all posts
Showing posts with label Python: Loops. Show all posts

Python: Loops

 We can run a single statement or set of statements repeatedly using loop command. In Python, we can run a loop by three ways. The basic functionality of the three loop commands is the same, but differ from each other in syntax and the amount of time required for checking the condition.

The following loop commands are available in Python programming language.

Sr. No.

Name of the loop

Loop Type and Description

1

While loop

It repeats the statement, while given condition is true. It tests the condition before executing the loop body.

2

For loop

This type of loop executes the code block multiple times and abbreviates the codes that manages the loop variable.

3

Nested loops

In nested loop, we can iterate a loop inside another loop.


Loop Control Statements: Statements used to control loops and change the course of iteration are called control statements. All the objects produced within the local scope of the loops are deleted when execution is completed.
Python provides the following control statements:

Sr. No

Name of the control statement

Descriptions

1

Break statement

This command terminates the loop’s execution and transfers the program’s control to the statement next to the loop.

2

Continue statement

This command skips the current iteration of the loop. The statements following the continue statement are not executed, once the Python interpreter reaches the continue statement.

3

Pass statement

Pass statement is used when a statement is syntactically necessary but no code is to be executed.


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 the particular iteration is completed.
Code:
#Python program to show how the for loop works
#very first create a sequence, like here i create a tuple of numbers
numbers=[2, 8, 6, 7, 6, 4, 9, 8, 13, 25]
#now create a variable to store the square of the numbers
square=0
#now create an empty list of squares of the given numbers
squares=[]
#finally create a for loop in this way
for value in numbers:
    square=value**2
    squares.append(square)
print("The list of square is", squares)

Output:
The list of square is [4, 64, 36, 49, 36, 16, 81, 64, 169, 625]


Using else Statement with for loop:
It is well known that a for loop excutes the code block until the sequence element is reached. The else statement is written right after the for loop and it is executed after the execution of the for loop is complete.
The else statement generally executed after the for loop. But it will not executed if we exit the for loop or any error is found in program.
Syntax:
for value in sequence:
#executes the statements until the sequence is exhausted
else:
#executes the statement when for loop is completed.

Here is the program to better understand if-else statements:
Example:
#very first create a sequence
list1=(2,4,5,6,3,7,8,9)
#now start for loop
for value in list1:
    if value%2==0:
        print(value)
#use else statement
else:
    print("These are even numbers present in the list")

Output:
2
4
6
8
These are even numbers present in the list

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

#use of range function
print(range(15))
print(list(range(15)))

Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7. 8. 9, 10, 11, 12, 13, 14]


We can give specific start, stop and step size values in the following manner:
range(start, stop, step size)
if the step size is not specified the default is 1.
example:
#use of range function
print(list(range(5, 15)))
print(list(range(9, 15, 3)))

Output:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
[9, 12]

Another use of range() function is indexing to iterate through the given sequence by combining it with an iterable's len() function.
Here is a program to explain it better:

#Python program to iterate over a sequence with the help of indexing
list2=("Python", "Loops", "Sequence", "Condition", "Range")
#iterating over list2 using range() function
for iterator in range(len(list2)):
    print(list2[iterator].upper())

Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop: While loops are used in Python to iterate untill a specified condition is met. However, the statement in the program that follows the while loop is executed once the condition changes to false.
Syntax of the while loop is:
While<condition>:
{code block}

Block of codes to define the while loop better:
Example1:
#Program to define while loop
num = 1
#initiating the while loop
while num<15:
    num=num*2
    print(num)

Output:
2
4
8
16
In above example, variable num is storing a value 1. Then we start while loop and condition is given here, unless value of num cross 15, process to show num=num*2 will going on.
Here very first, value of num is 1.
So num=1
When loop will start
num=num*2
          1*2=2
          2*2=4
          4*2=8
          8*2=16
Now 16 cross 15, so loop will automatic terminated.

Example2:
#Program to define while loop
str = 0
#initiating the while loop
while str<10:
    str=str+2
    print("Python while loop")

Output:
"Python while loop"
"Python while loop"
"Python while loop"
"Python while loop"
"Python while loop"
In above example, till then the value of num will remain <10, it will continuing to show "Python while loop".
Very first, value of num=0
When loop starts
num=0+2=2 (1time)
         2+2=4 (2time)
         4+2=6 (3time)
         6+2=8 (4time)
         8+2=10 (5time), now value of num is not less than 10(<10). So loop will terminated and "Python while loop" is shown 5 times.

Using else statement with while loop
As discussed above (else statement with for loop), it works in same manner with while loop also. When the given condition becomes false, the else statement is shown.
Syntax is same as above(with for loop)
Know the else statement better with this example:

#Program to define while loop
num = 1
#initiating the while loop
while num<30:
    num=num*2
    print(num)
#when condition becomes false, else statement starts.
else:
    print("Terminated because 32 exceeds 30, so condition is false now")

Output:
2
4
8
16
32
Terminated because 32 exceeds 30, so condition is false now

Loop Control Statements: Now we will discuss the loop control statements in detail.
1. Continue Statement: It returns the control to the beginning of the loop.
Example1:
#Program to define continue control statement in loop.
#initiating the  loop
for string in "Python loop":
    if string=="P" or string=="t" or string=="o":
        continue
    print('Current letter:',string)

Output:
Current letter: y
Current letter: h
Current letter: n
Current letter: 
Current letter: l
Here, it is case sensitive. So, P and p are considered as different characters.

Example2:
#Program to define continue control statement in loop.
#initiating the  loop
list1=(4, 7, 9, 8, 3, 4)
for value in list1:
    if value%2==0 :
        continue
    print('odd number:',value)

Output:
odd number: 7
odd number: 9
odd number: 3

2. Break Statement: It stops the execution of the loop, when the break statement is reached.
Example1:
#Program to define break control statement in loop.
#initiating the  loop
for string in "Python loop":
    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: 

Example2:
#Program to define continue control statement in loop.
#initiating the  loop
list1=(4, 2, 12, 8, 6, 3, 14)
for value in list1:
    if value%2==1:
        break
    print('even number:',value)

Output:
even number: 4
even number: 2
even number: 12
even number: 8
even number: 6

3. Pass Statement: Pass statements are used to create empty loops
Example:
#Program to define pass control statement in loop.
for string in "Python loop":
        pass
print('last letter:',string)

Output:
last letter: p



Python: Functions