0% found this document useful (0 votes)
21 views12 pages

Python Programming Basics for BCA Students

Uploaded by

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

Python Programming Basics for BCA Students

Uploaded by

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

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([Link](25)) # Output: 5.0

Example 2:

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

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

def greet(name):

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

You can then use this module in another script:

import mymodule

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

def add(a, b):

return a + b

def subtract(a, b):

return a - b

Use it in another script:

import arithmetic

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

Common questions

Powered by AI

Functions in Python offer significant advantages such as code reusability, where code can be defined once and used across various parts of a program, making development more efficient. They also promote modularity, allowing complex problems to be broken down into smaller, manageable parts, which enhances code readability and maintainability. Additionally, functions facilitate ease of maintenance, as any changes need to be made only in the function definition, not in every location where the functionality is used. Lastly, they improve code readability, making the program easier to understand and navigate .

Keyword arguments in Python enhance function calls by allowing you to explicitly state which arguments correspond to which parameters in a function. This leads to more readable and flexible code, as the order of arguments does not need to match that in the function definition. For example, consider the function `def greet(name, message)`, which can be called using `greet(name="Stacy", message="Hello")`, specifying the arguments directly by name for clarity and reducing errors in argument placement .

In Python, mutable objects can be changed after they are created, while immutable objects cannot. Lists in Python are mutable; you can modify their content, add, or remove elements after creation. For example, you can append an item to a list with `myList.append(item)`. On the other hand, tuples are immutable once created, meaning you cannot alter their elements, demonstrated by `tuple1 = (1, 2, 3)` where trying to change `tuple1[0]` would raise an error .

The `reload` function in Python, found within the `importlib` module, allows for the re-importation of a module that has already been imported in a session. It is practically used when you modify a module's code during runtime and need those changes to reflect immediately without restarting the session. By default, Python caches modules and only loads them once per session, so `reload` becomes essential when dynamic modifications are involved, ensuring that updated functionality is used in current operations .

Recursion in Python occurs when a function calls itself directly or indirectly, typically to solve problems that can be divided into smaller, similar subproblems. Recursion requires a base case to prevent infinite calls and stack overflow. An excellent example is the factorial function: `def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)`. In this example, `factorial(5)` calculates `5 * factorial(4)` recursively until reaching the base case `factorial(0)`, which returns 1 .

Lists and dictionaries in Python serve different purposes. Lists are ordered collections of items accessible by their index, useful for maintaining a sequence of elements and performing operations like slicing. Dictionaries, on the other hand, are unordered collections of key-value pairs, allowing for fast lookups and modifications by reference to keys. Typical use cases for lists include maintaining sequences, while dictionaries excel in scenarios where data items are associated with unique identifiers, providing efficient data retrieval and modification .

In Python, the `append` method adds a single element to the end of a list, modifying it in place. The `extend` method, on the other hand, adds each element of an iterable (like another list) to the end of the list, effectively extending it. The `insert` method allows you to add an element at a specified position, shifting the current elements to make space. Each method alters the list structure to accommodate new data but in distinct manners suited to various scenarios .

Modules in Python play a critical role in code organization by allowing developers to break down large programs into smaller, manageable segments. This enhances code reusability since you can write a function or class once and employ it in multiple programs. Modules also aid in maintaining operation by keeping functions and variables within their namespaces, reducing naming conflicts. Furthermore, they facilitate collaboration by enabling developers to share modules easily with others, making teamwork more effective. Lastly, importing modules makes applications scalable and maintainable, supporting larger codebases efficiently .

Packages in Python are collections of related modules organized in directories. They allow for a hierarchical structure, making large applications more manageable and modular. To create a package, a directory needs to contain an `__init__.py` file, which can be empty but signifies to Python that the directory should be treated as a package. Modules within the package can be imported using dot notation, such as `from my_package import module1`, providing organizational benefits and ease of access to the package's functionality .

The `__init__.py` file in a Python package serves as an indicator that the directory is to be treated as a package by Python. It can be used to execute package initialization code or set certain attributes for the package. Although it used to be mandatory, as of Python 3.3, the requirement for an `__init__.py` file is no longer strict for the directory to be recognized as a package. However, including it is good practice, especially if package initialization logic is needed .

You might also like