Python Inforamtion
Python Inforamtion
Unit – I
Introduction to Python Programming
Introduction to Python: Working with python, Variables, expressions, and statements,
accepting user input. Conditional execution. Nested conditionals, Iteration, Function Basics
Built-in Functions. Recursion, Scope Global, Local variables. Modules: Creating and importing
modules importing all or specific classes from module.
Introduction:
Python is a high-level, interpreted programming language known for its simplicity and
readability.
Python has become the most popular programming languages particularly for tasks like web
development, data analysis, artificial intelligence, scientific computing, and automation.
Features of pythons:
Readability and Simplicity: Python's syntax are easier for programmers to understand and write
code, reducing errors and improving maintainability.
Ease of Use: Compared to other languages, Python requires less code. This frees programmers
from writing repetitive code and allows them to focus on the core logic of their program.
Interpreted Language: An interpreter executes the code line by line, making development faster
and debugging easier.
Cross-Platform Compatibility: Python code can run on various operating systems like
Windows, macOS, and Linux without modification.
Dynamic Typing: Python variables don't have a predefined data type. The type is associated
with the value assigned to the variable at runtime.
Extensible: Python allows for easy integration with other languages like C and C++.
Strong Standard Library: Python comes with a comprehensive standard library that provides
modules and functions for a wide range of tasks, such as file I/O, networking, and data
manipulation.
Applications of Python:
Web Development: Python is widely used for building dynamic web applications.
Frameworks like Django and Flask provide developers with powerful tools for rapid
development, scalability, and security.
1|Page
Python Programming
Data Science and Machine Learning: Python has become the de facto language for data
science and machine learning due to its extensive libraries such as NumPy, pandas, etc. These
libraries facilitate data manipulation, analysis, visualization, and implementation of machine
learning algorithms.
Automation and Scripting: Python's simplicity and readability make it ideal for automating
repetitive tasks and writing scripts. It is commonly used for tasks such as system
administration, file manipulation, and batch processing.
Game Development: Python is increasingly being used in game development, both for indie
games and large-scale productions. Libraries like Pygame provide developers with tools for
building 2D games, while engines like Unity and Unreal Engine offer support for scripting in
Python.
Desktop GUI Applications: Python can be used to create desktop graphical user interface
(GUI) applications using libraries like Tkinter, PyQt, and wxPython. These libraries allow
developers to build cross-platform GUI applications with ease.
Python Versions
Python has undergone several major releases since its inception. Some of the notable versions
include:
Python 1.x: The initial versions of Python, including
1.0 and 1.6, introduced fundamental features of the language such as the core syntax and
basic data structures. These versions are no longer in active use.
Python 2.x: Python 2 was a major release series that introduced significant improvements
and new features. The most widely used versions in this series were Python 2.7, which
became the stable version for many
years. However, Python 2 reached its end-of-life on January 1, 2020, and is no longer maintained
or supported.
Python 3.x: Python 3 is the current and actively developed version of the language. Notable
versions in the Python 3 series include Python 3.0, Python 3.6,
Python 3.7, Python 3.8, Python 3.9, and Python 3.10 (the latest stable release as of my last
update). Python 3 is the recommended version for all new development.
Installation of Python
1. Download Python Executable Installer
On the web browser, in the official site of python ([Link]), move to the Download
for Windows section.
2|Page
Python Programming
2. Run Executable Installer
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
New.
Basics of Pythons
1. Python Identifiers
An identifier in Python is a name used for identifying a variable, class, function, object, module.
Python language does not allow punctuation characters within an identifier name for example: @,
$, and %.
3|Page
Python Programming
No identifiers can begin with a number, and no symbols other than the underscore.
2. Python Keywords
Keywords in python are the reserved words.
These words cannot be used as a variable name, function name, or any other identifier name.
Statements:
Statements are complete instructions that tell the Python interpreter to perform an action. They
don't
necessarily return a value.
Statements can be used for various tasks like:
Assigning values to variables (x = 5)
Printing output to the console (print("Hello, world!"))
Creating control flow using if, for, and while statements
Defining functions (def my_function():)
Importing modules (import math)
Expressions:
Expressions are combinations of values, variables, operators, and function calls that evaluate
to a single result.
This result can be a number, a string, a Boolean value, or even another data structure.
Expressions are often used within statements, but they don't perform actions on their own.
4|Page
Python Programming
4. Variables in Python
o Variables are containers for storing a value.
o Python is dynamically typed, it means that there is no requirement of pre-declaration of a variable
or its type.
o The type (and value) are initialized on the assignment. Assignments are performed using an equal
sign (=).
o Following example depicts how to declare variables in python:
>>> count = 0 name = 'Ram'
count = count + 1
o A variable is created the moment you first assign a value to it.
o Variables do not need to be declared with any particular type and can even change type after
they have been set.
x=4 # x is of type int
x= "Tally" #x is now of type str
o String variables in Python can be declared either by using single or double quotes.
Operators in Python
Operators in Python are symbols that perform operations on variables and values.
5|Page
Python Programming
1. Arithmetic Operators
2. Comparison Operators:
Comparison operators compare two values and return a Boolean result (True or False).
3. Assignment Operators:
6|Page
Python Programming
4. Logical Operators:
Bitwise Operators:
7|Page
Python Programming
5. Membership Operators:
o Membership operators test for membership in sequences like lists, tuples, and strings.
6. Identity Operators:
o While operator association defines the direction in which operators of the same precedence are
evaluated.
Precedence:
o Operator precedence determines the order in which operators are evaluated in an expression.
o Operators with higher precedence are evaluated before operators with lower precedence.
8|Page
Python Programming
o For example, multiplication (*) has higher precedence than addition (+), so 3 + 5 * 2 is evaluated
as 3 + (5 *
2), resulting in 13.
o Parentheses can be used to override precedence and explicitly specify the order of evaluation.
Association:
o Operator association determines the direction in which operators of the same precedence are
evaluated.
o Most operators in Python have left-to-right association, meaning they are evaluated from left to
right.
Datatypes in Python
In Python, data types represent the type or category of data that a variable or object can
hold.
Python is a dynamically-typed language, meaning that variables do not have fixed types.
Instead, the type of a variable is determined at runtime based on the value assigned to it.
1. Numeric Types:
o int: Integers represent whole numbers without any decimal point. Example: x = 10.
o float: Floats represent real numbers with a decimal point. Example: y = 3.14.
9|Page
Python Programming
o complex: Complex numbers consist of a real part and an imaginary part represented by j.
Example: z
= 3 + 2j.
2. Boolean Type:
o bool: Booleans represent the truth values True and False. Example: is_python_fun = True.
3. Dictionary:
o Keys must be unique and immutable (often strings or numbers), while values can be of any
data type
4. Set:
5. Sequence Types:
o string: Strings represent sequences of characters enclosed in single (') or double (") quotes.
o list: Lists represent ordered collections of items that can be of different data types.
o tuple: Tuples are similar to lists but are immutable (cannot be modified after creation).
6. None Type:
Indentation in Python
o Indentation is a unique and essential aspect of Python's syntax.
o Unlike many other programming languages that use curly braces { } to define code blocks, Python relies
on indentation to structure your code.
Indentation Scope: Statements with the same indentation level belong to the same block of code and
are executed together.
New Block, New Indentation: To create a new block of code (like within an if statement or
loop), you must indent the statements further to the right.
Consistent Indentation: It's crucial to maintain consistent indentation throughout your code.
Mixing spaces and tabs or using inconsistent indentation levels will lead to errors.
o Python is dynamically typed, meaning variables don't have a fixed data type assigned at declaration.
o When performing operations or assigning values that involve different data types, Python sometimes
automatically converts the data types to ensure compatibility. This implicit conversion happens
behind the scenes.
o In some cases, you might want to explicitly control the data type conversion.
Python Libraries
o Python libraries are collections of pre-written code modules that provide functionalities for various
tasks.
o They extend the capabilities of the Python language and allow you to perform complex operations
11 | P a g
e
Python Programming
without writing everything from scratch.
Importing Libraries
Use the import statement followed by the library name to import all functionalities from the library.
Example:
You can import specific functions or classes from a library using the from ... import syntax.
Example:
Example
1. Conditional Statements:
i. if statement:
12 | P a g
e
Python Programming
Provides an alternative block of code to execute if the condition in the if statement is False.
The for loop is used to iterate over a sequence of items such as a list, tuple, dictionary, set, or
string.
It automatically assigns each value in the sequence to a loop variable and executes the block of
code for every element.
It is mostly used when the number of iterations is known in advance.
Syntax:
14 | P a g
e
Python Programming
ii. continue:
Used within loops to skip the current iteration and proceed to the next one.
o The range() function can take one, two, or three arguments: range(stop), range(start, stop), or
range(start, stop, step).
2. exit() Function:
o The exit() function is used to terminate
the execution of the Python interpreter.
o The exit() function is usually called with an optional status code, which can indicate success (0) or
failure (non-zero).
What is a Function?
Built-in Functions-
o In Python, you can use built-in functions to perform console input and output operations.
o These functions allow you to interact with the user through the console (also known as standard input
and standard output).
o Here are the main built-in functions for console input and output:
2. Console Output:
o It can take one or more arguments, which can be of different data types.
o The function converts the arguments to strings and concatenates them, separating them with a
space by default.
3. Console Input:
o input(): The input() function is used to receive input from the user via the console.
o It displays a prompt to the user (if provided) and waits for the user to enter a value followed by
pressing the Enter key.
16 | P a g
e
Python Programming
Recursive Functions:
The term Recursion can be defined as the process of defining something in terms of itself
Recursion is programming technique where-in function is called repeatedly until a
condition is met.
Recursion is programming technique where-in function call itself.
In general, a recursive definition is made up of two parts. There is at least one base case
that directly specifies result for a special case and there is least one recursive case.
Example 1: Program to print the fibonacci series upto n_terms
def fib(n):
if n <= 1:
return n
else:
return(fib(n-1) + fib(n-2))
n_terms = 5
if n_terms <= 0:
print("Invalid input ! input a positive value")
else:
print("Fibonacci series:") for i in range(n_te rms):
print(recursive_fibonacci(i))
17 | P a g
e
Python Programming
Output
Fibonai series:
0
1
1
2
3
The variable lifetime is the period during which the variable remains in the memory
of the Python program. The variables' lifetime inside a function remains as long as the
function runs. These local types of variables are terminated as soon as the function replaces or
terminates.
Global variables:
Variables that are defined outside have a global scope. Global variables can be accessed
throughout the program body by all functions.
Local variables:
Variables that are defined inside a function body have a local [Link] means that local
variables can be accessed only inside the function in which they are declared.
Example total = 0; # This is global variable.
def sum( arg1, arg2 ):
total = arg1 total is local variable. print "Inside
the function local total : + arg2; # Here ", total
return total;
sum( 10, 20 );
print "Outside the function global total : ", total
Output:
Inside the function local total : 30
Example 2: # Program to print factorial of a numbe recursively.
18 | P a g
e
Python Programming
# Global variable
total = 0
def fact(n): # Local variable inside the function
if n == 1:
return n
else:
return n * fact(n - 1)
# Main program
num = 6
if num < 0:
print("Invalid input! Enter a positive number.")
elif num == 0:
print("Factorial of number 0 is 1")
else:
total = fact(num) # Accessing the global variable
print("Factorial of number", num, "=", total)
Modules:
1. What is a Module?
A module in Python is a file containing Python functions, classes, variables, and statements.
Any file saved with a .py extension is considered a module.
Example:
File name: my_module.py
Module name: my_module
Purpose:
Modules help in reusability, organization, and easy maintenance of large programs.
2. Importance of Modules
o Break large programs into smaller parts
o Reusability of functions and classes
o Easier debugging
o Each module has its own namespace
o Python provides many built-in modules like math, random, datetime, os
3. Creating a Module
Create any Python file and save it with .py extension.
19 | P a g
e
Python Programming
Example: my_module.py
def greet(name):
return f"Hello, {name}!"
class MyClass:
def __init__(self, value):
[Link] = value
def get_value(self):
return [Link]
PI = 3.14159
This file can be used in other programs by importing it.
4. Importing Modules
Python supports multiple import methods.
print(my_module.greet("Alice"))
obj = my_module.MyClass(10)
print(obj.get_value())
print(my_module.PI)
print([Link]("Bob"))
20 | P a g
e
Python Programming
4.3 Import Specific Items
from my_module import greet, MyClass
print(greet("Charlie"))
obj = MyClass(20)
print(obj.get_value())
21 | P a g
e
Python Programming
Example
if __name__ == "__main__":
print("Running directly")
else:
print("Imported")
Used to separate testing code from main logic.
7. Advantages of Modules
Reusable code
Better organization
Easy debugging
Avoids duplication
Faster development
Supports team collaboration
22 | P a g
e
PYTHON PROGRAMMING UNIT II
Unit: 2
Python Functions
Function is structured sequence of statements written in order to achieve specific task
There are three Types of functions in Python:
There are mainly types of functions in python.
Built-in library function: These are Standard functions in Python that are available to use.
(Python provides a lot of built-in functions that eases the writing of code. )
(Note: These Built-in-function has explained in the 1st unit)
User-defined function: We can create our own functions based on our requirements.
Anonymous function: which also are called lambda functions because they're not declared with the
quality def keyword. Instead, they are defined using the lambda keyword.
User-defined function:
A function starts with the keyword def, followed by the function name and parentheses ().
Input values (parameters) can be placed inside the parentheses.
The first line inside a function can be a docstring (optional), which describes what the function
does.
The code inside the function is written after a colon : and must be indented.
The return statement ends the function and can send a value back.
Example: return 5 sends back 5.
return with no value is the same as return None.
Syntax
In python each function is defined as
def name_of_function(list of formal parameters):
body of function
Ex:
# A simple Python function
def max(x, y):
if(x>y):
return x
else:
return y
# calling a function
max(30, 40)
Function Calling:
Defining a function gives it a name, sets its parameters, and organizes the code.
After a function is defined, you can use (call) it by writing its name.
If the function needs values (parameters), pass them inside the parentheses.
If it does not need any values, just use empty parentheses ().
Passing Parameters/arguments
Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
When function is used, formal parameters are bound to actual parameters during
PYTHON PROGRAMMING UNIT II
evenOdd(2)
evenOdd(3)
Output:
even
odd
greet("Pranesh", "Mumbai")
greet("Raj")
Output:
Hello Pranesh from Mumbai!
Hello Raj from Hyderabad!
Explanation:
First call: "Mumbai" replaces the default "Hyderabad".
Second call: No value for city, so the default "Hyderabad" is used.
Keyword Arguments
Keyword arguments are used when calling a function by specifying the parameter names.
They are often used with default values so that some arguments can be optional.
PYTHON PROGRAMMING UNIT II
Example:
def printName(fName, lName, reverse=False):
if reverse:
print(lName + ', ' + fName)
else:
print(fName, lName)
printName("KLE", "BCA")
# Output: KLE BCA
Key Points:
Default values allow calling the function with fewer arguments.
Using keyword arguments, you can change the order of arguments when calling the
function.
Lambda Functions:
A lambda function is a small anonymous function.
It can take any number of arguments, but can only have one expression.
Syntax:
lambda arguments : expression
The expression is evaluated and returned.
Basic Examples
1. Add 10 to an argument:
x = lambda a : a + 10
print(x(5))
Output: 15
2. Multiply two arguments:
x = lambda a, b : a * b
print(x(5,6))
Output: 30
3. Sum three arguments:
x = lambda a, b, c : a + b + c
print(x(5,6,2))
Output: 13
PYTHON PROGRAMMING UNIT II
mydoubler = myfunc(2)
print(mydoubler(11)) # Output: 22
mytripler = myfunc(3)
print(mytripler(11)) # Output: 33
Key Takeaways
Lambdas are good for small, throw-away functions.
Useful with map, filter, sorted on lists or iterables.
Limited to one expression — use def for complex logic.
Overuse can reduce readability; use sparingly.
PYTHON PROGRAMMING UNIT II
Strings
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes.
Creating and Storing Strings
Create a string by enclosing the characters in single-quotes or double-
quotes.
Examples
str1 = 'Hello Python' str2 = "Hello Python"
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
PYTHON PROGRAMMING UNIT II
Operations on Strings:
Concatenation
Two strings can be concatenated in Python by simply using the ‘+’ operator between
them.
s1="bca"
s2="kle"
s3=s1+s2
s4=s1+" "+s2
print(s3)
print(s4)
OUTPUT:
bcakle
bca kle
OUTPUT:
HELLO
IndexError: string index out of range
The str()function
OUTPUT
100 <class 'str'>
100.1 <class 'str'>
PYTHON PROGRAMMING UNIT II
Comparison
To compare two strings, to identify whether the two strings are equivalent to each other
or not, or greater or smaller than the other.
name = "KLE"
name1 = "BCA"
OUTPUT:
Are name and name1 equal? False
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of
the string.
Example:
String = 'ASTRING'
___
Join
The string join() method returns a string by joining all the elements of an iterable
(list, string, tuple), separated by the given separator.
Example:
text = ['Python', 'is', 'a', 'fun', 'programming', 'language']
Output:
Python is a fun programming language
Traversig Example 1:
string_name = "Pythonprogram"
# Iterate over the string
for element in string_name:
PYTHON PROGRAMMING UNIT II
output:
Pythonprogram
Example 2:
string_name = "Python"
Output:
Py t h o n
Escape Sequences:
Method Description
capitalize() It capitalizes the first character of the
String.
isalnum() It returns true if the characters in the string are alphanumeric
isalpha() It returns true if all the characters are alphabets and there is at least one
character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
isdigit() It returns true if all the characters are digits and there is at least one character,
otherwise False.
islower() It returns true if the characters of a string are in lower case, otherwise false.
File Handling
Every computer system uses files to save things from one computation to the next.
Python provides many facilities for creating and accessing files.
File Types
There are mainly two types of data files
1. Text file
2. Binary File
o A text file consists of human readable characters, which can be opened by any text editor.
o Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents.
Open a file
Read or write - Performing operation
Close the file
Creating files
filehandle = open(‘kids’ , ‘w’) instructs the operating system to create a file with name
kids
& return its filehandle for the file. The argument w indicates that file is opened for writing.
Syntax:
fileobject = open(<file-name>, <access mode>, <buffering>)
Opening a file
Python provides an open() function that accepts two arguments, file name and access mode in
which the file is accessed.
The function returns a file object which can be used to perform various operations like reading,
writing, etc.
Example
fileptr = open("[Link]","r")
if fileptr:
print("file is opened successfully")
Read a file
To read a file using the Python script, the Python provides the read() method. The
read() method reads a string from the file. It can read the data in the text as well as a binary
format.
We can also open file for reading using argument ‘r’ and prints its contents. Python treats file
as a sequence of lines, we use for statement to iterate over file’s contents.
Example:
fileptr = open("[Link]","r")
content = [Link](10)
print(type(content))
print(content) [Link]()
PYTHON PROGRAMMING UNIT II
Write in file
To write some text to a file, we need to open the file using the open method with one of the
following access modes.
o w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
o a: It will append the existing file. The file pointer is at the end of the file. It creates a
new file if no file exists.
Example
fileptr = open("[Link]", "w")
[Link](Python has an easy syntax and user friendly interaction)
[Link]()
Close Files
Once all the operations are done on the file, we must close it through our Python script
using the close() method.
Any unwritten information gets destroyed once the close() method is called on a file object.
Syntax
[Link]()
open(fn, 'w') fn is a string representing a file name. Creates a file for writing and returns a
file handle.
open(fn, 'r') fn is a string representing a file name. Opens an existing file for reading and
returns a file handle.
open(fn, 'a') fn is a string representing a file name. Opens an existing file for appending
and returns a file handle.
[Link]() returns a string containing the contents of the file associated with file handle fh.
[Link]() returns the next line in the file associated with the file handle fh.
[Link]() returns a list each element of which is one line of the file associated with the
file handle fh.
[Link](s) write the string s to the end of the file associated with the file handle fh.
[Link](S) S is a sequence of strings. Writes each element of S to the file associated
with the file handle fh.
[Link]() closes the file associated with the file handle fh
There are three methods that we can use to get the filename from a given path in python.
Some of these methods use built-in functions, others use a module.
1. Split function in python
Any path that is passed to the interpreter will be a string value.
When a path is passed as an input, it will look like C:\Users\User1\Documents\[Link]
We can use the built-in split function in python to split the path name. We will split the
path name at every \.
Once we do that, we will have a tuple that contains all the words between the
slashes.
Then we print the last element of the tuple and we get the filename with the extension.
Example:
file_path = "C:/Users/User1/Documents/[Link]"
file_name = file_path.split("/")[-1]
print(file_name)
OUTPUT:
[Link]
PYTHON PROGRAMMING UNIT II
2. OS module in python
The OS module in python provides special functions and methods for operating system
functionality like filename extraction.
We can use the [Link] function to get the filename from the path given by the
user.
we can use the [Link] function to get the filename without the extension.
Example:
import os
file_path = "C:/Users/User1/Documents/[Link]"
full_name = [Link](file_path)
file_name = [Link](full_name)
print(full_name)
print(file_name[0])
Output:
[Link]
file1
Output:
[Link]
file1
PYTHON PROGRAMMING UNIT II
PYTHON PROGRAMMING UNIT II
LISTS
• A list is a data structure in Python that is a mutable, ordered sequence of
elements. List is a data structure of collection of elements.
• Lists are defined using square brackets with items separated by commas.
• Mutable: lists are mutable, meaning we can change their values after they
are created.
• Ordered: lists maintains the order in which the elements were added to it.
• Indexing: we can access the elements of a list by their index.
• Slicing: we can extract a subset of elements from a list using slicing which
uses colon to separate a start and end indices.
Creating lists: different ways to create a list in python
1. Using square brackets: we can create a list by enclosing a comma-
separated sequence of values inside square brackets.
For example: my_list = [1, 2, 3, 4, 5]
2. Slicing: we can create a new list that contains a subset of the items in the
original list by using slicing. Slicing uses a colon to separate the start and stop
value. Example:
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4]) #[2, 3, 4]
Operations on Lists:
3. Concatenation: we can combine 2 or more lists into a single list using
concatenation, which uses + operator. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
concatenated_list = list1 + list2
print(concatenated_list) # [1, 2, 3, 4, 5, 6]
4. Repetition: we can create a new list that contains multiple copies of the
items in the original list using repetition, which uses * operator. Example:
my_list = [1, 2, 3]
repeated_list = my_list * 3
print(repeated_list) #[1, 1, 1, 2, 2, 2, 3, 3, 3]
Operations on Lists:
5. Length: we can determine the number of items in a list using the len()
function. Example:
mylist = [1, 2, 3, 5, 7]
print(len(mylist)) #5
8. Reversing: we can reverse the order of items in a list using the reverse() method.
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # [3, 2, 1]
Built-in Functions on Lists:
1. len() 8. count()
2. max() 9. index()
3. min() 10. append()
4. sum() 11. extend()
5. sorted() 12. insert()
6. reversed() 13. remove()
7. list() 14. pop()
15. clear()
Built-in Functions on Lists:
1. len(): This function returns the number of items in a list. Example:
my_list = [1, 3, 2]
print(len(my_list)) #3
4. sum(): This function returns the sum of all the elements in a list. Example:
my_list = [1, 3, 2]
print(sum(my_list)) #3
5. list(): Using list() function, we can convert a sequence (tuple, string) into list.
Example:
tuple = (1, 2, 3, 4)
my_list = list(tuple)
print(my_list) # [1, 2, 3, 4]
Built-in Functions on Lists:
6. sorted(): This function returns a sorted order of list in ascending order.
Example:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
print(sorted_list)) # [1, 2, 3]
11. extend(e): This function adds the elements of another list to the end of the
list. Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
[Link](list2)
print(list1) # [1, 2, 3, 4, 5, 6]
Built-in Functions on Lists:
12. insert(i,e): This function inserts an element at a specified position in the
list. Example:
my_list = [1, 2, 3, 4]
my_list.insert(0, 5)
print(my_list) # [5, 1, 2, 3, 4]
13. remove(e): This function removes the first occurrence of a specified
element in the list. Example:
numbers = [50, 10, 20, 30, 40, 50]
[Link](30)
print(numbers) # [50, 10, 20, 40, 50]
[Link](50)
print(numbers) # [10, 20, 40, 50]
Built-in Functions on Lists:
14. pop(): Using this function element can be removed from the list by specifying the
index value. If the indexed item is not specified then the last item will be deleted
from the list . Example:
my_list = [11, 12, 13, 14, 15]
removed_element = my_list.pop(1)
print(removed_element) # 12
removed_element = my_list.pop()
print(removed_element) # 15
15. clear(): This function removes all the elements from list. Example:
my_list = [1, 3, 2, 5, 7]
my_list.clear()
print(my_list) #[]
Nested Lists:
A Nested list is a list that contains another list as its elements. The elements of
a nested list can be accessed using multiple indices.
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, my_list is a list that contains three other lists as its
elements. The first element is [1, 2, 3], the second element is [4, 5, 6] and last
element is [7, 8, 9].
We can access the elements of a nested list using multiple indices. For
example,
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(my_list[0][0]) #1
print(my_list[1][2]) #6
print(my_list[2]) # [7, 8, 9]
DICTIONARIES
• Creating Dictionaries;
• Operations on Dictionaries;
• Built-in Functions on Dictionaries;
• Dictionary Methods;
• Populating and Traversing Dictionaries.
DICTIONARIES
• Creating dictionaries:
print("Age:", Employee["Age"])
print("Salary:", Employee["salary"])
print("Company:", Employee["Company"])
1. # Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[3] = ‘Rocky'
print("Dictionary after updating: ")
print(Dict)
Dict = {}
print("Empty Dictionary: ")
print(Dict)
del Employee
print(Employee)
Checking for existence of keys in Dictionary
• We use in keyword check existence of key in the dictionary.
• For example,
del Employee["Name"]
print(“Name” in Employee)
Looping over keys or values in dictionary
• We can loop through in dictionary for keys or values.
• For example,
2. keys()
3. values()
4. items()
5. get()
6. pop()
7. sorted()
Dictionary Methods
1. clear()
2. copy()
3. update()
4. pop()
5. popitem()
6. get()
7. items()
8. keys()
Dictionary Methods
1. clear() : It removes all the key-value pairs from the dictionary.
print([Link]())
#{}
# None
Dictionary Methods
2. copy() : It returns a shallow copy of the dictionary.
[Link](Emp2)
print(Emp1)
print(Emp1)
# 45000
# {'Name': 'Dev', 'Age': 20, 'Company': 'WIPRO'}
Dictionary Methods
5. popitem() : It removes the item (key-value pair) inserted into the dictionary.
The removed item is the return value of the popitem() method, as a tuple.
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print([Link]())
print(Emp1)
# ('Company', 'WIPRO')
# {'Name': 'Dev', 'Age': 20, 'Salary': 45000}
Dictionary Methods
6. get() : It returns the value of the specified key. If the key does not exist, it
returns the specified default value (None).
Emp1 = {"Name": "Dev", "Age": 20, “Salary":45000, "Company":"WIPRO"}
print([Link](“Age”))
# 20
Dictionary Methods
7. items() : It returns a list of all the key-value pairs in a dictionary as tuples.
for i in Employee:
print(i)
for i in Employee:
print(Employee[i])
for i in [Link]():
print(i)
for i in [Link]():
print(i)
print([Link]())
print([Link]())
TUPLES
• Creating Tuples;
• Operations on Tuples;
• Built-in Functions on Tuples;
• Tuple Methods.
Tuples
• A Tuple is an ordered collection of elements, similar to a list. However tuples
are immutable, meaning that their values cannot be changed once they are
created.
• Tuple elements are enclosed within parentheses and separated by commas.
• A tuple in Python is similar to a list. The difference between the two is that
we cannot change the elements of a tuple once it is assigned whereas we
can change the elements of a list.
Creating a Tuple
• A Tuple is created by placing all the items (elements) inside parentheses (),
separated by commas. The parentheses are optional, however, it is a good
practice to use them.
• A tuple can have any number of items and they may be of different types
(integer, float, list, string, etc.).
# prints - a
Operations on Tuples
2. Negative Indexing: Python allows negative indexing for its sequences. The
index of -1 refers to the last item, -2 to the second last item and so on. For
example;
6. Length: We can find the length of a tuple using the len() function. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print(len(letters1))
#6
Operations on Tuples
7. Membership test: We can check if an element is present in a tuple using the
in operator. For example;
my_tuple = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
print( ‘p’ in my_tuple) #True
print( ‘g’ in my_tuple) #False
8. Iteration: We can iterate over the elements of a tuple using a for loop. For
example;
letters1 = ('p', ‘y', ‘t', ‘h', ‘o', ‘n')
p
for elements in letters1: y
t
print(elements) h
o
n
Built-in Functions on Tuples
• len()
• max()
• min()
• sum()
• sorted()
Built-in Functions on Tuples
• len() – returns the number of elements in a tuple.
print(len(my_tuple)) #6
print(max(my_tuple)) #6
print(min(my_tuple)) #1
print(sum(my_tuple)) # 21
print(sorted(my_tuple)) # [1, 2, 3, 4, 5, 6]
Tuple Methods
• Tuples are immutable in Python, which means they cannot be modified once
they are created. As a result, there are only two methods defined for tuples;
1. count()
2. index()
• 1. count(): This method takes one argument and returns the number of
times that argument appears in the tuple:
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(count(1))
#4
Tuple Methods
• 2. index(): This method takes one argument and returns the index of the
first occurrence of that argument in the tuple. If the argument is not found,
it raises ValueError.
Example: my_tuple = (1, 2, 3, 4, 5, 1, 2, 1, 1)
print(my_tulpe(index(4)) #3
print(my_tulpe(index(1)) #0
Note: These methods do not modify the original tuple. If you wish to modify a
tuple, you must first convert it to a list, make changes and then convert it back
to a tuple.
PYTHON PROGRAMMING UNIT II
Unit: 3
Exception Handling
An exception is defined as something that does not conform to the norm and therefore
somewhat rare.
Exception handling is mechanism provided to handle the run-time errors or exceptions
which often disrupt the normal flow of execution.
Most common types of exceptions are: TypeError, IndexError, NameError and ValueError.
When an exception is raised that causes program to terminate, we say that an unhandled
exception has been raised
1
PYTHON PROGRAMMING UNIT II
Note:
Exceptions let programs detect and respond to unexpected situations instead of crashing.
2. Handling Exceptions
Python provides structured exception handling using the following blocks:
1. try,
2. except,
3. else, and
4. finally.
2
PYTHON PROGRAMMING UNIT II
3
PYTHON PROGRAMMING UNIT II
3. Raising Exceptions
You can manually raise an exception using the raise keyword.
This is useful for enforcing rules or signaling errors in your code.
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
return age
try:
my_age = validate_age(-5)
except ValueError as e:
print(f"Validation Error: {e}")
4. User-Defined Exceptions
You can create custom exceptions by subclassing the built-in Exception class.
This allows domain-specific or meaningful error messages.
class MyCustomError(Exception):
"""Custom exception for specific errors"""
pass
def process_data(data):
if not data:
raise MyCustomError("Input data cannot be empty.")
print("Data processed successfully")
try:
process_data([])
except MyCustomError as e:
print(f"Custom Error: {e}")
Example:
def divide_numbers(a, b):
4
PYTHON PROGRAMMING UNIT II
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print("Division result:", result)
finally:
print("Executing the finally block.\n")
divide_numbers(10, 2)
divide_numbers(10, 0)
OUTPUT:
5. Note:
5
PYTHON PROGRAMMING UNIT IV
name = "John"
def display (self):
print("ID: “,[Link])
print("Name: “,[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()
4
PYTHON PROGRAMMING UNIT IV
def Add(self,T):
R=TwoNum()
R. x=self. x+T. x
R. y=self. y+T. y
return R
obj1 = TwoNum()
obj2 = TwoNum()
5
PYTHON PROGRAMMING UNIT IV
Example: Example:
class Parent1:
class Calculation1:
def func1(self):
print ("function is defined inside the parent class.") def Summation(self,a,b):
return a+b;
class Child1(Parent1):
class Calculation2:
def func2(self):
print ("function is defined inside the child class.") def Multiplication(self,a,b):
# Driver's code return a*b;
object = Child1()
object.func1() class Derived(Calculation1,Calculation2):
object.func2() def Divide(self,a,b):
return a/b;
Output: d = Derived()
Output:
Multiple Inheritance If a class is able to be created
30
from multiple base classes, this kind of Inheritance is 200
known as multiple Inheritance. When there is multiple 0.5
Inheritance, each of the attributes that are present in the
classes of the base has been passed on to the class that is Multilevel and Multipath Inheritance
derived from it. Multi-level inheritance is archived when a derived
class inherits another derived class. There is no limit
on the number of levels up to which, the multi-level
inheritance is archived in python.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite> Syntax
. class class1:
. <class-suite>
. class class2(class1):
class BaseN: <class suite>
<class-suite> class class3(class2):
class Derived(Base1, Base2, ........ BaseN): <class suite>
<class-suite> .
.
6
PYTHON PROGRAMMING UNIT IV
7
PYTHON PROGRAMMING UNIT IV
Example 1:
class example:
def init (self, X):
self.X = X
Output: