0% found this document useful (0 votes)
136 views14 pages

Control Structures in Python

The document discusses various types of loops in Python including for, while, and do-while loops. It provides examples of using each loop type to iterate through lists, strings, ranges of numbers, and check conditions. The key advantages of loops are code reusability and not having to repeat the same code multiple times. Break and continue statements are also covered, allowing loops to be exited or skipping the current iteration.

Uploaded by

James Ngugi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
136 views14 pages

Control Structures in Python

The document discusses various types of loops in Python including for, while, and do-while loops. It provides examples of using each loop type to iterate through lists, strings, ranges of numbers, and check conditions. The key advantages of loops are code reusability and not having to repeat the same code multiple times. Break and continue statements are also covered, allowing loops to be exited or skipping the current iteration.

Uploaded by

James Ngugi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 14

Python Loops

The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code may
need to be repeated several numbers of times.

For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.

Why we use loops in python?


The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of
the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the print statement 10 times, we can print inside a loop which runs up to 10
iterations.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.

Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested
loop. It is better to use for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop
until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also called
loop post tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
  print(x)

The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
  print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
  print(x)
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example

Using the start parameter:

for x in range(2, 6):


  print(x)

The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):

Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


  print(x)

The while Loop


With the while loop we can execute a set of statements as long as a condition is true.

Example

Print i as long as i is less than 6:

i=1
while i <= 6:
  print(i)
  i += 1#equivalent to i=i+1

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

3. Pass Statement - The pass statement is used to declare the empty loop. It is also used to
define empty class, function, and control statement. Let's understand the following example.
Example -

1. # An empty loop   
2. str1 = 'javatpoint'  
3. i = 0  
4.   
5. while i < len(str1):   
6.     i += 1  
7.     pass  
8. print('Value of i :', i)  

Output:

Value of i : 10

Example-1: Program to print 1 to 10 using while loop

1. i=1  
2. #The while loop will iterate until condition becomes false.  
3. While(i<=10):    
4.     print(i)   
5.     i=i+1   

Example -2: Program to print table of given numbers.

1. i=1    
2. number=0    
3. b=9    
4. number = int(input("Enter the number:"))    
5. while i<=10:    
6.     print("%d X %d = %d \n"%(number,i,number*i))    
7.     i = i+1    

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas zero indicates
the always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.

Example 1

1. while (1):    
2.     print("Hi! we are inside the infinite while loop")  
Example 2

1. var = 1    
2. while(var != 2):    
3.     i = int(input("Enter the number:"))    
4.     print("Entered value is %d"%(i))    

Using else with while loop


Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop is
broken using break statement, then the else block will not be executed, and the statement present
after else block will be executed. The else statement is optional to use with the while loop.
Consider the following example.

Example 1

1. i=1   
2. while(i<=5):    
3.     print(i)    
4.     i=i+1    
5. else:  
6.     print("The while loop exhausted")    

Example 2

1. i=1    
2. while(i<=5):    
3.     print(i)    
4.     i=i+1    
5.     if(i==3):    
6.         break   
7. else:  
8.     print("The while loop exhausted")  

In the above code, when the break statement encountered, then while loop stopped its execution
and skipped the else statement.

Example-3 Program to print Fibonacci numbers to given limit

1. terms = int(input("Enter the terms "))  
2. # first two intial terms  
3. a = 0  
4. b = 1  
5. count = 0  
6.   
7. # check if the number of terms is Zero or negative  
8. if (terms <= 0):  
9.    print("Please enter a valid integer")  
10. elif (terms == 1):  
11.    print("Fibonacci sequence upto",limit,":")  
12.    print(a)  
13. else:  
14.    print("Fibonacci sequence:")  
15.    while (count < terms) :  
16.        print(a, end = ' ')  
17.        c = a + b  
18.        # updateing values  
19.        a = b  
20.        b = c  
21.      
22.     count += 1  

Python break statement


The break is a keyword in python which is used to bring the program control out of the loop. The
break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner
loop first and then proceeds to outer loops. In other words, we can say that break is used to abort
the current execution of the program and the control goes to the next line after the loop.

The break is commonly used in the cases where we need to break the loop for a given condition.

The syntax of the break is given below.

1. #loop statements  
2. break;   

