Loops and Control Statements
Python If Else
• There comes situations in real life when we need to make some
decisions and based on these decisions, we decide what should we do
next.
• Similar situations arise in programming also where we need to make
some decisions and based on these decisions we will execute the next
block of code.
• Decision-making statements in programming languages decide the
direction(Control Flow) of the flow of program execution.
Types of Control Flow in Python
• In Python programming language, the type of control flow statements
are as follows:
• The if statement
• The if-else statement
• The nested-if statement
• The if-elif-else ladder
IF Statement
• The if statement is the most simple decision-making statement.
• It is used to decide whether a certain statement or block of statements
will be executed or not.
• Syntax:
if condition:
# Statements to execute if
# condition is true
IF Statement
• Here, the condition after evaluation will be either true or false.
• if the statement accepts boolean values – if the value is true then it will execute the
block of statements below it otherwise not.
• As we know, python uses indentation to identify a block.
• So the block under an if statement will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Flowchart of Python if statement
IF Statement
• Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• These conditions can be used in several ways, most commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
EXAMPLE
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
a = 33
b = 200
if b > a:
print("b is greater than a")
0UTPUT
b is greater than a
EXAMPLE
• a = 33
b = 200
if b > a:
print("b is greater than a")
• # you will get an error
if-else statement
• The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t.
• But if we want to do something else if the condition is false, we can use the else statement
with if statement to execute a block of code when the if condition is false.
• Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Flowchart of Python if-else statement
Example of Python if-else statement
• The block of code following the else statement is executed as the condition present in the if
statement is false after calling the statement which is not in the block(without spaces).
• # python program to illustrate If else statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Else
• The else keyword catches anything which isn't caught by the PREVIOUS
conditions.
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")
In this example a is greater than b, so the first condition is not true,also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".
You can also have an else without the elif:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
nested-if statement
• A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement.
• Yes, Python allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.
• Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart of Python Nested if Statement
Nested If
.
Python program to demonstrate # nested if statement
• # python program to illustrate nested If statement
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
if-elif-else ladder
• Here, a user can decide among multiple options.
• The if statements are executed from the top down.
• As soon as one of the conditions controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be executed.
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Flowchart of Python if-elif-else ladder
Example of Python if-elif-else ladder
# Python program to illustrate if-elif-else ladder
i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Short Hand if statement
• Whenever there is only a single statement to be executed inside the if
block then shorthand if can be used.
• The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Short Hand if statement
Example of Python if shorthand
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")
Short Hand if-else statement
• This can be used to write the if-else statements in a single line where
only one statement is needed in both if and else block.
• Syntax:
statement_when_True if condition else statement_when_False
Example of Python if else shorthand
• # Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)
Loops in Python
• Python programming language provides the following types of loops
to handle looping requirements.
•while loops
•for loops
Python For Loops
• A for loop is used for repeating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
• With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.
While Loop in Python
• In python, a while loop is used to execute a block of statements repeatedly until a
given condition is satisfied.
• And when the condition becomes false, the line immediately after the loop in the
program is executed.
Syntax:
while expression:
statement(s)
• All the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code.
• Python uses indentation as its method of grouping statements.
The while Loop
• Example
• Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
For Loop in Python
• For loops are used for sequential traversal.
• For example: traversing a list or string or array etc.
• In Python, there is “for in” loop which is similar to for each loop in
other languages.
• Let us learn how to use for in loop for sequential traversals.
• Syntax:
for iterator_var in sequence:
statements(s)
• It can be used to iterate over a range and iterators.
Example
• # Python program to illustrate
• # Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)
Example with List, Tuple, string, and
dictionary iteration using For Loops in
Python
# Iterating over a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
Example with List, Tuple, string, and
dictionary iteration using For Loops in
Python
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)
Example with List, Tuple, string, and
dictionary iteration using For Loops in
Python
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("%s %d" % (i, d[i]))
# Iterating over a set
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Nested Loops
• Python programming language allows to use one loop inside another
loop.
• Following section shows few examples to illustrate the concept.
• Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Nested Loops
• The syntax for a nested while loop statement in the Python
programming language is as follows:
while expression:
while expression:
statement(s)
statement(s)
Nested for
• A nested loop is a loop inside a loop.
• Example
• Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Using else statement with While Loop in
Python
• The else clause is only executed when your while condition becomes false.
• If you break out of the loop, or if an exception is raised, it won’t be executed.
• Syntax of While Loop with else statement:
while condition:
# execute these statements
else:
# execute these statements
Examples of While Loop with else statement
• # Python program to illustrate
• # combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello world")
else:
print("In Else Block")
Infinite While Loop in Python
• If we want a block of code to execute infinite number of time, we can use
the while loop in Python to do so.
• # Python program to illustrate
• # Single statement while block
count = 0
while (count == 0):
print("Hello World")
Note: It is suggested not to use this type of loop as it is a never-ending infinite
loop where the condition is always true and you have to forcefully terminate
the compiler.
Using else statement with for loop in Python
• We can also combine else statement with for loop like in while loop.
• But as there is no condition in for loop based on which the execution will terminate so the else
block will be executed immediately after for block finishes execution.
• # Python program to illustrate
• # combining else with for
list = ["geeks", "for", "geeks"]
for index in range(len(list)):
print(list[index])
else:
print("Inside Else Block")
Loop Control Statements
• Continue Statement
• Break Statement
• Pass Statement
The continue Statement
• With the continue statement we can stop the current iteration, and continue with
the next:
• Example
• Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i) op; 1 2 4 5 6: 3 is missing
The break Statement
• With the break statement we can stop the loop even if the while condition
is true:
• Example
• Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The pass Statement
• if statements cannot be empty, but if you for some reason have an if
statement with no content:
put in the pass statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
• # having an empty if statement like this, would raise an error without the
pass statement
Example
• Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Example
• Loop through the letters in the word "banana":
for x in "banana":
print(x)
Function
• Python Functions is a block of statements that
return the specific task.
• The idea is to put some commonly or repeatedly
done tasks together and make a function so that
instead of writing the same code again and again for
different inputs, we can do the function calls to
reuse code contained in it over and over again.
Advantage of Function
• Increase Code Readability
• Increase Code Reusability
• Reducing the duplication of code: i.e. You don’t have to write the code
gain and again
• Improved reusability of code. One function can be call several times
• Clearer code: Each code can be identified for the particular task.
• Bigger problems are broken down into smaller problems: We can
bread the code into several function and can be assigned.
Python Function Declaration
• The syntax to declare a function is:
Types of Functions in Python
• There are mainly two types of functions in Python.
1. Built-in library function: These are Standard functions in Python that
are available to use.
2. User-defined function: We can create our own functions based on
our requirements.
Creating a Function in Python
• In Python a function is defined using the def keyword:
• Example
def my_function():
print("Hello from a function")
Calling a Function
• After creating a function in Python we can call it by using the
name of the function followed by parenthesis containing
parameters of that particular function:
• Example
• def my_function():
print("Hello from a function")
my_function()
Python Function with Parameters
• Defining and calling a function with parameters
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Example
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside
the parentheses.
• You can add as many arguments as you want, just
separate them with a comma.
Python Function Arguments
In this example, we will create a simple function in Python to check whether the number passed as an argument to
the function is even or odd.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Number of Arguments
• By default, a function must be called with the correct
number of arguments.
• Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more,
and not less.
Types of Python Function Arguments
• Python supports various types of arguments that can be passed at the
time of the function call.
• In Python, we have the following 4 types of function arguments.
1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4. Arbitrary arguments (variable-length arguments *args and
**kwargs)
Default Arguments
• A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument.
• The following example illustrates Default arguments.
• # Python program to demonstrate
• # default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Keyword Arguments
• The idea is to allow the caller to specify the argument name with
values so that the caller does not need to remember the order of
parameters.
• # Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname=‘NEW', lastname=‘Horizon')
student(lastname=‘New Horizon', firstname=‘Bengaluru')
Positional Arguments
• Position-only arguments mean whenever we pass the arguments in the order we have defined function parameters
in which if you change the argument position then you may get the unexpected output.
• We should use positional Arguments whenever we know the order of argument to be passed.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because argument is given in order
print("Case-1:")
nameAge("Prince", 20)
# You will get incorrect output because argument is not in order
print("\nCase-2:")
nameAge(20, "Prince")
Arbitrary Keyword Arguments
• In Python Arbitrary Keyword Arguments, *args, and **kwargs can
pass a variable number of arguments to a function using special
symbols.
• There are two special symbols:
1. *args in Python (Non-Keyword Arguments)
2. **kwargs in Python (Keyword Arguments)
Variable length non-keywords argument
• Example 1:
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', ‘New Horizon College')
Variable length keyword arguments
• Example 2:
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myCollege(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myCollege(first=‘New', mid=‘Horizon', last=‘Bengaluru')
Python Return
• The Python return statement is used to return a value from a
function.
• The user can only use the return statement in a function.
• It cannot be used outside of the Python function. A return
statement includes the return keyword and the value that will be
returned after that.
• Syntax of return statement:
def funtion_name():
statements
return [expression]
Python Function Return Statement
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Passing a List as an Argument
• You can send any data types of argument to a function
(string, number, list, dictionary etc.),
• and it will be treated as the same data type inside the
function.
• def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
The pass Statement
• function definitions cannot be empty, but if you for some reason
have a function definition with no content, put in the pass statement
to avoid getting an error.
• The pass Statement
built-in python functions
• Built-in functions are ones for which the compiler generates
inline code at compile time.
• There are 68 built-in python functions.
Python Lambda Functions
• Python Lambda Functions are anonymous function means that the function is without a
name.
• As we already know that the def keyword is used to define a normal function in Python.
• Similarly, the lambda keyword is used to define an anonymous function in Python.
• Python Lambda Function Syntax
• Syntax:
lambda arguments: expression
• This function can have any number of arguments but only one expression, which is evaluated and
returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to a single
expression.
• It has various uses in particular fields of programming, besides other types of expressions in functions.
Python Lambda
• A lambda function is a small function.
• A lambda function can take any number of arguments, but can only
have one expression.
• Syntax
lambda arguments : expression
• The expression is executed and the result is returned:
• Ex:
lambda display: print('Hello World')
Example
• # lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)
# lambda call
greet_user(‘User')
# Output: Hey there, User
Python Lambda Function Example
• Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
• Lambda functions can take any number of arguments:
• Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
• Summarize argument a, b, and c and return the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Python Lambda Function Example
• str1 = ‘New Horizon College of Engineering'
• # lambda returns a function object
rev_upper = lambda string: string.upper()[::-1]
print(rev_upper(str1))
Condition Checking Using Python lambda
function
• Check_number = lambda num:"even" if a%2==0 else "odd"
Map function
• map() function returns a map object(which is an iterator) of the results
after applying the given function to each item of a given iterable (list,
tuple etc.)
• Syntax :
map(function, iterables)
• Parameter Values
• Function:Required. The function to execute for each item
• Iterable: Required. A sequence, collection or an iterator object. You can
send as many iterables as you like, just make sure the function has one
parameter for each iterable.
Example
def myfunc(a, b):
return a + b
x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon',
'pineapple'))
Filter Function
• The filter() method filters the given sequence with the help of a
function that tests each element in the sequence to be true or not.
• syntax:
filter(function, sequence)
• Parameters:
• function: function that tests if each element of a sequence true or not.
• sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or
containers of any iterators.
• Returns: returns an iterator that is already filtered.
Example:
• # function that filters vowels
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
• # sequence
sequence = [‘n', 'e', ‘w', ‘h', ‘o', ‘r', ‘i', 'z’, ‘o’,’n’]
# using filter function
filtered = filter(fun, sequence)
print('The filtered letters are:')
for s in filtered:
print(s)
Example
• # a list contains both even and odd numbers.
seq = [0, 1, 2, 3, 5, 8, 13]
# result contains odd numbers of the list
result = filter(lambda x: x % 2 != 0, seq)
print(list(result))
# result contains even numbers of the list
result = filter(lambda x: x % 2 == 0, seq)
print(list(result))
Example
• # Python Program to find numbers divisible by thirteen from a list using anonymous
function
# Take a list of numbers.
my_list = [12, 65, 54, 39, 102, 339, 221, 50, 70, ]
# use anonymous function to filter and comparing
# if divisible or not
result = list(filter(lambda x: (x % 13 == 0), my_list))
# printing the result
print(result)
reduce() in Python
• The reduce(fun,seq) function is used to apply a particular function passed in its
argument to all of the list elements mentioned in the sequence passed along.
• This function is defined in “functools” module.
# importing functools for reduce()
import functools
• Working :
• At first step, first two elements of sequence are picked and the result is obtained.
• Next step is to apply the same function to the previously attained result and the number just
succeeding the second element and the result is again stored.
• This process continues till no more elements are left in the container.
• The final returned result is returned and printed on console.
Example
• # python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [1, 3, 5, 6, 2]
# using reduce to compute sum of list
print("The sum of the list elements is : ", end="")
print(functools.reduce(lambda a, b: a+b, lis))
# using reduce to compute maximum element from list
print("The maximum element of the list is : ", end="")
print(functools.reduce(lambda a, b: a if a > b else b, lis))