0% found this document useful (0 votes)
11 views16 pages

Python Control Flow and Functions Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

Python Control Flow and Functions Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 [Link]():

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}

Common questions

Powered by AI

Recursive functions are highly effective for problems that can be divided into smaller subproblems of the same kind. By calling themselves, they simplify complex problems like calculating factorials or generating Fibonacci numbers by addressing each smaller piece—also known as divide and conquer. They continue solving until they reach a base case, which stops further recursion. This method breaks down tasks into more manageable steps, enabling clearer logic and reducing how the solution addresses both large-scale issues and repetitive structures .

The pass statement serves as a placeholder in Python scripting, which is particularly useful during early development phases when the code structure is being outlined but the actual logic or functionality has yet to be implemented. This helps developers maintain proper syntax and focus on code organization or flow without executing incomplete code. It allows for the iterative build-up of a program by providing scaffolding to be filled in later with substantive code, enhancing debugging and future expansion .

Positional arguments require values to be passed in the order of the function's parameters, which can limit flexibility and lead to errors if arguments are mistakenly ordered . Conversely, keyword arguments allow specifying values by explicitly naming parameters, promoting better readability and flexibility, as argument order becomes irrelevant. This approach makes code self-descriptive, enhances clarity, and reduces the likelihood of errors from mismatched or missing arguments, particularly in functions with many parameters .

Functions in Python promote code modularity and maintainability by encapsulating code blocks designed to perform specific tasks, allowing for reusable code. This structural separation fosters better organization by isolating code segments for individual operations, reducing redundancy. By enabling parameterization through arguments, developers can tailor function applicability across different scenarios without rewriting base logic. Function definitions provide clear and concise documentation through docstrings, which improve readability and ease troubleshooting in large codebases .

Arbitrary argument types such as `*args` and `**kwargs` significantly enhance Python function capabilities by allowing functions to accept a variable number of arguments. `*args` collects positional arguments into a tuple, enabling functions to handle unspecified numbers of inputs, which suits operations like aggregations or concatenations without predefined limits. `**kwargs` collects keyword arguments into a dictionary, allowing for flexible handling of named parameters and setting dynamic features in functions. These capabilities provide robust solutions for writing functions that adapt to various data inputs or user preferences dynamically .

The syntax and structure of a function definition in Python, starting with 'def', followed by the function name and parameters, create a clear entry point for execution . Indentation signals the function's body, encapsulating the operational logic neatly. This structure, combined with optional docstrings, supports execution by clearly defining processes and enhances readability with documented purpose and parameter explanation. Parameters within parentheses allow flexible input handling, and return statements explicitly outline output, making the function easy to understand and integrate into larger programs .

The break statement is significant in loops because it allows for the premature termination of the loop when a specified condition is met. This alters the loop's behavior by interrupting the natural consecutive execution of iterations and transferring control to the statement that follows the loop, effectively stopping any further execution within the loop .

The if statement executes a block of code only if the specified condition evaluates to True; if the condition is False, the block is skipped and no alternative block is executed . Conversely, the if-else statement provides two distinct paths: one block executes if the condition is True; otherwise, a different 'else' block executes when the condition is False. This ensures that one of the two code blocks always runs .

The return statement plays a crucial role in Python functions by facilitating output back to the caller, allowing processed data to be utilized elsewhere in the program. It serves as a pathway for the function to pass results or computed values, thus enabling logical chaining of operations. By employing tuples, lists, or dictionaries, return statements can transfer multiple pieces of data simultaneously, improving data transfer efficiency. This functionality enhances modularity by avoiding global variable reliance and promoting the encapsulation of specific operations within functions .

Nested loops enhance program functionality by allowing operations across multi-dimensional data or performing parallel tasks that require examining multiple levels of data simultaneously. They repeat a set of instructions over elements that also demand repeated operations within themselves, such as iterating over rows and columns in a matrix. Common use cases include generating combinations or permutations, calculating the product of matrices, and processing multidimensional arrays or grids .

You might also like