Decision Control Statements
Decision Control Statements: Decision
control statements
Selection/conditional branching
Statements: if, if-else, nested if, if-elif-
else statements .
Basic loop Structures/Iterative
statements: while loop, for loop,
selecting appropriate loop. Nested loops,
The break, continue, pass, else statement
used with loops.
Decision Control Statements:
We have the two types of Control statement in
Python:
Branching (Decision Making Statement):
If, If..else, if…elif….else.
Loop(Flow Control Statement):
for, while, break, continue
It is used when we have to take some decision like
the comparison between anything or to check the
presence and gives us either TRUE or FALSE.
The syntax:
if (expression):
code to be executed under
the condition statement1
statement2
var1 = 10
var2 = 12
if var2 > var1: #if true, if block is executed
print(“var2 is greater”)
if var1 > var1: #if flase, if block will not not executed
print(“Var1 is greater”)
print(“Other statements”)
If….else Statement
The else statement can be used with the if statement. It
usually contains the code which is to be executed at the
time when the expression in the if statement returns the
FALSE. There can only be one else in the program with every
single if statement
It is optional to use the else statement with if statement it
depends on your condition.
The syntax for If….Else Statement is as:
if (expression): #body of if
statement1
statement2
else: #body of else
statement1
statement2
var1 = 10
var2 = 12
if var2 > var1: #if block executed if its condn true
print( “var2 is greater than var1”)
else: #else block executed when „if‟ condn false
print(“var1 is greater than var2”)
print(“Good Bye”)
The Elif Statement
Theelif statement in the Python is used to
check the multiple expression for TRUE and
execute a block of code as soon as one of the
conditions returns to TRUE.
Syntax:
if expression: #body to be executed in if
statement x
elif: #body to be executed in elif
statement y
else: #body to be executed in else
statement z
e.g:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Python Nested if..(if within if)
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
O/P:?
Example: largest among three numbers
--Program statement are executed sequentially one
after another. In some situations, a block of code
needs of times.
--Loops are used in programming to repeat a
specific block of code.
--These are repetitive program codes, the computers
have to perform to complete tasks.
--The following are the loop structures available in
python.
while statement
for loop statement
nested loop statement
While loop
In python, while loop is used to execute a block of
statements repeatedly until a given a condition is
satisfied.
And when the condition becomes false, the line
immediately after the loop in program is executed.
Syntax :
while expression:
statement(s)
e.g:
count = 0
while (count < 3):
count = count + 1
print(“Python")
E.g:
counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else“)
o/p:??
Que: Print numbers from 1 to 10
Ans:
i=1
while i<=10:
print(i)
i=i+1
Que: Print numbers from 10 to 1
Addition of natural nos upto given no:
i=1
n=10
sum = 0
while i <= n:
sum = sum + i
i = i+1 # update counter
print("The sum is", sum) # print the sum
O/P:??
Eg:
Que: Even no between 1 to 10
counter = 1
while counter<= 10:
if counter%2==0:
print(counter)
counter = counter + 1
else:
print("Inside else")
For loop:
The for loop in Python is used to iterate over a sequence
(list, tuple, string) or other iterable objects. Iterating
over a sequence is called traversal.
Syntax of for Loop:
for val in sequence:
body of for loop
Here, val is the variable that
takes the value of the item inside
the sequence on each iteration.
Loop continues until we reach
the last item in the sequence.
The body of for loop is separated from the rest of the
code using indentation.
e.g:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
o/p??
e.g:
primes = (2, 3, 5, 7)
for prime in primes:
print(prime)
e.g:
# Program to find the sum of all numbers stored in a list
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
o/p?
The range() function in for loop
We can generate a sequence of numbers
using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size
as range(start, stop, stepsize). step size defaults to
1 if not provided.
Syntax:
for var in range(start, stop, stepsize)
e.g:
for x in range(5):
print(x)
e.g:
for x in range(3,6):
print(x)
e.g:
for x in range(3,16,2):
print(x)
e.g: Addition of 1 to 10 numbers
sum=0
for a in range(1,11):
sum=sum+a
print(sum)
e.g: Table of 5
i=1;
num=int(input(”Enter number”))
for i in range(1,11):
print(num,i,num*i)
Nested Loops:
Python programming language allows to use one loop
inside another loop.
You can put any type of loop inside of any other type of
loop.
Also you can nest any no of for loops within for loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
e.g:
for x in range(1,3):
for y in range(1,4):
print("Python")
o/p:??
Que:Check given number is prime or not
num=int(input("Enter a number: "))
if num>1:
for i in range(2,num): #from 2 to given no it checks remainder
#whether 0 or not.
if(num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
o/p:
4
4 is not a prime number
else with for and while loop..
A for loop and while loop can have an optional else block as
well. The else part is executed if the items in the sequence
used in loop are exhausts..or after loop terminated.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
digits = [0, 1, 5]
e.g:
for i in range(0,5):
print(i)
else:
print("No items left.")
pass Loop:
In Python, 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 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.
e.g: o/p:
1
for num in range(1,10): 2
if num==6: 3
4
pass 5
else: 7
8
print(num) 9
o/p:
e.g:
for num in [5,6,8]:
if num==6:
pass
print(“at the time pass”,num)
print(num)
o/p:
5
at the time pass 6
6
8
break statement:
The break statement terminates the loop
containing it. Control of the program flows to
the statement immediately after the body of
the loop.
If break statement is inside
a nested loop (loop inside
another loop), break will
terminate the innermost loop.
Syntax :
break
for val in range(1,5):
if val==“3":
break
print(val)
print("The end")
o/p:
1
2
The end
for val in "string":
if val=="i":
break
print(val)
print("The end")
o/p:
S
T
R
The end
Python continue statement
The continue statement is used to skip the rest of
the code inside a loop for the current iteration
only.
Loop does not terminate but continues on with
the next iteration.
e.g: o/p:
s
t
r
for val in "string": n
if val == "i": g
continue the end
print(val)
print("The end“)
e.g:
for i in range(1,8):
if i==5:
continue;
print("%d"%i);
e.g:
i=0
while i<=3:
print(i)
continue
i=i+1
Lists:
How to create a list?
In Python programming, a list is created by placing all the
items (elements) inside a square bracket [ ], separated by
commas.
It can have any number of items and they may be of different
types (integer, float, string etc.).
It is mutable, so we can add, remove, sort, reverse elements
from list.
We can create list as…
my_list = []
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4]
nested list:
my_list = [“Tiger", [8, 4, 6], ['a']]
Access elements from a list?
We can use the index operator [] to access an item
in a list.
If there is no element then returns indexError
If index is not integer then returns typeError
e.g
my_list = ['p','r','o','b','e']
print(my_list[0])
print(my_list[4])
OP:
p
e
Negative indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the
second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1])
print(my_list[-5])
Output:
e
p
Slice lists in Python:
We can access a range of items in a list by using the
slicing operator:(colon)
my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
print(my_list[:5])
print(my_list[:-5]) #prints 0 to -6
print(my_list[5:])
print(my_list[:])
OP:
['o', 'g', 'r']
['p', 'r', 'o', 'g„, 'r']
['p', 'r', 'o', 'g']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']
Add elements to list:
e.g:
odd = [1, 3, 5]
[Link](7)
print(odd)
[Link]([9, 11, 13])
print(odd)
# Output:
[1, 3, 5, 7, 9, 11, 13]
[1, 3, 5, 7]
delete or remove elements from a list:
We can delete one or more items from a list using
the keyword del. It can even delete the list
entirely.
We can use remove() method to remove the given
item or pop() method to remove an item at the
given index.
The pop() method removes and returns the last
item if index is not provided. This helps us
implement lists as stacks (first in, last out data
structure).
We can also use the clear() method to empty a list.
my_list = ['p','r','o','b','l','e','m']
del my_list[2]
print(my_list)
del my_list[1:5]
print(my_list)
del my_list
print(my_list)
Output:
['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
#Error: List not defined
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
print(my_list)
print(my_list.pop(1))
print(my_list)
print(my_list.pop())
print(my_list)
my_list.clear()
print(my_list)
Output:
['r', 'o', 'b', 'l', 'e', 'm']
'o'
['r', 'b', 'l', 'e', 'm']
'm'
['r', 'b', 'l', 'e']
[]
List Methods:
len(): returns number of an elements in list
e.g:
num=[2,5,9]
print(len(num))
OP: 3
max(): returns largest element from list
num=[2,5,9]
print(max(num))
OP: 9
min(): returns smallest element
num=[2,5,9]
print(min(num))
OP: 2
Sum: This method will make addition of all the numbers in list
e.g:
num=[2,5,9]
print(sum(num))
OP: 16
all: Returns true if all elements of list are true
num=[2,5,9]
print(all(num))
OP: True
not in: checks if the value is not present in the list
num=[2,5,9]
print(4 not in num)
OP: True
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
Dictionary:
It‟s a unordered collection of items.
dictionary has a key: value pair
Dictionaries are used to retrieve values when the key is
known.
Dictionary value is mutable, so we can add new items
or change values
Keys are immutable, we can not change keys
creating a dictionary:
We can insert elements using curly braces {} separated
by comma.
An item has a key and the corresponding value
expressed as a pair, key: value.
While values can be of any data type and can repeat,
keys must be of immutable type (string, number and
tuple with immutable elements) and must be unique.
We can create dictionary by following ways:
my_dict = {}
my_dict = {1: 'apple', 2: 'basket'} # dictionary with integer keys
my_dict = {'name': 'John', 1: [2, 4, 3]} # dictionary with mixed keys
access elements from a dictionary:
While indexing is used with other container types to
access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.
The difference while using get() is that it
returns None instead of KeyError, if the key is not
found.
my_dict = {'name':'Jack', 'age': 26}
print(my_dict['name'])
print(my_dict.get('age'))
Output:
Jack
26
Add or change elements in a dictionary:
Dictionary are mutable. We can add new items or change
the value of existing items using assignment operator.
If the key is already present, value gets updated, else a
new key: value pair is added to the dictionary
my_dict = {'name':'Jack', 'age': 26}
my_dict['age'] = 27 #update item
print(my_dict) # {'name': 'Jack„, 'age': 27}
my_dict['address'] = 'Downtown' #add item
print(my_dict) # {'name': 'Jack„,„age': 27, 'address': 'Downtown'}
delete or remove elements from a
dictionary:
We can remove a particular item in a dictionary by
using the method pop(). This method removes as item
with the provided key and returns the value.
All the items can be removed at once using
the clear() method.
We can also use the del keyword to remove individual
items or the entire dictionary itself.
squares = {1:1, 2:4, 3:9, 4:16, 5:25} # create a dictionary
print([Link](4)) #Output: 16 remove a particular item
print(squares) # Output: {1: 1, 2: 4, 3: 9, 5: 25}
del squares[3] # delete a particular item
print(squares) #Output:{1: 1, 2: 4}
[Link]() #remove all items
print(squares) # Output: { }
del squares # delete the dictionary itself