Unit-II Notes PDF
Unit-II Notes PDF
Unit-II Notes PDF
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Notes: Unit-II
Course Objective:
1. To understand the flow of programming.
Control structures are essential programming constructs that allow developers to control the
flow of execution within a program. It is used to develop program logic for solution of a
problem.
There are 3 types of control structures:
Selection Construct- A selection structure is known as decision statement. It has the decision
making capabilities on the basis of given conditions. It allows alternative paths for the
instructions of a program on the basis of given conditions. Simple if, if else, if else if, nested if
else statements are common selection statements.
Iteration Construct- It allow a program to execute a block of code repeatedly. for loop, while
loop are iteration constructs in Python.
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
1
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
1. Conditional Blocks
Conditional blocks control the flow of the program by executing specific blocks of code based
on conditions. In Python, conditional blocks are created using if, elif, and else statements.
Syntax
if condition:
# Code block executed if the condition is True
elif another_condition:
# Code block executed if the first condition is False
# and another_condition is True
else:
# Code block executed if all previous conditions are False
Explanation of Statements
• if Statement: Checks a condition. If the condition evaluates to True, the code inside
the if block is executed.
• elif Statement: Stands for "else if". It checks another condition if the previous if (or
elif) was False. There can be multiple elif statements following an if.
• else Statement: The code in the else block runs if all previous conditions were False.
An else statement is optional and appears at the end of the conditional chain.
Example
temperature = 30
Explanation:
• Here, the if checks if the temperature is above 35. If true, it prints "It's a hot day."
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
2
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
• If not, the elif checks if the temperature is above 20. If true, it prints "It's a warm day."
• If both are false, the else block prints "It's a cold day."
Nested Conditionals
Conditional statements can be nested, allowing for more complex decision-making.
score = 85
if score >= 90:
print("Grade: A")
else:
if score >= 80:
print("Grade: B")
else:
print("Grade: C")
2. Looping Constructs
Loops allow a program to execute a block of code repeatedly. Python provides two main
types of loops: for loops and while loops.
For Loops
A for loop iterates over a sequence (such as a list, string, or range). It executes the block of
code inside the loop for each item in the sequence.
Syntax
1. Using a Range
for i in range(5):
print(i)
Explanation: range(5) generates numbers from 0 to 4. The loop prints each number.
Explanation: The loop iterates over each item in the fruits list and prints it.
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
3
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
for letter in "Python":
print(letter)
Explanation: The loop iterates over each character in the string "Python" and prints
it.
4. Using Dictionaries
Explanation: The loop iterates over key-value pairs in a dictionary using .items().
While Loops
A while loop repeatedly executes a block of code as long as a specified condition remains
True.
Syntax
while condition:
# Code block to execute as long as condition is True
1. Simple Example
counter = 0
while counter < 5:
print("Counter is:", counter)
counter += 1
Explanation:
counter = 0
while True:
print("Counter is:", counter)
counter += 1
if counter == 5:
break
Explanation:
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
4
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
o The while True loop creates an infinite loop.
o The break statement is used to exit the loop when counter reaches 5.
1. Break Statement
for i in range(10):
if i == 5:
break
print(i)
2. Continue Statement
for i in range(10):
if i % 2 == 0:
continue
print(i)
Explanation: The loop skips printing even numbers and only prints odd numbers.
3. Pass Statement
for i in range(5):
if i == 3:
pass # Placeholder for future code
print(i)
An else statement can also be used with loops. In a while loop, the else block executes when
the loop condition becomes False.
count = 0
while count < 3:
print("Count is:", count)
count += 1
else:
print("Loop completed.")
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
5
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Explanation: The else block executes after the loop completes naturally.
Conditional blocks (if, elif, else) are used to execute code based on specific conditions.
For loops are used to iterate over sequences like lists, strings, and ranges.
While loops run as long as a condition is True, making them useful for indefinite iteration.
Loop control statements (break, continue, pass) help manage loop behavior by exiting,
skipping, or passing through iterations.
Functions in Python
Functions are a core component of Python programming that allow you to encapsulate code
into reusable blocks.
Functions help you organize your code, avoid repetition, and improve readability by breaking
down complex tasks into smaller, manageable units.
What is a Function?
A function is a named block of code that performs a specific task. Functions take input
(parameters), process the input, and often return an output. They allow code to be reused
throughout a program, reducing redundancy and making the code modular.
Defining a Function
In Python, functions are defined using the def keyword, followed by the function name,
parentheses (which may include parameters), and a colon. The body of the function is indented
below the definition line.
Syntax
def function_name(parameters):
# Code block to execute
return result # Optional return statement
• Function Name: The name should be descriptive and follow the snake_case naming
convention.
• Parameters: Variables listed inside the parentheses that the function takes as input.
Parameters are optional.
• Return Statement: The return statement is optional and is used to send a result back
to the caller.
Examples of Functions:
def greet():
"""Prints a greeting message."""
print("Hello, welcome to Python programming!")
greet()
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
6
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Explanation: This function, greet, does not take any parameters and simply prints a greeting
message. The """ syntax indicates a docstring, which documents what the function does.
def greet(name):
"""Greets a person by name."""
print(f"Hello, {name}!")
greet("Alice")
Explanation: This version of greet takes one parameter, name, and prints a customized
greeting. When calling the function, you provide an argument ("Alice" in this case) that fills
the name parameter.
result = add(5, 3)
print("Sum:", result)
Explanation: This function, add, takes two parameters, a and b, adds them, and returns the
result. The result is then printed outside the function.
Positional Parameters
• These parameters are assigned values based on their position in the function call.
• For example, in add(5, 3), 5 and 3 are positional arguments for a and b, respectively.
Keyword Parameters
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
7
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
• Keyword arguments specify values by parameter name, which makes the function call
more readable.
• Example:
greet(name="Alice", message="Welcome")
Default Parameters
• Assign default values to parameters, which are used if the caller doesn’t provide an
argument.
• Example: def greet(name, message="Hello")
def add_all(*numbers):
return sum(numbers)
def describe_person(**info):
for key, value in info.items():
print(f"{key}: {value}")
Variables defined inside a function have a local scope and are not accessible outside the
function. Global variables, on the other hand, are accessible throughout the script.
Example
def my_function():
x = 10 # Local variable
print(x)
my_function()
print(x) # This will cause an error because x is not defined outside the function
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
8
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Global Variables
To access a global variable inside a function, use the global keyword.
x=5
def modify_global():
global x
x = 10
modify_global()
print(x) # Output: 10
Higher-Order Functions
A higher-order function is a function that takes another function as a parameter, or returns a
function as a result. Functions like map, filter, and reduce are higher-order functions.
Modules in Python
Modules are files containing Python code (typically functions, classes, or variables) that can
be imported and used in other scripts. Modules enable better organization and reuse of code.
Creating a Module
To create a module, save your Python code in a .py file. For example, let's create a file called
math_utils.py with the following content:
# math_utils.py
Importing Modules
Once you have a module, you can import it into other Python scripts using the import statement.
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
import math_utils
import math_utils as mu
Example:
import math
Advantages of Modules
Packages in Python
Packages are a way of structuring Python’s module by using “dotted module names.” A
package is essentially a directory that contains multiple modules and a special __init__.py file,
which indicates that the directory is a Python package.
Creating a Package
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
10
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
1. A directory with a name (the package name).
2. Modules (Python files) within this directory.
3. An __init__.py file inside the directory. The __init__.py file can be empty or contain
initialization code for the package.
Suppose you want to create a package called utilities with two modules: math_utils.py and
string_utils.py.
Using Packages
Once you’ve set up a package, you can import its modules in other scripts.
Advantages of Packages
External packages are third-party libraries that are not included in Python's standard library.
These packages can be installed using package managers like pip.
2. Using an External Package After installing, you can import and use the package as
needed.
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
11
SCHOOL OF ENGINEERING & TECHNOLOGY
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Examples of Popular External Packages
*Please refer to the class/lecture notes, examples, and PPT slides for
the complete notes. Detailed slides on Lambda functions have already
been shared, so Lambda functions have not been included in the
notes above.
PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
12