Unit III Python
Unit III Python
LECTURE NOTES
BCA III Sem - BCAT-211,BCAP-211
(2023-2026)
DEPARTMENT OF COMPUTER SCIENCE- IITM
SYLLABUS-
In this course, the learners will be able to develop expertise related to the following: -
1. To understand Python programming fundamentals
2. To define the structure and components of a Python program.
3. To apply fundamental problem-solving techniques using Python
4. To design and program applications using Python.
UNIT–I
UNIT–II
Mutable and Immutable objects: List: creating, initializing, accessing, slicing, and
traversing List. List operations: length, concatenation, repetition, in, not in, max, min,
sum, all, any. List methods: append, extend, count, remove, index, pop,
insert, sort, reverse. Tuples: creating tuples, Tuple operations: length, concatenation,
repetition, membership, maximum, minimum, tuple
methods: count, index. Dictionary: creating, accessing values, adding, modifying and
deleting items in dictionary, Dictionary methods: len, str, clear, copy, get, update, copy.
Difference between list and dictionary
UNIT–III
UNIT–IV
TEXTBOOKS:
REFERENCE BOOKS:
RB1. Let Us Python 2Nd Ed: Python Is Future, Embrace It Fast (Second Edition):
YashvantKanetkar.
RB2. Programming Python, 4th Edition by Mark Lutz Released December 2010
Publisher(s): O'Reilly Media, Inc.
RB3. Python: The Complete Reference by Martin Brown.
Functions in Python:
In Python, functions are reusable code blocks that perform a specific task. They make your
code more organized, modular, and easier to understand. Here’s an overview of the concept of
functions in Python, including how to define and call them, as well as the different types of
functions:
Defining a Function:
To define a function in Python, use the `def` keyword, followed by the function name and
parentheses `()`, which may include parameters. The function body contains the code that
executes when the function is called.
def greet():
print("Hello, World!")
In this example:
Calling a Function:
Once a function is defined, you can call it by using its name followed by parentheses `()`.
This calls the `greet` function, and the `print` statement inside it gets executed.
Types of Functions:
There are mainly two categories of functions in Python:
1) Built-in Functions
● These are functions provided by Python itself, such as `print()`, `len()`, `sum()`,
`max()`, etc.
● They are readily available for use without needing to define them.
Example:
print(len("Python")) Output: 6
2) User-defined Functions
● These are functions that you define yourself to perform specific tasks. They are
created using the `def` keyword.
Example:
return a + b
result = add_numbers(5, 3)
print(result) Output: 8
With Parameters: You can define functions that accept parameters or arguments, making
them more flexible.
def greet(name):
print(f"Hello, {name}!")
Without Parameters: Functions can also be defined without parameters, as in the earlier
`greet` example.
Example:
def square(x):
return x * x
result = square(4)
print(result) Output: 16
Example:
def say_hello():
print("Hello!")
● These are small, one-line functions that don’t require the `def` keyword and are
defined using the `lambda` keyword.
● They can have any number of parameters but can only have one expression.
Example:
square = lambda x: x * x
print(square(5)) Output: 25
Modularity: Functions break down complex problems into smaller, manageable parts.
Ease of Maintenance: Changes can be made in one place (the function definition) rather than
multiple locations in the code.
Practice Question: Create a function called multiply that takes two arguments and
returns their product. Then, call the function with the numbers 4 and 5 and print the
result.
In programming, particularly in the context of functions, the terms formal arguments and actual
arguments (or parameters and arguments) refer to different aspects of function definition and
invocation. Here's a breakdown of each:
Formal Arguments (Parameters): These are the variables defined in the function signature or
definition. They act as placeholders for the values that will be passed to the function when it is
called.
Example:
return a + b
Actual Arguments (Arguments): These are the values or expressions you provide when
calling a function. These values are passed to the function and assigned to the formal
arguments.
Example:
Relationship:
● When you call a function, the actual arguments are passed to the formal arguments.
● In the above example, `3` is passed to `a` and `5` is passed to `b`, so inside the `add`
function, `a` is `3` and `b` is `5`.
Keyword Arguments: These are arguments passed to a function by explicitly naming them,
allowing for better readability and flexibility. When using keyword arguments, you specify which
formal parameter the value is for. They can be passed in any order.
Example:
print(f"{message}, {name}!")
Default Arguments: These allow you to assign a default value to a parameter in a function
definition. If an argument is not provided when the function is called, the default value is used.
Example:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
Scope and Lifetime: Scope refers to the region of a program where a variable is
accessible.
Local Scope: Variables declared inside a function or block. They can only be accessed
within that function.
Global Scope: Variables declared outside all functions. They can be accessed from
anywhere in the code.
Local variables exist as long as the function is executing. Once the function ends, they
are removed.
Global variables exist as long as the program runs.
Example:
x = 10 # Global variable
def my_function():
y = 5 # Local variable
print(x, y)
my_function()
print(x) # Works
Recursion: Recursion occurs when a function calls itself directly or indirectly. It’s
commonly used to solve problems that can be broken down into smaller, similar problems (like
calculating factorials, Fibonacci sequences, etc.). Recursive functions need a base case to
stop the recursion; otherwise, they will keep calling themselves and cause a stack overflow.
Example:
def factorial(n):
if n == 0: # Base case
return 1
else:
Here, `factorial(5)` calculates `5 * factorial(4)` and continues until it reaches the base case
`factorial(0)`.
Modules in Python:
● A module is a Python file (.py) containing Python code, such as functions, classes,
variables, or even runnable code.
● Using modules allows you to break down large programs into smaller, more
manageable, and reusable files.
● You can import these modules into other Python files to use their functions, classes, and
variables.
Types of Modules
● Built-in Modules: These are pre-installed with Python and include common modules
like math, os, sys, random, and many more. These modules provide various utilities and
functionalities that can be easily accessed.
Example:
import math
Example 2:
● User-defined Modules: These are modules created by users to organize their code.
Any Python file that you write can be considered a module.
Example:
# File: mymodule.py
def greet(name):
print(f"Hello, {name}!")
import mymodule
Importing Modules: You can use the import statement to bring in the functionality of another
module.
● By default, Python only loads a module once per session. If you make changes to a
module and want to reload it, you can use the importlib library.
Example:
python
import mymodule
reload(mymodule)
Packages in Python: Packages are introduced to organize Modules into Packages.
● A package is a collection of related modules stored in a directory. Packages make it
easier to organize complex applications.
● Each package is defined by a directory that contains an __init__.py file (which can be
empty).
● You can access modules from a package using dot notation.
Example:
from my_package import module1
module1.some_function()
● Any Python file can act as a module. Simply create a Python file with some functions or
variables and import it into another script.
Example:
# File: arithmetic.py
return a + b
return a - b
import arithmetic
Modules are an essential part of writing scalable, maintainable, and reusable code in Python.
They help you organize your code effectively and allow you to build larger applications more
efficient