Professional Documents
Culture Documents
CONDITIONAL STATEMENTS
BY AMIT PATEL
CONDITIONAL STATEMENTS
In order to write useful programs, we almost always need the ability to check conditions and
change the behavior of the program accordingly. Conditional statements give us this ability.
Branching statement means the ability of program to alter its execution sequences.
It contains a body of code which runs only when the condition given in the if statement is
true.
If <condition> :
statements
CONDITIONAL STATEMENTS : if
The colon (:) is significant and required. It separates the header of the compound
statement from the body.
The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.
All lines indented the same amount after the colon will be executed whenever the condition
is true.
CONDITIONAL STATEMENTS : if
For Example
food = ‘pizza'
if food == ‘pizza':
print('Ummmm, my favorite!')
It is frequently the case that you want one thing to happen when a condition true, and
something else to happen when it is false.
If <condition> :
statements
else :
statements
CONDITIONAL STATEMENTS : if … else
For Example
food = ‘pizza'
if food == ‘pizza':
print('Ummmm, my favorite!’)
else:
For Example:
a_number=13;
Output:
depending upon our need. However, using elif is optional. elif <condition> :
statements
The elif statement works like an if-else-if ladder statement in
<else:>
C. It must be succeeded by an if statement.
statements
CONDITIONAL STATEMENTS : elif
print(“number
{ } is equals to 10“,.format(number))
Output:
elif number==50: Enter the number?15
if statements cannot be empty, there must be at least one statement in every if and elif block.
You can use the pass statement to do nothing and avoid getting an error.
For example:
a_number = 9
Output:
if a_number % 2 == 0: elif a_number % 3 == 0: File "<ipython-input-33-77268dd66617>", line 2
print('{} is divisible by 3 but not divisible by 2') elif a_number % 3 == 0:
^ IndentationError: expected an indented block
“pass” statement
a_number=9
if a_number % 2 == 0:
pass
elif a_number % 3 == 0:
Output:
9 is divisible by 3 but not divisible by 2
format( )
The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder
section below.
Where value1,value2 is required. It is the value that should be formatted and inserted in the string.
For Example:
The value is converted into a boolean automatically using the bool operator.
This means that false values like 0, '', {}, [], None etc. evaluate to False and all other values
evaluate to True.
Non Boolean Condition
if '': if “Hi”:
else: else:
Output:
Output:
The condition evaluted to False The condition evaluted to True
LOOPING STATEMENT
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.
LOOPING STATEMENT
Advantages of loops
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
LOOPING STATEMENT : for
The for loop in Python is used to iterate the statements or a part of the program several times. It
is frequently used to traverse the data structures like list, tuple, or dictionary.
Syntax:
statement(s)
LOOPING STATEMENT : for
sum = sum+i M
O Output:
print("The sum is:",sum)
N Key: name , Value: Om
D Key: age , Value: 32
Output:
A
The sum is: 183
Y
FOR LOOP USING range( )
The range function is used to create a sequence of numbers that can be iterated over using
a for loop. It can be used in 3 ways:
The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1
to 4 iterations. It is optional.
The step size is used to skip the specific numbers from the iteration. It is optional to use. By
default, the step size is 1. It is optional.
Note : range( )
To quickly recap the range() function when passing one, two, or three parameters:
One parameter will create a sequence, one-by-one, from zero to one less than the parameter.
Two parameters will create a sequence, one-by-one, from the first parameter to one less than
the second parameter.
Three parameters will create a sequence starting with the first parameter and stopping before
the second parameter, but this time increasing each step by the third parameter.
FOR LOOP USING range( )
For Example
for i in range(10): n = int(input("Enter the number ")) list = [‘om',‘sai',’ram‘]
for i in range(2,n,2): for i in range(len(list)):
print(i,end = ' ')
print(i) print("Hello",list[i])
2 sai
4 ram
6
8
FOR LOOP WITH ELSE()
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
The break keyword can be used to stop a for loop. In such cases, the else part is ignored.
For Example
digits = [0, 1, 5] Here, the for loop prints items of the list until the loop
for i in digits: exhausts. When the for loop exhausts, it executes the block of
else: This for...else statement can be used with the break keyword to
run the else block only when the break keyword was not executed.
print("No items left.")
Output:
0 1 5 No items left.
Note
For Example: We want to print number 5 and if we write following code it gives above error.
for x in 5:
print(x)
In the above example, we are trying to iterate through a for loop using an integer value. But the
integers are not inerrable. As the single integer value 5, it cannot be iterated using a for loop or any
other loop.
Note
For Example: We want to print number 5 in the following way , using list, it cant give error
for x in [5]:
print(x)
Output : 5
In the above example, we printing the elements of the list using the for loop. since the list is an iterable
object, thus we can use the for loop to iterate through it.
To check which datatype is inerrable and which is not , Write following code: It show all method of list. Find
_iter_ method : If it is present then datatype is inerrable.
List= [ ]
print(dir(List))
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.
We generally use this loop when we don't know the number of times to iterate beforehand.
Syntax
while test_expression:
Body of while
LOOPING STATEMENT : WHILE
In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True.
After one iteration, the test expression is checked again. This process continues until
the test_expression evaluates to False.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
LOOPING STATEMENT : WHILE
For Example
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
Output:
i = i+1
The sum is 55
print("The sum is", sum)
WHILE LOOP WITH ELSE()
Same as with for loops, while loops can also have an optional else block.
The else part is executed if the condition in the while loop evaluates to False.
The while loop can be terminated with a break statement. In such cases, the else part is ignored.
Hence, a while loop's else part runs if no break occurs and the condition is false.
LOOPING STATEMENT : WHILE
For Example
counter = 0
Output:
while counter < 3:
Inside loop
print("Inside loop")
Inside loop
counter = counter + 1
Inside loop
else: Inside else
print("Inside else")
Note: When to use which loop?
Use while loop when you want to repeat an action until a condition
changes.
Use for loop when there’s a sequence of element that you want to
iterate.
“break” Statement
For Example:
For Example:
loops can be nested inside other loops. This is useful for looping lists of lists, dictionaries etc.
Output:
For Example:
Monday apple
days = ['Monday', 'Tuesday', 'Wednesday']
Monday banana
fruits = ['apple', 'banana', 'guava']
Monday guava
for day in days: Tuesday apple
for fruit in fruits: Tuesday banana
print(day, fruit) Tuesday guava
Wednesday apple
Wednesday banana
List
Mutable type its mean we can modify its element after it created.
The items in the list are separated with the comma (,) .
For Example: L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
2. To call the Python list built-in function by passing the items to it.
List in python doesn't enforce to have a single item type in it. You can have a list of different items.
This gives you the flexibility to add multiple data types in the list.
You can add a list inside this list. This is called a nested list.
Method Description
append() adds an element to the end of the list
Method Description
sort() sort items in a list in ascending order
In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.
print(my_list[4]) #e
Access Element from List : slicing
print(my_list[:]) # ['p','r','o','g','r','a','m','i',‘n']
Access Element from List : Negative Index
The last element (rightmost) of the list has the index -1.
Its adjacent left element is present at the index -2 and so on until the left-most elements are
encountered.
Access Element from List : Negative Index
Print(my_list[-4:-2] #[‘r’,’o’]
print(my_list[-1]) #e
print(my_list[-5]) #p
Updating Element in List
For Example:
odd = [1, 3, 5]
odd. append(7)
print(odd)
Output:
odd. extend([9, 11, 13]) [1, 3, 5, 7]
print(odd) [1, 3, 5, 7, 9, 11, 13]
Updating Element in List
list = [1, 2, 3, 4, 5, 6]
print(list)
print(list) # It will add value at the end of the list
list[-1] = 25
# assign value to the value to the second index
print(list)
list[2] = 10
print(list) Output:
[1, 2, 3, 4, 5, 6]
# Adding multiple-element
[1, 2, 10, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Updating Element in List
Lists are the most versatile data structures in Python since they are mutable, and their values
can be updated by using the slice and assignment operator.
Python also provides append() and insert() methods, which can be used to add values to the
list.
Consider the following example to update the values inside the list.
Updating Element in List
list = [1, 2, 3, 4, 5, 6]
print(list)
print(list) # It will add value at the end of the list
list[-1] = 25
# assign value to the value to the second index
print(list)
list[2] = 10
print(list) Output:
[1, 2, 3, 4, 5, 6]
# Adding multiple-element
[1, 2, 10, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Deleting Element from List
Method Description
For Example:
remove() method if we do not know which element is to be deleted from the list.
The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (first in, last out data structure).
And, if we have to empty the whole list, we can use the clear() method.
Deleting Element from List
For Example:
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm‘] # remove ‘m’
print(my_list.pop())
my_list.remove(‘p’) Output
print(my_list)
['r', 'o', 'b', 'l', 'e', 'm']
print(my_list) # Clear whole list
o
my_list.clear()
# remove ‘o’ using pop ['r', 'b', 'l', 'e', 'm']
# Output: []
m
my_list.pop(1) print(my_list)
['r', 'b', 'l', 'e']
[]
Copy List
For Example:
Using =
old_list = [1, 2, 3]
new_list = old_list
If you modify new_list, old_list is also modified. It is because the new list is referencing or
pointing to the same old_list object.
Copy List
For Example:
old_list = [1, 2, 3]
# copy list using =
new_list = old_list
# add an element to list
new_list. append('a')
Output
print('New List:', new_list)
Old List: [1, 2, 3, 'a']
print('Old List:', old_list)
New List: [1, 2, 3, 'a']
Copy List
For Example:
list = ['cat', 0, 6.7]
# copying a list using slicing
new_list = list[:]
# Adding an element to the new list
new_list.append('dog')
# Printing new and old list
print('Old List:', list) Output
Old List: ['cat', 0, 6.7]
print('New List:', new_list
New List: ['cat', 0, 6.7, 'dog']
Reverse List
For Example:
For Example:
For Example:
For Example:
sort() method sorts the elements of a given list in a specific ascending or descending order.
reverse : If True, the sorted list is reversed (or sorted in Descending order)
key : function that serves as a key for the sort comparison
Return value : The sort() method doesn't return any value. Rather, it changes the original list.
If you want a function to return the sorted list rather than change the original list, use sorted().
sort( ) Vs sorted() : sort( ) changes the list directly and doesn't return any value,
while sorted() doesn't change the list and returns the sorted list.
Sorted List
For Example:
count() method returns the number of times the specified element appears in the list.
For Example:
Concatenation It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
(+) operator.
Membership It returns true if a particular item exists in a particular list print(2 in l1)
( in ) otherwise false. Give output as True.
Length It is used to get the length of the list len(l1) = 4
Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Write a program to print the sum of list
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is 67
Write the program to find the lists consist of at least one common element.
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:
The common element is 2
Exercise
Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do
this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in
the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list
comprehension.
Exercise
def pig_latin(text):
say = ""
words = text.split()
for word in words:
---------------------------
---------------------------
say=say+text+" "
return say