Python Programming Course Overview
Python Programming Course Overview
UNIT- 1
History of Python Programming Language, Thrust Areas of Python, Installing Anaconda
Python Distribution, Installing and Using Jupyter Notebook.
Parts of Python Programming Language: Identifiers, Keywords, Statements and Expressions,
Variables, Operators, Precedence and Associativity, Data Types, Indentation, Comments,
Reading Input, Print Output, Type Conversions, the type () Function and Is Operator, Dynamic
and Strongly Typed Language.
Control Flow Statements: if statement, if-else statement, if...elif…else, Nested if statement,
while Loop, for Loop, continue and break Statements, Catching Exceptions Using try and
except Statement.
Sample Experiments:
1. Write a program to find the largest element among three Numbers.
2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary variable.
4. Demonstrate the following Operators in Python with suitable examples.
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators
iv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators
viii) Identity Operators
5. Write a program to add and multiply complex numbers
6. Write a program to print multiplication table of a given number.
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
S
Learning Material
1.1 History of Python Programming Language
Python was first developed by Guido van Rossum in the late 80’s and early 90’s at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
It has been derived from many languages such as ABC, Modula-3, C, C++, Algol-68,
SmallTalk,UNIX shell and other scripting languages.
Since early 90’s Python has been improved tremendously. Its version 1.0 was released
in1991, which introduced several new functional programming tools.
While version 2.0 included list comprehension was released in 2000 by the
BeOpenPythonLabs team.
Python 2.7 which will be supported till 2020
Python continues to evolve with regular releases (e.g., Python 3.10, 3.11) that introduce new
features, optimizations, and improvements.
8. Choose whether to add Anaconda to your PATH environment variable or register Anaconda
11. After a successful installation you will see the “Thanks for installing Anaconda” dialog box:
3. You will see that a command window opens. Just wait for few seconds until you see
a file location (something like shown below)
4. Type “jupyter notebook” in the command prompt and then Press Enter
5. In few seconds, you will see that your command is executed as shown below.
6. At the same time, you will also see that your browser opens showing Jupyter
Notebook Interface. Click on “New” located at upper right corner if you wish
to open Jupyter Notebook.
4. To run a code either click the run button or press shift ⇧ + enter ⏎ after selecting the
cell you want to execute. After writing the above code in the jupyter notebook, the
output was:
1.5.2 Keywords
Keywords are the reserved words in Python. We cannot use a keyword as variable
name, function name or any other identifier.
Here's a list of all keywords in Python Programming.
There are 33 keywords in Python [Link] number can vary slightly in course of time.
All the keywords except True, False and None are in lowercase and they must be
written as it is. The list of all the keywords are given below.
as elif if or yield
Arithmetic operators
Comparison (Relational) operators
Unary Operators
Bitwise operators
Shift Operators
Logical Operators
Membership and Identity Operators
Assignment operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
This operator will work on two operands.
Example: If a=100 and b=200 then look at the table below, to see the result of
arithmetic operations.
Unary Operator
Unary operators act on single operands. Python supports unary minus operator.
Unary minus operator is strikingly different from the arithmetic operator that operates
on two operands and subtracts the second operand from the first operand.
When an operand is preceded by a minus sign, the unary operator negates its value.
For example, if a number is positive, it becomes negative when preceded with a unary
minus operator. Similarly, if the number is negative, it becomes positive after
applying the unary minus operator. Consider the given example.
b = 10 a = -(b)
The result of this expression, is a = -10, because variable b has a positive value. After
applying unary minus operator (-) on the operand b, the value becomes -10, which
indicates it as a negative value.
Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift operators.
Bitwise operators expect their operands to be of integers and treat them as a sequence
of bits.
The truth tables of these bitwise operators are given below.
Example: If a=60 and b=13 then look at the table below, to see the result of Bitwise
operations.
~ (~a ) = -61
Binary Ones (means 1100 0011 in
Complement It is unary and has the effect of 'flipping' bits. 2's complement form
due to a signed binary
number.
<< The left operands value is moved left by the a << 2 = 240
Binary Left Shift number of bits specified by the right operand. (means 1111 0000)
Shift Operators
Python supports two bitwise shift operators. They are shift left (<<) and shift right
(>>).
These operations are used to shift bits to the left or to the right. The syntax for a shift
operation can be given as follows:
Logical Operators
Python supports two types of membership operators–in and not in. These operators,
test for membership in a sequence such as strings, lists, or tuples.
in Operator: The operator returns true if a variable is found in the specified sequence
and false otherwise. For example, a in nums returns 1, if a is a member of nums.
not in Operator: The operator returns true if a variable is not found in the specified
sequence and false otherwise. For example, a not in nums returns 1, if a is not a
member of nums.
Identity Operators
is Operator: Returns true if operands or values on both sides of the operator point to
the same object and false otherwise. For example, if a is b returns 1, if id(a) is same as
id(b).
is not Operator: Returns true if operands or values on both sides of the operator does
not point to the same object and false otherwise. For example, if a is not b returns 1, if
id(a) is not same as id(b).
Assignment Operators
Assignment operators are used in Python to assign values to variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.
Assignment operators in
Python
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
1.5.8 Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only,
the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Example
if 5 > 2:
print("Five is greater than two!")
output:
1.5.9 Comments
Python has commenting capability for the purpose of in-code documentation.
Comments can be used to explain Python code.
Comments start with a symbol # , and Python will render the rest of the line as a
comment.
Python does not really have a syntax for multiline comments.
Example
#This is a comment.
print("Hello, World!")
Output: Hello, World!
1.5.10 Reading Input
In Python, we use the input() function to read input from the user.
Whatever you enter as input, the input function converts it into a string. If you
enter an integer value still input() function converts it into a string.
Syntax: input(prompt)
Example:
name = input('What is your name?\n')
print(name)
output:
What is your name?
Ram
Ram
1.5.11 Print Output
The print() function prints the specified message to the screen, or other standard
output device.
The message can be a string, or any other object, the object will be converted into
a string before written to the screen.
Examples:
1. print("Hello World")
2. print("Hello", "how are you?")
3. x = ("apple", "banana", "cherry")
print(x)
1.5.12 Type Conversions
Python defines type conversion functions to directly convert one data type to
another.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
The Python interpreter automatically performs Implicit Type Conversion.
It converts one data type to another without any user involvement.
Python prevents Implicit Type Conversion from losing data.
runtime.
Strong typing means that variables do have a type and that the type matters when
performing operations on a variable.
1.6 Control Flow Statements
A control Flow statement is a statement that determines the control flow of a set of
instructions, i.e., it decides the sequence in which the instructions in a program are to be
executed.
Selection/Conditional Control: To execute only a selected set of statements.
Iterative Control: To execute a set of statements repeatedly.
Un-conditional Control:
statement x
Example:
else:
statement_block 2
statement x
If the condition is true, then it will execute statement block 1 and if the condition is
false then it will execute statement block 2.
Flowchart:
A series of if and elif statements have a final else block, which is executed if none of
the if or elif expressions is True.
Syntax:
if (test expression 1):
statement block1
elif (test expression 2):
statement block2
. . . . . . . . . . . . . . ..
elif( test expression N):
statement block N
else:
statement block X
Flowchart:
Program: To test whether a number entered by the user is negative, positive, or zero
Example: Program that prompts the user to enter a number and then print the interval
Statement y
In while loop, the condition is tested before any of the statements in the statement
block is executed.
If the condition is TRUE, only then the statements will be executed otherwise if the
condition is False, the control will jump to statement y, that is the immediate
statement outside the while loop block.
Flowchart:
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9 10
Flowchart:
range() Function :
o The range( ) function is a built-in function in Python that is used to iterate over
a sequence of numbers.
o Syntax:
range(beg, end, [step])
o The range( ) produces a sequence of numbers starting with beg (inclusive) and
ending with one less than the number end.
o The step argument is option (that is why it is placed in brackets). By default,
every number in the range is incremented by 1 but we can specify a different
increment using step. It can be both negative and positive, but not zero.
Example: Program to print first n numbers using the range() in a for loop
o If range( ) is called with two arguments, it produces values from the first to the
second. For example, range(0, 10) gives 0-9.
o If range( ) has three arguments then the third argument specifies the interval of
the sequence produced. In this case, the third argument must be an integer. For
example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.
Example:
1.6.7 continue
The continue statement can only appear in the body of a loop.
When the compiler encounters a continue statement then the rest of the statements in
the loop are skipped and the control is unconditionally transferred to the loop-
continuation portion of the nearest enclosing loop.
Syntax:
Continue
Note that the code is meant to print numbers from 0 to [Link] as soon as i becomes
equal to 5, the continue statement is encountered, so rest of the statements in the loop
are skipped. In the output, 5 is missing as continue caused early increment of i and
skipping of statement that printed the value of i on screen.
Below figure illustrates the use of continue statement in loops.
It can be concluded that the continue statement is somewhat the opposite of the break
statement. It forces the next iteration of the loop to take place, skipping any code in
between itself and the test condition of the loop.
The continue statement is usually used to restart a statement sequence when an error
occurs.
1.6.8 break
The break statement is used to terminate the execution of the nearest enclosing loop
in which it appears.
The break statement is widely used with for loop and while loop.
When compiler encounters a break statement, the control passes to the statement that
follows the loop in which the break statement appears.
Syntax:
break
Example: Program to demonstrate the break statement
Above code is meant to print first 10 numbers using a while loop, but it will actually
print only numbers from 0 to 4. As soon as i becomes equal to 5, the break statement
is executed and the control jumps to the following while loop.
Hence, the break statement is used to exit a loop from any point with in its body, by
passing its normal termination expression. Below, Figure shows the transfer of control
when the break statement is encountered.
Whereas the code inside the except block will execute whenever the program
encounters some error in the preceding try block.
The try contains statements that can raise exceptions, whereas the except clause
contains statements that handle the exception.
Syntax:
try:
# Some Code
except:
# Executed if error in the try block
Example:
a=[1,2,3]
try:
print(a[10])
except IndexError:
print(“You are not giving valid index”)
output:-
You are not giving valid index
Sample Experiments:
1. Write a program to find the largest element among three Numbers.
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
output:
print (number)
output:
UNIT-II
Strings: Creating and Storing Strings, Basic String Operations, Accessing Characters
in String by Index Number, String Slicing and Joining, String Methods, Formatting
[Link]: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-
In Functions Used on Lists, List Methods, del Statement.
Sample Experiments:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.
i) Introduction to Function
A function in Python is defined using the `def` keyword, followed by the function name,
parentheses `()`, and a colon `:`.
Inside the parentheses, you can specify parameters that the function can accept.
The code block within the function is indented.
**Syntax:**
def function_name(parameters):
# Code block
return result
**Example:**
def greet(name):
print(f"Hello, {name}!")
In this example, `greet` is a function that takes one parameter, `name`, and
prints a greeting message.
1. **Code Reusability:**
Functions allow you to reuse code. Instead of writing the same code multiple
times, you can define a function once and call it whenever needed.
**Example:**
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
```
2. **Modularity:**
Functions help to break down complex problems into smaller, manageable
parts. Each function can focus on a single task.
**Example:**
def calculate_area(length, width):
return length * width
print_area(5, 3)
3. **Improved Readability:**
Functions with descriptive names make the code easier to understand. Each
function name gives a clear indication of what the function does.
**Example:**
def calculate_tax(income):
return income * 0.2
def print_tax(income):
tax = calculate_tax(income)
print(f"The tax on an income of {income} is {tax}")
print_tax(50000)
4. **Maintainability:**
Functions make it easier to maintain and update code. If a change is needed,
it can be made in one place (the function) rather than multiple places in the
code.
**Example:**
def discount(price, percentage):
return price * (1 - percentage / 100)
print_discounted_price(100, 10)
**Example:**
def is_even(number):
return number % 2 == 0
def test_is_even():
assert is_even(4) == True
assert is_even(7) == False
print("All tests passed.")
test_is_even()
1. `print()`
**Example:**
2. `len()`
**Example:**
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5
3. `type()`
**Example:**
**Example:**
print(int("10")) # Output: 10
print(float("10.5")) # Output: 10.5
print(str(10)) # Output: "10"
5. `sum()`
**Example:**
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
6. `max()`, `min()`
**Example:**
numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5
print(min(numbers)) # Output: 1
7. `abs()`
**Example:**
print(abs(-10)) # Output: 10
print(abs(10)) # Output: 10
8. `round()`
**Example:**
9. `sorted()`
**Example:**
numbers = [3, 1, 4, 1, 5, 9]
print(sorted(numbers)) # Output: [1, 1, 3, 4, 5, 9]
10. `enumerate()`
Returns an enumerate object, which contains pairs of index and value from the
iterable.
**Example:**
11. `zip()`
**Example:**
12. `map()`
**Example:**
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
13. `filter()`
**Example:**
def is_even(x):
return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers)) # Output: [2, 4, 6]
**Example:**
```python
numbers = [0, 1, 2, 3]
print(all(numbers)) # Output: False (because 0 is False)
print(any(numbers)) # Output: True (because at least one value is True)
```
15. `range()`
**Example:**
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
1. `math` Module
**Example:**
import math
2. `datetime` Module
The `datetime` module supplies classes for manipulating dates and times.
**Example:**
import datetime
now = [Link]()
print(now) # Output: Current date and time
today = [Link]()
print(today) # Output: Current date
new_year = [Link](2024, 1, 1)
print(new_year) # Output: 2024-01-01
3. `random` Module
**Example:**
import random
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers) # Output: Shuffled list
4. `os` Module
**Example:**
import os
current_directory = [Link]()
print(current_directory) # Output: Current working directory
5. `sys` Module
**Example:**
import sys
Functions are defined using the `def` keyword, followed by the function
name and parentheses containing any parameters.
After defining a function, you can call it by using its name followed by
parentheses, optionally including arguments.
Function Definition
def function_name(parameters):
# Code block
return result
Calling a Function
function_name(arguments)
`return` Statement
Example:
**Example:**
# Function Definition
def add_numbers(a, b):
result = a + b
return result
**Explanation:**
1. **Function Definition:**
- `def add_numbers(a, b):` - This line defines a function named `add_numbers`
that takes two parameters `a` and `b`.
- `result = a + b` - This line calculates the sum of `a` and `b` and stores it in
the variable `result`.
- `return result` - This line returns the value of `result` to the caller.
**Output:**
The sum is: 8
Additional Examples
# Function Definition
def square(number):
return number * number
**Output:**
# Function Definition
def greet(name):
return f"Hello, {name}!"
**Output:**
Hello, Alice!
v) void function
In Python, a void function is a function that does not return any value.
Instead of returning a value, it performs some actions like printing to the
console, modifying a global variable, or altering the state of an object.
A void function in Python is defined the same way as any other function
but it does not include a `return` statement that returns a value.
# Function Definition
def greet(name):
print(f"Hello, {name}!")
**Explanation:**
1. **Function Definition:**
def greet(name): - This line defines a function named `greet` that takes
one parameter `name`.
print(f"Hello, {name}!") - This line prints a greeting message to the console
using the value of `name`.
greet("Alice") - This line calls the `greet` function with the argument
`"Alice"`, which results in the function printing the greeting message.
**Output:**
Hello, Alice!
In Python, the scope of a variable refers to the region of the code where
the variable is accessible.
The lifetime of a variable is the period during which the variable exists in
memory.
Understanding these concepts is crucial for writing clear and bug-free
code.
Types of Scope
1. **Local Scope**
2. **Enclosing Scope**
3. **Global Scope**
4. **Built-in Scope**
1. Local Scope
**Example:**
def my_function():
local_var = 10
print("Inside function:", local_var)
my_function()
# print(local_var) # This will raise an error because local_var is not accessible
outside the function.
**Output:**
Inside function: 10
**Example:**
def outer_function():
outer_var = "I am outside!"
def inner_function():
print("Inside inner function:", outer_var)
inner_function()
outer_function()
**Output:**
Inside inner function: I am outside!
3. Global Scope
A variable defined at the top level of a script or module has a global scope. It is
accessible throughout the module.
**Example:**
global_var = "I am global!"
def my_function():
print("Inside function:", global_var)
my_function()
print("Outside function:", global_var)
**Output:**
Inside function: I am global!
Outside function: I am global!
4. Built-in Scope
These are special variables and functions provided by Python, such as `print()`,
`len()`, etc. They are always available in any part of the code.
**Example:**
print("Hello, World!")
print(len("Hello"))
**Output:**
Hello, World!
5
Lifetime of Variables
The lifetime of a variable refers to the period during which the variable
exists in memory.
**Local Variables:**
Exist during the execution of the function in which they are defined.
**Global Variables:**
Exist for the duration of the program.
**Example:**
def my_function():
local_var = "I am local"
print("Inside function:", local_var)
my_function()
# print(local_var) # This will raise an error because local_var's lifetime ends with
the function execution.
**Output:**
Inside function: I am local
Outside function: I am global
To modify a global variable inside a function, you need to use the `global`
keyword.
**Example:**
counter = 0
def increment_counter():
global counter
counter += 1
increment_counter()
increment_counter()
print("Counter:", counter)
**Output:**
Counter: 2
Nonlocal Variables
**Example:**
def outer_function():
outer_var = "I am outer"
def inner_function():
nonlocal outer_var
outer_var = "I have been changed"
print("Inside inner function:", outer_var)
inner_function()
print("Inside outer function:", outer_var)
outer_function()
**Output:**
Default Parameters
**Example:**
def greet(name, message="Hello"):
print(f"{message}, {name}!")
**Output:**
Hi, Alice!
Hello, Bob!
Keyword Arguments
**Example:**
def describe_pet(pet_name, animal_type):
print(f"I have a {animal_type} named {pet_name}.")
**Output:**
*args
**Example:**
def make_pizza(size, *toppings):
**Output:**
**kwargs
**Example:**
def build_profile(first, last, **user_info):
profile = {
'first_name': first,
'last_name': last,
}
for key, value in user_info.items():
profile[key] = value
return profile
**Output:**
You can use both `*args` and `**kwargs` in the same function to accept a
combination of positional and keyword arguments.
**Example:**
def show_details(name, age, *args, **kwargs):
print(f"Name: {name}, Age: {age}")
print("Additional positional arguments:", args)
print("Additional keyword arguments:", kwargs)
**Output:**
Name: Alice, Age: 30
Additional positional arguments: ('Engineer', 'Single')
Additional keyword arguments: {'city': 'New York', 'hobby': 'Reading'}
Using `[Link]`
**Example:**
Now, run the script from the command line with different arguments:
**Output:**
Total arguments: 4
Script name: [Link]
Arguments: ['arg1', 'arg2', 'arg3']
viii) Strings
In Python, strings are sequences of characters enclosed within either single
quotes (`'`) or double quotes (`"`). They are immutable, meaning once defined,
their content cannot be changed. Here are various ways to create and
manipulate strings in Python:
1. Creating Strings
```python
# Single quotes
single_quoted = 'Hello, World!'
print(single_quoted)
# Double quotes
double_quoted = "Python Programming"
print(double_quoted)
```
2. String Concatenation
str1 = "Hello"
str2 = "World"
concatenated_string = str1 + ", " + str2 + "!"
print(concatenated_string)
4. String Slicing
5. String Methods
6. Format Strings
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
7. Escape Characters
8. Raw Strings
9. String Conversion
number = 42
converted_string = str(number)
print(converted_string) # Output: '42'
string_variable = "Python"
list_of_strings = ["apple", "banana", "cherry"]
dictionary_of_strings = {"name": "Alice", "city": "Wonderland"}
1. String Concatenation
**Output:**
Hello, World!
2. String Repetition
original_string = "Python"
repeated_string = original_string * 3
print(repeated_string)
**Output:**
PythonPythonPython
3. String Length
You can find the length of a string using the `len()` function:
message = "Hello, World!"
length_of_string = len(message)
print(length_of_string)
**Output:**
13
4. Accessing Characters
5. String Slicing
6. String Methods
7. String Formatting
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
**Output:**
My name is Alice and I am 30 years old.
8. String Conversion
number = 42
converted_string = str(number)
print(converted_string) # Output: '42'
9. Checking Substrings
You can check if a substring exists within a string using the `in` keyword:
message = "Hello, World!"
print('Hello' in message) # Output: True
print('Python' in message) # Output: False
You can remove whitespace from the beginning and end of a string using
`strip()`, `lstrip()`, and `rstrip()` methods:
message = "Python"
You can iterate over a string and access each character by its index:
message = "Python"
**Output:**
Character at index 0: P
Character at index 1: y
Character at index 2: t
Character at index 3: h
Character at index 4: o
Character at index 5: n
String Slicing
Basic Slicing
# Extracting a substring
substring = message[7:18] # Starts at index 7, ends at index 17
(exclusive)
print(substring) # Output: 'Programming'
You can use negative indices to slice from the end of the string:
If you omit the start index, slicing starts from the beginning of the
string.
If you omit the end index, slicing continues to the end of the
string:
String Joining
1. capitalize()
Converts the first character of the string to uppercase and the rest to
lowercase.
message = "hello world"
capitalized_message = [Link]()
print(capitalized_message) # Output: 'Hello world'
3. count(substring)
`find()` and `index()` both return the index of the first occurrence of
the substring in the string.
The difference is that `find()` returns `-1` if the substring is not found,
while `index()` raises a `ValueError`.
message = "Python is powerful"
print([Link]("is")) # Output: 7
print([Link]("power"))# Output: 10
5. `replace(old, new)`
6. `split(delimiter)`
message = "apple,banana,cherry"
fruits_list = [Link](",")
print(fruits_list) # Output: ['apple', 'banana', 'cherry']
Checks if the string starts or ends with the specified prefix or suffix.
9. `join(iterable)`
number = "12345"
word = "Python"
print([Link]()) # Output: True
print([Link]()) # Output: True
11. `format()`
**Output:**
My name is Alice and I am 30 years old.
**Output:**
The sum of 5 and 10 is 15.
2. Using `[Link]()`
print(formatted_string)
**Output:**
My name is Bob and I am 25 years old.
You can specify the order of arguments and use field names:
name = "Carol"
age = 35
formatted_string = "My name is {1} and I am {0} years old.".format(age,
name)
print(formatted_string)
**Output:**
My name is Carol and I am 35 years old.
**Output:**
My name is David and I am 40 years old.
**Output:**
apple, banana, cherry
text = "Hello"
print([Link](10)) # Output: 'Hello '
Lists:
xiii) Creating Lists, Basic List Operations, Indexing and Slicing in Lists,
Built-In Functions Used on Lists, List Methods
In Python, lists are ordered collections of items, which can be of any data
type (such as integers, floats, strings, or even other lists).
Lists are mutable, meaning you can change their contents after they are
created.
Here’s how you can create and work with lists in Python:
1. Creating a List
2. Nested Lists
Lists can contain other lists as elements, allowing for nested data structures:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(nested_list) # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
3. Accessing Elements
You can access elements of a list using square brackets and the index of
the element (indexing starts at 0):
# Negative indexing
print(fruits[-1]) # Output: 'cherry' (last element)
```
4. Slicing Lists
You can slice a list to extract a sublist using the syntax `[start:end]`.
Slicing doesn't modify the original list but returns a new list:
numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4]
print(sublist) # Output: [2, 3, 4]
5. Modifying Lists
Lists are mutable, so you can modify elements, append new elements, or
delete existing ones:
[Link]("pear")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'pear']
del fruits[0]
print(fruits) # Output: ['orange', 'cherry', 'pear']
6. List Methods
numbers = [3, 1, 2, 5, 4]
[Link]()
print(numbers) # Output: [1, 2, 3, 4, 5]
[Link]()
print(numbers) # Output: [5, 4, 3, 2, 1]
[Link](6)
print(numbers) # Output: [5, 4, 3, 2, 1, 6]
[Link](3)
print(numbers) # Output: [5, 4, 2, 1, 6]
7. List Comprehensions
List comprehensions provide a concise way to create lists. They can also
include conditions and nested loops:
Lists are versatile data structures in Python that allow you to store and
manipulate collections of items efficiently.
Understanding how to create, access, and modify lists is fundamental for
Python programming.
You can use `del` to remove an element from a list by specifying its index:
numbers = [1, 2, 3, 4, 5]
numbers = [1, 2, 3, 4, 5]
To delete the entire list and free up memory, you can use `del` on the list
itself:
numbers = [1, 2, 3, 4, 5]
del numbers
4. Deleting Variables
You can use `del` to delete variables and free up their memory:
x = 10
print(x) # Output: 10
del x
Sample Experiments:
In Python, functions can return multiple values by packing them into a tuple, list,
or other data structures. Here’s an example of how to define a function that returns
multiple values:
def calculate_statistics(numbers):
total_sum = sum(numbers)
count = len(numbers)
print(f"Average: {avg}")
print(f"{message} {name}!")
Output:
Hello, Alice!
Hi Bob!
3. Write a program to find the length of the string without using any
library functions.
def find_string_length(input_string):
length = 0
length += 1
return length
# Example usage
length = find_string_length(input_string)
**Output**:
return False
# Example usage
main_string = "Hello, World!"
substring1 = "World"
substring2 = "Python"
if is_substring_present(main_string, substring1):
print(f"'{substring1}' is present in '{main_string}'")
else:
print(f"'{substring1}' is not present in '{main_string}'")
if is_substring_present(main_string, substring2):
print(f"'{substring2}' is present in '{main_string}'")
else:
**Output**:
'World' is present in 'Hello, World!'
'Python' is not present in 'Hello, World!'
5. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
# Define a list
numbers = [1, 2, 3, 4, 5]
# i. Addition operation
[Link](6)
Output:
numbers = [5, 2, 7, 1, 8, 3]
length = len(numbers)
max_value = max(numbers)
min_value = min(numbers)
sorted_numbers = sorted(numbers)
total_sum = sum(numbers)
print(f"Sum of all elements in the list: {total_sum}") # Output: Sum of all elements
in the list: 26
Output:
UNIT-III
Sample Experiments:
Dictionary
It is a data structure in which we store values as a pair of key and value.
Each key is separated from its value by a colon (:), and consecutive items are separated
by commas.
The entire items in a dictionary are enclosed in curly brackets ({}).
Creating Dictionary:
Syntax:
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}
If there are many keys and values in dictionaries, then we can also write just one key-
value pair on a line to make the code easier to read and [Link] is shown below.
dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3 , ….}
Keys in the dictionary must be unique and be of any immutable data type (like Strings,
numbers, or tuples), there is no strict requirement for uniqueness and type of values.
Values of a key can be of any type.
Dictionaries are not Sequences, rather they are mappings.
Mappings are collections of objects that are store objects by key instead of by relative
position.
Accessing
o In Dictionary, values are accessed through keys.
Example:
d={'Name': 'Arav', 'Course': '[Link]', 'roll_no': '18/001'}
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
Output:
d[Name]: Arav
d[course]: [Link]
d[roll_no]: 18/001
Modifying an item
To modify an entry, just overwrite the existing value as shown in the following
Example:
d={'Name': 'Arav', 'Course': '[Link]', 'roll_no': '18/001'}
d['marks']=99 #new entry
print('d[Name]:',d['Name'])
print('d[course]:',d['Course'])
print('d[roll_no]:',d['roll_no'])
print('d[marks]:',d['marks'])
d[‘Course’]=’BCA’ #Updated entry
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 64
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
print('d[course]:',d['Course'])
Output:
d[Name]: Arav
d[course]: [Link]
d[roll_no]: 18/001
d[marks]: 99
d[course]: BCA
Built-in Methods:
Del Statement:
Deleting
o We can delete one or more items using the del keyword.
o To delete or remove all the items in just one statement, use the clear () function.
o Finally, to remove an entire dictionary from the memory, we can gain use the del
statement as del Dict_name.
o The syntax to use the del statement can be given as,
deldictionary_variable[key]
Example:
Creating Tuples:
[Link] = ("apple", "banana", "cherry")
print(thistuple)
output:
('apple', 'banana', 'cherry')
[Link] = ("a", "b", "c")
print(tuple)
output:
(‘a’,’b’,’c’)
Basic Tuple Operations :
Length len((1,2,3,4,5,6)) 6
print(i,end=’ ‘)
Tup2=(1,2,3,4,5)
print(Tup1>Tup2)
Maximum max(1,0,3,8,2,9) 9
Minimum min(1,0,3,8,2,9) 0
tuple() Function :
The Python tuple() function is a built-in function in Python that can be used to create
a tuple. A tuple is an ordered and immutable sequence type.
('a', 'b', 'c'', 'c')
Example:
l = [1,2,3]
print(tuple(l))
Output:
(1,2,3)
Indexing and Slicing in Tuples :
Indexing Tuples :
In Python, every tuple with elements has a position or index. Each element of the tuple can
be accessed or manipulated by using the index number.
Positive Indexing
Negative Indexing
Positive Indexing
In positive the first element of the tuple is at an index of 0 and the following elements are at
+1 and as follows.
Ex:
tuple =(5,2,9,7,5,8,1,4,3)
print(tuple(3))
print(tuple(7))
Output:
7
4
Negative Indexing
In negative indexing, the indexing of elements starts from the end of the tuple. That is the last
element of the tuple is said to be at a position at -1 and the previous element at -2 and goes
on till the first element.
Ex:
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(-2))
print(tuple(-8))
Output
4
2
Slicing tuples
Tuple slicing is a frequent practice in Python, and it is the most prevalent technique used by
programmers to solve efficient problems. Consider a Python tuple. You must slice a tuple in
order to access a range of elements in it. One method is to utilize the colon as a simple slicing
operator (:).
Syntax
Example 1
tuple=('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])
print(tuple[-1:-5:-2])
Output
This function returns the number of elements present in a tuple. Moreover, it is necessary to
provide a tuple to the len() function.
Ex:
>>> len(tup)
This function will help us to fund the number of times an element is present in the tuple.
Furthermore, we have to mention the element whose count we need to find, inside the count
function.
For example,
>>> [Link](22)
>>> [Link](54)
The tuple index() method helps us to find the index or occurrence of an element in a tuple. This
function basically performs two functions:
>>> print([Link](45))
>>> print([Link](890))
7
Example 2:
>>> print([Link](3.2))
This method takes a tuple as an input and returns a sorted list as an output. Moreover, it does not
make any changes to the original tuple.
EX:
>>> sorted(tup)
min(): gives the smallest element in the tuple as an output. Hence, the name is min().
For example,
>>> min(tup)
max(): Gives the largest element in the tuple as an output. Hence, the name is max().
>>> max(tup)
890
Sum:Gives the sum of the elements present in the tuple as an output.
>>> sum(tup)
1023
Relation between Tuples and Lists:
The key difference between the tuples and lists is that while the tuples are
immutable objects the lists are mutable. This means that tuples cannot be changed
while the lists can be modified.
Tuples are more memory efficient than the lists.
import sys
a_list = []
a_tuple = ()
a_list = ["Geeks", "For", "Geeks"]
a_tuple = ("Geeks", "For", "Geeks")
print([Link](a_list))
print([Link](a_tuple))
Output
96
80
tuple = ('a',10,'b',0.4,True)
print("Tuple:", tuple)
dictionary = {'a':True,10:'Ten'}
print("Dictionary:", dictionary)
output:
The zip() function returns a zip object, which is an iterator of tuples where the first item in
each passed iterator is paired together, and then the second item in each passed iterator are
paired together etc.
If the passed iterables have different lengths, the iterable with the least items decides the
length of the new iterator.
Syntax
iterable1, iterable2, iterable3 ... Iterable objects that will be joined together
Example:
x = zip(a, b)
output:
Sets:
Set is a mutable and unordered collection of items represented using curly brackets { }.
Set does not allow duplicate values.
Since sets are unordered, indexing cannot be done.
Like mathematical sets, python sets are also a powerful tool that have the ability to
calculate union, differences and intersections between other sets.
difference_update() -= Removes the items in this set that are also included
in another, specified set
intersection_update() &= Removes the items in this set that are not present in
other, specified set(s)
issubset() <= Returns whether another set contains this set or not
issuperset() >= Returns whether this set contains another set or not
update() |= Update the set with the union of this set and others
Frozenset:
Syntax
frozenset(iterable)
Example:
x = frozenset(mylist)
print(x)
Output:
def main():
print("Concatenated Tuple:")
print(concatenated_tuple)
if __name__ == "__main__":
main()
OUTPUT:
Concatenated Tuple:
('Alice', 25, '123 Street, CityA', 'ABC College', 'Bob', 28, '456 Avenue, CityB', 'XYZ College')
2. Write a program to count the number of vowels in a string (No controlflow allowed).
def count_vowels(s):
# Define the vowels in a set for quick lookup
vowels = {'a', 'e', 'i', 'o', 'u'}
return num_vowels
def main():
# Input string for testing
input_string = "Hello World, How are you?"
if __name__ == "__main__":
main()
Output:
Number of vowels in the string: 7
def main():
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Key to check
key_to_check = 'b'
if __name__ == "__main__":
main()
Output: The key 'b' exists in the dictionary.
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 78
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
def main():
# Existing dictionary
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
if __name__ == “__main__”:
main()
Output:
Updated Dictionary: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
def sum_dictionary_items(d):
total_sum = sum([Link]())
return total_sum
# Example usage
my_dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum of all items in the dictionary:", sum_dictionary_items(my_dict))
OUTPUT:
Sum of all items in the dictionary: 600
UNIT-IV
Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write
Data, Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV
Files, Python os and [Link] Modules.
Object-Oriented Programming: Classes and Objects, Creating Classes in Python,
Creating Objects in Python, Constructor Method, Classes with Multiple Objects, Class
Attributes Vs Data Attributes, Encapsulation, Inheritance, Polymorphism.
Sample Experiments
1. Write a program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source
must be lowered.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
4. Write a program to create, display, append, insert and reverse the order of the
items in the array.
5. Write a program to add, transpose and multiply two matrices.
6. Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like
circle, triangle, and square.
Files:
File is a collection of records. Files are stored in Secondary memory called permanent
memory. Secondary memory devices are: Hard disk, memory card, CD/DVD, Pen drive.
Before saving the file, it is temporally stored in RAM random access memory (temporary
memory).
In Python, files are treated in two modes as text or binary. The file may be in the text or
binary format, and each line of a file is ended with the special character.
Types of Files:
Computers store every file as a collection of 0s and 1s i.e., in binary form. Therefore, every
file is basically just a series of bytes stored one after the other. There are mainly two types of
data files — text file and binary file. A text file consists of human readable characters, which
can be opened by any text editor. On the other hand, binary files are made up of non-human
readable characters and symbols, which require specific programs to access its contents.
1. Text files
2. Binary Files
In ASCII, UNICODE or any other encoding scheme, the value of each character of the text
file is stored as bytes. So, while opening a text file, the text editor translates each ASCII value
and shows us the equivalent character that is readable by the human being. For example, the
ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor as the letter
“A‟ since the number 65 in ASCII character set represents “A‟. Each line of a text file is
terminated by a special character, called the End of Line (EOL).
For example, the default EOL character in Python is the newline (\n). However, other
characters can be used to indicate EOL. When a text editor or a program interpreter
encounters the ASCII equivalent of the EOL character, it displays the remaining file contents
starting from a new line. Contents in a text file are usually separated by whitespace, but
comma (,) and tab (\t) are also commonly used to separate values in a text file.
[Link] Files: Binary files are also stored in terms of bytes (0s and 1s), but unlike text
files, these bytes do not represent the ASCII values of characters. Rather, they represent the
actual content such as image, audio, video, compressed versions of other files, executable
files, etc.
These files are not human readable. Thus, trying to open a binary file using a text editor will
show some garbage values. We need specific software to read or write the contents of a
binary file. Binary files are stored in a computer in a sequence of bytes. Even a single bit
change can corrupt the file and make it unreadable to the supporting application.
Also, it is difficult to remove any error which may occur in the binary file as the stored
contents are not human readable. We can read and write both text and binary files through
Python programs.
[Link]('Hello, world!\n')
content = [Link]()
print(content)
1) Open
2) Read/write
3) Close
file_obj=open("filename","mode")
Ex: f=open('e:/[Link]','w')
1) r-read mode
6) a+ - both read/write
7) rb -read binary
8) wb -write binary
9) ab - append binary
2) Read/Write: After opening file user has to read or write data from file. For reading the
contents of file python contains the following methods:
[Link]()
[Link]()
[Link]()
For writing data into file python contains the following methods
1)write()
2)writelines()
3) close(): Last and final operation is closing, after finishing read/write, file has to close
by using „close()‟ method.
Syntax:
File_obj,close()
For reading data from file, Python contains the following methods:
1) read()
2) readline()
3) readlines()
Syntax:
[Link]()
OR
Program 1: (To read First ‘n’ characters from given input file)
try:
Input file:
f=open(file,'r')
[Link]()
Output:
2) readline():This function reads lines from that file and returns as a string. Syntax:
[Link]()
Program:
try:
f=open(file,'r')
print("First line from given file is:",[Link]()) #It reads first line
except FileNotFoundError as e:
Output:
3) readlines():This function returns a list where each element is single line of that file.
(Including \n and spaces)
Syntax:
[Link]()
Program:
try:
f=open(file,'r')
except FileNotFoundError as e:
Output:
File Write Operations: For Writing information into file Python contains the following
methods.
1)write()
2)writelines()
Syntax:
[Link](“String information”)
Program
try:
f=open(file,'a')
[Link]()
except FileNotFoundError as e:
Output:
2)writelines():This function is also used to post some information into file but it writes data
int the form list of strings.
Syntax:
Program:
try:
[Link](student)
[Link]()
except FileNotFoundError as e:
Output:
Above code automatically creates Ms-Excel file with the name „[Link]‟ in „D‟ Drive:
Reading and writing binary files in Python involves handling data in its raw byte format
rather than as text characters. This can be useful for working with non-text files such as
images, audio files, or any data that isn't meant to be interpreted as text.
To read from a binary file, you typically use the `'rb'` mode when opening the file. Here’s
how you can read from a binary file:
def read_binary_file(input_file):
try:
data = [Link]()
return data
except IOError:
return None
Ouput:
To write to a binary file, you typically use the `'wb'` mode when opening the file. Here’s how
you can write to a binary file:
try:
[Link](data)
except IOError:
write_binary_file(output_file, data)
try:
data = f_in.read()
f_out.write(data)
except IOError:
Pickle module
The `pickle` module in Python is used for serializing and deserializing Python objects.
Serialization is the process of converting Python objects into a byte stream, and
deserialization is the process of converting the byte stream back into Python objects. This is
useful for saving Python objects to a file, sending them over a network, or storing them in a
database.
Here's a simple example demonstrating how to use the `pickle` module to serialize and
deserialize Python objects:
import pickle
[Link](data, f)
```
import pickle
loaded_data = [Link](f)
Output:
Python Objects: `pickle` can handle most Python objects, including custom classes and
instances, nested data structures (lists, dictionaries), and more.
Security: Be cautious when unpickling data from untrusted sources, as `pickle` does not
provide secure deserialization and can execute arbitrary code.
Compatibility: Pickled files created with `pickle` in Python 2.x may not always be compatible
with Python 3.x due to differences in internal representation.
import pickle
class Person:
[Link] = name
[Link] = age
[Link](person, f)
loaded_person = [Link](f)
Reading and writing CSV (Comma Separated Values) files in Python is a common task,
especially when dealing with tabular data. Python provides a built-in `csv` module that
simplifies the process of reading from and writing to CSV files.
import csv
def read_csv_file(input_file):
data = []
reader = [Link](file)
[Link](row)
return data
Output:
import csv
writer = [Link](file)
[Link](row)
OS Module
The `os` module provides a way of using operating system-dependent functionality, such as
reading or writing to the file system, creating or deleting directories, and more.
Methods
import os
print([Link]())
[Link]('/path/to/directory')
print([Link]('.'))
[Link]('new_directory')
[Link]('new_directory')
[Link]('[Link]')
[Link]('old_name.txt', 'new_name.txt')
[Link]('ls -l')
[Link] Module
The `[Link]` module is a submodule of `os` and provides functions for interacting with the
file system pathnames.
Methods
print([Link]('[Link]'))
print([Link]('/path/to/[Link]')
print([Link]('/path/to/[Link]'))
print([Link]('[Link]'))
6. [Link](path):- Splits the pathname into a pair `(head, tail)` where `tail` is the last part
of the path and `head` is everything leading up to it.
print([Link]('/path/to/[Link]'))
7. [Link](path):- Splits the pathname into a pair `(root, ext)` where `ext` is the file
extension.
print([Link]('/path/to/[Link]'))
print([Link]('/path/to/[Link]'))
print([Link]('[Link]'))
print([Link]('/path/to/directory'))
1) Object: Object is runtime entity or real world entity. Every object contains some
properties, those properties are called as data members, and operations performed on those
data members are called as methods or member functions.
2)Class: class is a collection of object with similar features, and class is also called as
blueprint of an object, In Object oriented programming, object code is represented in the form
of classes. In python class is created with class keyword with the following syntax:
classclass_name:
var1=value var2=value
.........
self.var2=value
............
Ex:
class Student:
print([Link],[Link])
print([Link],[Link])
[Link]()
[Link]()
class Student:
def display(self):
[Link]()
[Link]
[Link]()
Output:
def getData(self,a,b):
self.a=a
self.b=b
def add(self):
self.c=self.a+self.b
def display(self):
print('addition is',self.c)
r=Addition()
[Link](x,y)
[Link]()
[Link]()
Output:
Constructor is a type of method used to initialize object members in a class. Generally there
are two types of constructors in Python. Constructor in Python is defined as init__(self)
method. ‘init(self)’ method prefix and suffix with two under scores. No separate calling for
constructors, they automatically called at the time of object creation.
Types of constructors:
• Default constructor.
• Parameterized constructor.
• Default Constructor: A constructor which do not take any parameter except „self‟ is
called as default constructor.
Syntax:
classclass_name:
Example Program:
class Student:
[Link]="John"
[Link]="Gudlavalleru"
[Link]='AP'
[Link]()
Output:
John Gudlavalleru AP
Syntax:
classclass_name:
Example program:
class Student:
[Link]=name
[Link]=address
[Link]=state
[Link]()
Class Attributes
Definition: Class attributes are attributes that are shared among all instances of a
class. They are defined within the class construction but outside any instance
methods.
Scope: They are shared by all instances of the class. Changing the value of a class
attribute will affect all instances of the class.
Definition: Instance attributes are attributes that are unique to each instance of a class.
They are defined within methods (usually __init__) and are prefixed with self.
Scope: They are specific to each instance. Changing the value of an instance attribute
will only affect that particular instance.
Data encapsulation: Wrapping up of data and functions into single unit is called as data
encapsulation. Python classes contain both data and methods.
Inheritance: The process of deriving one class from already existing class is called as
inheritance or a class shares the properties of another class is called as inheritance.
Already existing class is called as base class or super class or parent class, and newly
derived class is called as sub class or derived class or child class. In python two classes are
combined with parenthesis symbols ( ) for inheritance.
Syntax:
Python supports all types of inheritances including multiple, multipath and hybrid.
Types of inheritances:
E) Multipath Inheritance
F) Hybrid Inheritance.
A) Single Inheritance: Single inheritance contains only one base class and only one child
class.
Example program:
def display(self):
print('hai')
def show(self):
print('hello')
r=B()
[Link]()
[Link]()
B) Multiple inheritance: Basically Java does not support multiple inheritance, Only C++ is
the language supports multiple inheritance, Python also supports multipleinheritance of
classes. In multiple inheritance More number of base classes are derived to sub class.
Example Program:
class A:
def display1(self):
class B:
def display2(self):
class C:
def display3(self):
def display4(self):
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 100
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
r=D()
r.display1()
r.display2()
r.display3()
r.display4()
Output:
Example Program:
class A:
def display1(self):
class B(A):
def display2(self):
class C(A):
def display3(self):
class D(A):
def display4(self):
r2=C()
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 101
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
r3=D()
r1.display1()
r1.display2()
r2.display3()
r3.display4()
Output:
Example Program:
class A:
def display1(self):
class B(A):
def display2(self):
class C(B):
def display3(self):
class D(C):
def display4(self):
r1.display1()
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 102
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
r1.display2()
r1.display3()
r1.display4()
Output:
Example Program:
class A:
def display1(self):
class B(A):
def display2(self):
class C(A):
def display3(self):
def display4(self):
r1=D()
r1.display1()
r1.display2()
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 103
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
r1.display3()
r1.display4()
Example Program:
class A:
def display1(self):
def display2(self):
class C:
def display3(self):
def display4(self):
r1.display1()
r1.display2()
r1.display3()
r1.display4()
Output:
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 104
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
2) Operator Overloading.
3) Method Overriding
1) Method Overloading: Python does not allow same function name with multiple times. So
direct method overloading is not supported in Python. By specifying default arguments in a
function, python achieves method overloading.
Example program:
class Addition:
print('Addition is',a+b+c)
r=Addition()
Output:
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 105
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
Following are the list of Magic methods available to perform arithmetic operators
overloading.
class Addition:
defgetdata(self):
self.a=int(input('Enter a value'))
self.b=int(input('Enter b value'))
self.c=int(input('Enter c value'))
self.d=int(input('Enter d value'))
def add (self,x): #Operator overload with add () magic method x.a=self.a+x.a
x.b=self.b+x.b
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 106
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
x.c=self.c+x.c
x.d=self.d+x.d
return x
def display(self):
print(self.a,self.b,self.c,self.d)
r=Addition()
[Link]()
v=Addition()
[Link]()
x=Addition()
[Link]()
3) Method Overriding: It is runtime polymorphism mechanism, both derived class and base
class contains same method signature then that method is called as overriding method. In
such case derived class method overrides base class method.
Example program:
classAirtel:
defgetConnection(self):
classJio(Airtel):
Note: ‘@final’ annotation is used to prevent method overriding and class inheritance,
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 107
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
super()’ function in Python: „super()‟ function is used to access super class members into
derived class. Overridden methods and constructors are also accessed with „super()‟
function. Example program: (With Overridden methods)
class Airtel:
defgetConnection(self):
class Jio(Airtel):
super().getConnection()
[Link]()
Output:
Note: Base class constructors are also accessed in derived class with „super()‟ function.
[Link] a program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source must
be lowered.
words = [Link]().split()
[Link]()
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 108
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
[Link](word + '\n')
# Example usage:
sort_words(input_file, output_file)
output:
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 109
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
except FileNotFoundError as e:
print("File or directory not exist")
3. Python program to compute the number of characters, words and lines in a file.
OR
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 110
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
except FileNotFoundError as e:
print("File or directory not exist")
[Link] a program to create, display, append, insert and reverse the order of the
items in the array.
def create_array():
return []
def display_array(arr):
print("Array:", arr)
def reverse_array(arr):
return arr[::-1]
def main():
# Create array
arr = create_array()
display_array(arr)
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 111
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
append_to_array(arr, 2)
append_to_array(arr, 3)
display_array(arr)
if __name__ == "__main__":
main()
Output:
import numpy as np
def add_matrices(matrix1, matrix2):
if [Link] != [Link]:
raise ValueError("Matrices must have the same dimensions to be added.")
return matrix1 + matrix2
def transpose_matrix(matrix):
return [Link](matrix)
def multiply_matrices(matrix1, matrix2):
if [Link][1] != [Link][0]:
raise ValueError("Number of columns in the first matrix must equal the
number of rows in the second matrix.")
return [Link](matrix1, matrix2)
def main():
# Define two matrices
matrix1 = [Link]([[1, 2, 3],
[4, 5, 6]])
matrix2 = [Link]([[7, 8, 9],
[10, 11, 12]])
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 112
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
# Add matrices
try:
sum_matrix = add_matrices(matrix1, matrix2)
print("\nSum of Matrix 1 and Matrix 2:")
print(sum_matrix)
except ValueError as e:
print(e)
# Transpose matrices
transpose_matrix1 = transpose_matrix(matrix1)
transpose_matrix2 = transpose_matrix(matrix2)
print("\nTranspose of Matrix 1:")
print(transpose_matrix1)
print("\nTranspose of Matrix 2:")
print(transpose_matrix2)
# Define two matrices for multiplication
matrix3 = [Link]([[1, 2],
[3, 4],
[5, 6]])
matrix4 = [Link]([[7, 8],
[9, 10]])
print("\nMatrix 3:")
print(matrix3)
print("\nMatrix 4:")
print(matrix4)
# Multiply matrices
try:
product_matrix = multiply_matrices(matrix3, matrix4)
print("\nProduct of Matrix 3 and Matrix 4:")
print(product_matrix)
except ValueError as e:
print(e)
if __name__ == "__main__":
main()
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 113
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
import math
class Shape:
def area(self):
def perimeter(self):
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 114
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
class Circle(Shape):
[Link] = radius
def area(self):
def perimeter(self):
class Square(Shape):
self.side_length = side_length
def area(self):
return self.side_length ** 2
def perimeter(self):
return 4 * self.side_length
class Triangle(Shape):
self.a = a
self.b = b
self.c = c
def area(self):
def perimeter(self):
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 115
II [Link] I-Sem. PYTHON PROGRAMMING LAB D -23
def main():
shapes = [
Circle(5),
Square(4),
Triangle(3, 4, 5)
print(f"{shape.__class__.__name__}:")
if __name__ == "__main__":
main()
Output:
Dhanekula Institute of Engineering and Technology Dept. Of CSM A.Y: 2024-25 116