0% found this document useful (0 votes)
5 views

Unit III Python

Uploaded by

guptalakshay2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit III Python

Uploaded by

guptalakshay2004
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Basics Of Python Programming

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

Basic Introduction: Origin, Need of Python Programming, Features, program


structure, identifiers, reserved words, escape sequences, IDLE-Python Interpreter
Python Programming Introduction: Variables and assignment statements, data types,
Operators: Assignment, Unary, Binary, Arithmetic, Relational, Logical, Bitwise Operator
and membership operator. Control Structures: if-conditional statements, if –else
condition, if-elif-else condition, nested if-elif-else condition, Iteration (for Loop and while
loop), Nested Loops, break and continue statement. Strings: Slicing, Membership, Built
in functions (count, find, capitalize, title, lower, upper and swap case, replace, join,
isspace (), isdigit(), split(), startswith(), endswith()).

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

Concept of Functions: Functions: Defining, Calling and Types of Functions,


Arguments and Return Values, Formal vs. Actual Arguments, Scope and Lifetime,
Keyword Arguments, Default Arguments, Recursion. Modules: importing Modules,
Math and Random Module, creating your own modules, and concept of Packages.

UNIT–IV

NumPy Library: introduction to NumPy, Creation of One-Dimensional Arrays,


Re-shaping of an Array, Element-wise Operations, Aggregate Operations, Array
indexing, Array Slicing, insert Row/Columns, Append Row/Columns, Array
Manipulation Operations.
Introduction to matplotlib: Bar Graphs , pie charts
File handling: Types of Files (Text file, Binary Files, CSV file), Creation, writing,
appending, Insertion, deletion, updating, modification of data into the files.

TEXTBOOKS:

TB1. Programming in Python 3: A Complete Introduction to the Python Language (2nd


Edition), Mark Summerfield.
TB2. Python Programming: A Modular Approach by TanejaSheetal, Kumar Naveen,
Eleventh Impression, Pearson
India Education Services Pvt. Ltd.
TB3. Agile tools for real world data: Python for Data Analysis by Wes McKinney,
O’Reilly

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.

Unit III - Introduction to Python Programming

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:

● `def`: Keyword to define a function.


● `greet`: The function name.
● `()`: Parentheses that can contain parameters.
● `print("Hello, World!")`: The function body.

Calling a Function:
Once a function is defined, you can call it by using its name followed by parentheses `()`.

greet() Output: Hello, World!

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

print(max([1, 2, 3])) Output: 3

2) User-defined Functions
● These are functions that you define yourself to perform specific tasks. They are
created using the `def` keyword.

Example:

def add_numbers(a, b):

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

greet("Alice") Output: Hello, Alice!

Without Parameters: Functions can also be defined without parameters, as in the earlier
`greet` example.

Different Types of User-defined Functions:


A) Function with Return Statement: Functions can return values using the `return` keyword,
which allows you to capture the result of the function call.

Example:

def square(x):

return x * x
result = square(4)

print(result) Output: 16

B) Function Without Return Statement: A function without a `return` statement returns


`None` by default.

Example:

def say_hello():

print("Hello!")

say_hello() Output: Hello!

C) Lambda Functions (Anonymous Functions)

● 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

Advantages and Benefits of Using Functions:


Code Reusability: Functions help reuse code by defining it once and calling it wherever
needed.

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.

Readability: Code becomes easier to read and understand with functions.

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:

def add(a, b): # 'a' and 'b' are formal arguments.

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:

result = add(3, 5) # '3' and '5' are actual arguments.

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:

def greet(name, message):

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

greet(message="Hello", name="Stacy") # Using keyword arguments.

Output: Hello, Stacy!

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

greet("Alice") # Uses default value for 'message'.

Output: Hello, Alice!

greet("Alice", "Good morning") # Overrides the default.

Output: Good morning, Alice!

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.

Lifetime refers to the duration for which a variable exists in memory.

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

# print(y) # Error: 'y' is not defined outside the function.

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:

return n * factorial(n - 1) # Recursive call

print(factorial(5)) # Output: 120

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

print(math.sqrt(25)) # Output: 5.0

Example 2:

import random # Generate a random integer between 1 and 10 (inclusive)

random_integer = random.randint(1, 10)

● 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}!")

You can then use this module in another script:

import mymodule

mymodule.greet("Welcome to IITM") # Output: Welcome to IITM

Importing Modules: You can use the import statement to bring in the functionality of another
module.

Example: Import Specific Functions/Classes:

from math import sqrt, pi

print(sqrt(16)) # Output: 4.0

print(pi) # Output: 3.141592653589793

Example: Import with Aliases:


import numpy as np

print(np.array([1, 2, 3])) # Uses 'np' as a shortcut for 'numpy'.

Re-importing Modules (reload)

● 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

from importlib import reload

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

Some Commonly Used Built-in Modules:

● os: For interacting with the operating system.


● sys: For accessing Python runtime environment.
● math: For mathematical functions.
● random: For generating random numbers.
● datetime: For working with dates and times.
● json: For working with JSON data.

Creating and Using Your Own Modules:

● 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

def add(a, b):

return a + b

def subtract(a, b):

return a - b

Use it in another script:

import arithmetic

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

Benefits of Using Modules:


● Code Reusability: Write a function or class once and use it in multiple programs.
● Code Organization: Break down large codebases into smaller, more manageable files.
● Collaboration: Share modules with others, making teamwork easier.
● Namespace Management: Modules help keep functions and variables in separate
namespaces, reducing naming conflicts.

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

You might also like