Unit-II Notes PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

SCHOOL OF ENGINEERING & TECHNOLOGY

PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
Notes: Unit-II

Course Objective:
1. To understand the flow of programming.

Course Learning Outcomes:


1. To explain the control statements and functions with packages.

Control Structures in Python

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:

Sequence Construct- A sequence construct is a liner structure. It executes instructions one


after another in sequence. There is no mechanism for choosing alternate paths in instructions
flow. It executes one statement then automatically moves to next statement and so on.

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

if temperature > 35:


print("It's a hot day.")
elif temperature > 20:
print("It's a warm day.")
else:
print("It's a cold day.")

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

for item in sequence:


# Code block to execute for each item

Examples of For Loops

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.

2. Iterating Over a List

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

Explanation: The loop iterates over each item in the fruits list and prints it.

3. Iterating Over a String

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

ages = {"Alice": 25, "Bob": 30, "Charlie": 35}


for name, age in ages.items():
print(f"{name} is {age} years old")

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

Example of a While Loop

1. Simple Example

counter = 0
while counter < 5:
print("Counter is:", counter)
counter += 1

Explanation:

o The loop prints the value of counter and then increments it by 1.


o The loop stops when counter is no longer less than 5.

2. Using a Break Statement

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.

Loop Control Statements

• break: Exits the loop entirely.


• continue: Skips the rest of the code inside the loop for the current iteration and moves
to the next iteration.
• pass: Does nothing and is often used as a placeholder.

Examples of Loop Control Statements

1. Break Statement

for i in range(10):
if i == 5:
break
print(i)

Explanation: The loop stops entirely when i equals 5.

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)

Explanation: pass does nothing, so the loop continues normally.

While Loops with else

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:

Example 1: A Simple Function without Parameters

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.

Example 2: A Function with Parameters

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.

Example 3: A Function with a Return Value

def add(a, b):


"""Adds two numbers and returns the result."""
return a + b

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.

Example 4: Using Default Parameters

def greet(name, message="Hello"):


"""Greets a person with a custom or default message."""
print(f"{message}, {name}!")

greet("Bob") # Uses default message


greet("Alice", "Welcome") # Overrides default message

Explanation: Here, message has a default value of "Hello". If no second argument is


provided, the default is used; otherwise, the provided argument replaces the default.

Types of Function Parameters


Python supports several types of parameters to make functions more flexible:

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:

def greet(name, message):


print(f"{message}, {name}!")

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")

Arbitrary Arguments (*args)

• Allows passing a variable number of positional arguments to a function.


• *args collects additional arguments as a tuple.

def add_all(*numbers):
return sum(numbers)

print(add_all(1, 2, 3, 4)) # Output: 10

Arbitrary Keyword Arguments (**kwargs)

• Allows passing a variable number of keyword arguments to a function.


• **kwargs collects additional arguments as a dictionary.

def describe_person(**info):
for key, value in info.items():
print(f"{key}: {value}")

describe_person(name="Alice", age=30, job="Engineer")

Scope of Variables in Functions

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.

Benefits of Using Functions


• Reusability: Write a function once and reuse it multiple times.
• Modularity: Break down complex tasks into smaller, manageable units.
• Readability: Functions with descriptive names make code more readable.
• Maintainability: Functions make it easier to update and manage code.
• Debugging: Easier to isolate and test parts of code separately.

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

def add(a, b):


return a + b

def subtract(a, b):


return a - b

Importing Modules
Once you have a module, you can import it into other Python scripts using the import statement.

Examples of Importing Modules

1. Importing the Entire Module


PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
9
SCHOOL OF ENGINEERING & TECHNOLOGY

PCU/SOET/MCA/2024B/SemI/NamitaC/Notes/PythonP/PMC101/Unit2
import math_utils

print(math_utils.add(5, 3)) # Output: 8


print(math_utils.subtract(5, 3)) # Output: 2

2. Importing Specific Functions from a Module

from math_utils import add

print(add(5, 3)) # Output: 8

3. Using Aliases for Modules or Functions

import math_utils as mu

print(mu.add(5, 3)) # Output: 8

Standard Library Modules


Python comes with a rich standard library that provides pre-built modules for various tasks,
like file handling, regular expressions, math operations, and more.

Examples of Standard Library Modules:


• math: Provides mathematical functions.
• random: Used for generating random numbers.
• datetime: Used for date and time manipulation.

Example:

import math

print(math.sqrt(16)) # Output: 4.0

Advantages of Modules

• Code Organization: Modules separate code into files based on functionality.


• Reusability: Once written, modules can be reused across different programs.
• Namespace Management: Modules provide separate namespaces, reducing naming
conflicts.

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

To create a package, you need:

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.

Example Structure of a Package

Suppose you want to create a package called utilities with two modules: math_utils.py and
string_utils.py.

utilities/ # Package directory


__init__.py # Init file
math_utils.py # Module 1
string_utils.py # Module 2

Using Packages
Once you’ve set up a package, you can import its modules in other scripts.

from utilities import math_utils, string_utils

print(math_utils.add(3, 5)) # Calls function from math_utils

Advantages of Packages

• Hierarchical Organization: Packages enable a hierarchical structuring of modules,


making complex projects easier to navigate.
• Scalability: Packages make it easier to scale a project by organizing related modules
together.

Using External 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.

Installing and Using External Packages

1. Installing a Package with pip

pip install package_name

2. Using an External Package After installing, you can import and use the package as
needed.

Example: Using the requests package for making HTTP requests.

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

• NumPy: For numerical computations.


• Pandas: For data manipulation and analysis.
• Matplotlib: For data visualization.
• Flask: For web application development.
• Requests: For handling HTTP requests.

Advantages of External Packages

• Pre-built Solutions: Many packages provide ready-to-use solutions for common


tasks.
• Community Support: Many external packages are open-source and have large
communities for support.
• Efficiency: Using external libraries saves development time by leveraging existing
code.

*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

You might also like