Unit II:Flow Control: Decision Making – Loops – Nested Loops –
Types of Loops. Functions: Function Definition – Function Calling –
Function Arguments – Recursive Functions – Function with more
than one return value.
Decision making statement
decision making statement if, if else , if elif else, Nested if statement
definition with example and syntax
1. If Statement
The if statement is the most basic decision-making statement. It
executes block of code only if the specified condition evaluates to True.
Syntax
if condition:
# code block to execute if condition is True
Example
a = 10
if a > 5:
print("a is greater than 5")
Output:
a is greater than 5
2. If-Else Statement
The if-else statement executes one block of code if the condition
is True, otherwise it executes the else block.
Syntax
if condition:
# code when True
else:
# code when False
Example
a = 10
if a > 20:
print("a is greater than 20")
else:
print("a is 20 or less")
Output:
a is 20 or less
3. If-Elif-Else Statement (Chained Conditionals)
The if-elif-else statement checks multiple conditions sequentially. The first
True condition’s block executes, or else block if none match.
Syntax
if condition1:
# code if condition1 True
elif condition2:
# code if condition2 True
else:
# code if all above False
Example
number = -5
if number > 0:
print("Positive number")
elif number == 0:
print("Zero")
else:
print("Negative number")
Output:
Negative number
4. Nested If Statement
A nested if statement is an if statement inside another if
statement, allowing checking multiple conditions in a hierarchical manner.
Syntax
if condition1:
if condition2:
# code if both condition1 and condition2 True
else:
# code if condition1 True but condition2 False
else:
# code if condition1 False
Example
var = 100
if var == 100:
print("The number is 100")
if var % 2 == 0:
print("The number is even")
else:
print("The number is odd")
else:
print("The number is not 100")
Output:
The number is 100
The number is even
Loops
1. For Loop
A for loop in Python is used to iterate over a sequence (like a list,
tuple, string, or range) and executes a block of code for each element in
the sequence.
Syntax
for variable in sequence:
# code block to execute for each element
Example
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. While Loop
A while loop runs a block of code repeatedly as long as a
specified condition evaluates to True.
Syntax
while condition:
# code block to execute while condition is True
Example
count = 1
while count <= 5:
print(count)
count += 1
Output:
3. Nested Loops
A nested loop is a loop inside another loop. The inner loop is
executed completely every time the outer loop runs once.
Syntax
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# code block to execute nested
Example
for i in range(1, 4):
for j in range(1, 4):
print(f'i={i}, j={j}')
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
Control Statements
1. Break Statement
The break statement terminates the loop prematurely when a
specified condition is met and transfers control to the statement
immediately following the loop.
Syntax
for variable in sequence:
if condition:
break
# other code
Example
for i in range(10):
if i == 5:
break
print(i)
Output:
2. Continue Statement
The continue statement skips the current iteration of the loop
and proceeds to the next iteration, effectively ignoring the remaining code
in the loop body for that iteration.
Syntax
For variable in sequence:
if condition:
continue
# other code
Example
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output:
3. Pass Statement
The pass statement is a null operation; it does nothing when
executed. It is commonly used as a placeholder in code blocks where
syntax requires a statement but no action is needed or planned yet.
Syntax
for variable in sequence:
if condition:
pass
else:
# other code
Example
for i in range(5):
if i == 3:
pass # placeholder for future code
print(i)
Output:
Function
A function in Python is a reusable block of code designed to
perform a specific task. Functions help organize code, make it modular,
and improve readability and maintainability. A function runs only when it is
called.
Syntax
Def function_name(parameters):
“””Docstring (optional): Describe the function.”””
# function body (code block)
Return value # optional return statement
- `def`: Keyword to define a function
- `function_name`: The name of the function (should follow Python
naming rules)
- `parameters`: Optional inputs to the function inside parentheses,
comma-separated
- The function body is indented and contains the code executed when the
function is called
- `return`: Optional statement to send back a result from the function (if
needed)
Examples
1. Basic Function Without Parameters
Def greet():
Print(“Hello, World!”)
Greet()
Output:
Hello, World!
2. Function With Parameters
Def greet(name):
Print(“Hello, “ + name + “!”)
Greet(“Alice”)
Greet(“Bob”)
Output:
Hello, Alice!
Hello, Bob!
3. Function With Return Value
Def add(a, b):
Return a + b
Result = add(5, 3)
Print(result)
Output:
4. Function With Docstring
Def square(num):
“””Returns the square of a number.”””
Return num * num
Print(square(4))
Output:
16
Function calling
Function calling in Python is the process of executing a function that
has been defined earlier. When a function is called, the control transfers to
the function, its code block is executed, and then control returns to the
point from where the function was called.
Syntax
function_name(arguments)
- `function_name`: The name of the function to call.
- `arguments`: Optional values passed to the function parameters inside
parentheses.
Examples
1. Calling Function Without Arguments
def greet():
print("Hello, World!")
greet() # Calling the function
Output:
Hello, World!
2. Calling Function With Arguments
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Passing argument during call
Output:
Hello, Alice!
3. Calling Function and Using Return Value
def add(a, b):
return a + b
result = add(5, 3) # Function call with arguments
print(result)
Output:
4. Calling One Function From Another
def first():
print("First function called")
second()
def second():
print("Second function called")
first() # Calls first(), which calls second()
Output:
First function called
Second function called
Function Arguments
Python functions can accept different types of arguments to
provide flexibility in passing values. Here are the main types with
examples:
1. Positional Arguments
Arguments passed in the correct positional order. The number of
arguments must match the parameters.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25)
Output:
Hello Alice, you are 25 years old.
2. Default Arguments
Arguments that have a default value if not provided during the
function call.
Example:
def greet(name, age=18):
print(f"Hello {name}, you are {age} years old.")
greet("Bob") # Uses default age=18
greet("Charlie", 30) # Overrides default
Output:
Hello Bob, you are 18 years old.
Hello Charlie, you are 30 years old.
3. Keyword Arguments
Arguments passed by explicitly specifying parameter names,
allowing argument order to vary.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=22, name="David")
Output:
Hello David, you are 22 years old.
4. Arbitrary Positional Arguments (`*args`)
Allows passing a variable number of positional arguments as a
tuple.
Example:
def add(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add(1, 2))
print(add(4, 5, 6))
Output:
15
5. Arbitrary Keyword Arguments (`**kwargs`)
Allows passing a variable number of keyword arguments as a
dictionary.
Example:
def person_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
person_info(name="Eva", age=29, city="London")
Output:
name: Eva
age: 29
city: London
Recursive Functions
A recursive function is a function that calls itself directly or
indirectly in order to solve a problem by breaking it down into simpler or
smaller subproblems. It continues to call itself until it reaches a **base
case** which stops the recursion.
Syntax
def recursive_function(parameters):
if base_case_condition:
return base_case_value
else:
return recursive_function(modified_parameters)
- The base case is the exit condition that prevents infinite recursion.
- The recursive case is where the function calls itself with modified
arguments.
Examples
1. Factorial Using Recursion
Calculates factorial of a positive integer $$ n $$.
def factorial(n):
if n == 0:
return 1 # Base case
else:
return n * factorial(n-1) # Recursive call
print(factorial(5))
Output:
120
2. Fibonacci Sequence Using Recursion
Calculates the $$ n^{th} $$ Fibonacci number.
def fibonacci(n):
if n == 0:
return 0 # Base case 1
elif n == 1:
return 1 # Base case 2
else:
return fibonacci(n-1) + fibonacci(n-2) # Recursive calls
print(fibonacci(10))
Output:
55
Function with More Than One Return Value in Python:
A Python function can return multiple values simultaneously by
separating them with commas. Internally, Python packs these values into
a tuple and returns it. This feature allows more than one piece of data to
be returned and used by the caller function.
Syntax
def function_name(parameters):
# code
return value1, value2, ..., valueN
When calling, multiple return values can be unpacked into individual
variables like:
val1, val2, ..., valN = function_name(arguments)
Examples
1. Returning Multiple Values as a Tuple
def multiple_returns():
return "Sum", 15
operation, total = multiple_returns()
print(operation)
print(total)
Output:
Sum
15
2. Returning Multiple Values Using List
def multiple_returns():
return ["Sum", 15]
values = multiple_returns()
print(values)
Output:
['Sum', 15]
3. Returning Multiple Values Using Dictionary
def multiple_returns():
return {"operation": "Sum", "total": 15}
values = multiple_returns()
print(values)
Output:
{'operation': 'Sum', 'total': 15}
4. Example: Return Quotient and Remainder
def div_with_remainder(num, div):
quotient = num // div
remainder = num % div
return quotient, remainder
q, r = div_with_remainder(17, 3)
print("Quotient:", q)
print("Remainder:", r)
Output:
Quotient: 5
Remainder: 2
Multiple return values improve a function’s versatility by enabling it to
output related pieces of data in a single call, using tuples, lists,
dictionaries, or objects .A Python function can return more than one value
at a time by separating the return values with commas. These values are
returned as a tuple, which can be unpacked into separate variables for
use.
Syntax
def function_name(parameters):
# computation
return value1, value2, ..., valueN
Examples
1. Returning multiple values as tuple
def multiple_returns():
return "Sum", 15
operation, total = multiple_returns()
print(operation) # Output: Sum
print(total) # Output: 15
2. Returning quotient and remainder
def div_with_remainder(num, div):
quotient = num // div
remainder = num % div
return quotient, remainder
q, r = div_with_remainder(17, 3)
print("Quotient:", q) # Output: Quotient: 5
print("Remainder:", r) # Output: Remainder: 2
3. Returning multiple values as dictionary
def func():
return {"operation": "Sum", "total": 15}
result = func()
print(result) # Output: {'operation': 'Sum', 'total': 15}