Example 1
1. list =[1,2,3,4]  
2. count = 1;  
3. for i in list:  
4.     if i == 4:  
5.         print("item matched")  
6.         count = count + 1;  
7.         break  
8. print("found at",count,"location");  

Example 2
1. str = "python"  
2. for i in str:  
3.     if i == 'o':  
4.         break  
5.     print(i);  

Example 3: break statement with while loop


1. i = 0;  
2. while 1:  
3.     print(i," ",end=""),  
4.     i=i+1;  
5.     if i == 10:  
6.         break;  
7. print("came out of while loop");  

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

Example 3
1. n=2  
2. while 1:  
3.     i=1;  
4.     while i<=10:  
5.         print("%d X %d = %d\n"%(n,i,n*i));  
6.         i = i+1;  
7.     choice = int(input("Do you want to continue printing the table, press 0 for no?"))  
8.     if choice == 0:  
9.         break;      
10.     n=n+1  

Python continue Statement


The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with the
next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition.The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.

Syntax
1. #loop statements    
2. continue  
3. #the code to be skipped     

Flow Diagram

Consider the following examples.

Example 1

1. i = 0                     
2. while(i < 10):                
3.    i = i+1  
4.    if(i == 5):  
5.       continue  
6.    print(i)  

Output:

Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.

Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty. It is the same as the name refers to. It just makes the
control to pass by without executing any code. If we want to bypass any code pass statement can
be used.

It is beneficial when a statement is required syntactically, but we want we don't want to execute
or execute it later. The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

1. # pass is just a placeholder for  
2. # we will adde functionality later.  
3. values = {'P', 'y', 't', 'h','o','n'}  
4. for val in values:  
5.     pass  

Example - 2:

1. for i in [1,2,3,4,5]:   
2.     if(i==4):  
3.         pass  
4.         print("This is pass block",i)  
5.     print(i)  

Control Structures
Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the
name implies, decision making allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a
block of code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also
Statement provides the block of the code for the false case of the condition to be checked.
If the condition provided in the if statement is false, then the else statement
will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if
Statement statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.

The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a
block of code known as if-block. The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.

1. if expression:  
2.     statement  

Example 1

1. num = int(input("enter the number?"))  
2. if num%2 == 0:  
3.     print("Number is even")  
4. else:
5. print(“the number is odd”)
6.

Example 2 : Program to print the largest of the three numbers.

1. a = int(input("Enter a? "));  
2. b = int(input("Enter b? "));  
3. c = int(input("Enter c? "));  
4. if a>b and a>c:  
5.     print("a is largest");  
6. if b>a and b>c:  
7.     print("b is largest");  
8. if c>a and c>b:  
9.     print("c is largest");  

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

1. if condition:  
2.     #block of statements   
3. else:   
4.     #another block of statements (else-block)   

Example 1 : Program to check whether a person is eligible to vote or not.

1. age = int (input("Enter your age? "))  
2. if age>=18:  
3.     print("You are eligible to vote !!");  
4. else:  
5.     print("Sorry! you have to wait !!");  

Example 2: Program to check whether a number is even or not.

1. num = int(input("enter the number?"))  
2. if num%2 == 0:  
3.     print("Number is even...")  
4. else:  
5.     print("Number is odd...")  

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block of
statements depending upon the true condition among them. We can have any number of elif
statements in our program depending upon our need. However, using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.

The syntax of the elif statement is given below.

1. if expression 1:   
2.     # block of statements   
3.   
4. elif expression 2:   
5.     # block of statements   
6.   
7. elif expression 3:   
8.     # block of statements   
9.   
10. else:   
11.     # block of statements  

Example 1

1. number = int(input("Enter the number?"))  
2. if number==10:  
3.     print("number is equals to 10")  
4. elif number==50:  
5.     print("number is equal to 50");  
6. elif number==100:  
7.     print("number is equal to 100");  
8. else:  
9.     print("number is not equal to 10, 50 or 100");  

Example 2
1. marks = int(input("Enter the marks? "))  
2. if marks > 85 and marks <= 100:  
3.    print("Congrats ! you scored grade A ...")  
4. elif marks > 60 and marks <= 85:  
5.    print("You scored grade B + ...")  
6. elif marks > 40 and marks <= 60:  
7.    print("You scored grade B ...")  
8. elif (marks > 30 and marks <= 40):  
9.    print("You scored grade C ...")  
10. else:  
11.    print("Sorry you are fail ?")  

You might also like