2-1 Python Manual
2-1 Python Manual
PYTHON PROGRAMMING
(Skill Enhancement Course)
LABORATORY MANUAL
SCHEME:R23
MISSION
M1: To provide strong fundamentals and value - based technical education for
Computer Science applications through effective teaching learning
methodologies.
M5: To inculcate problem solving and team building skills and promote
lifelong learning with a sense of societal and ethical responsibilities.
PROGRAM OUTCOMES (POS)
Engineering Graduates will be able to:
PO1.ENGINEERING KNOWLEDGE: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.
PO5.MODERN TOOL USAGE: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
PO6. THE ENGINEER AND SOCIETY: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7.ENVIRONMENT AND SUSTAINABILITY: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
PO8.ETHICS: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO12.LIFE-LONG LEARNING: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
Program Specific Outcomes (PSOs)
The Computer Science & Engineering graduate will
The Computer Engineering Graduates are able to understand,
analyze and develop computer programs in the areas related to
PSO-1 Professional Skills: algorithms, system software, multimedia, web design, big data
analytics and networking for efficient design of computer based
systems of varying complexity.
The Computer Engineering Graduates are able to employ modern
Successful Career computer languages, environments, and platforms in creating
PSO-2 and innovative career paths to be an entrepreneur and enthusiastic
Entrepreneurship: for higher studies/employability in the field of Computer Science
& Engineering.
Do’s
1. Please leave footwear outside the laboratory at the designated place.
2. Please keep your belongings such as bags in the designated place.
3. Students must present a valid ID card before entering the computer lab.
4. Maintain Discipline in the laboratory.
5. Work on the designated computers only.
6. Do keep your computer and workspace clean and organized.
7. Do save your work frequently to avoid data loss.
8. Do follow ethical guidelines and respect copyright when using digital resources.
9. Students must inform the in-charge Lecturer of any observed hardware or software
failures.
10. Turn off the respective systems and arrange the chairs before you leaving the laboratory.
Don’ts
1. Don’t touch the computer with a pen or pencil.
2. Don’t eat or drink near your computer.
3. Don’t touch wires or cables when the computer is on.
4. Do not install, uninstall or alter any software on the computer.
5. Students are not allowed to use personal Pen Drives, CDs, DVDs etc., in a Computer
Lab. Only prescribed official Pen Drives, CDs, DVDs etc. will be used in the Computer
Lab to avoid VIRUS in Computers.
6. The use of cell phones is prohibited in the computer lab.
7. Don’t forget to turn off your computer before leaving.
II Year B.Tech. CSE- I Sem
Course Objectives:
The main objectives of the course are to
• Introduce core programming concepts of Python programming language.
• Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries
• Implement Functions, Modules and Regular Expressions in Python Programming and to
create practical and contemporary applications using these
Course Outcomes:
After completion of the course, students will be able to
1. showcase adept command of Python syntax, deftly utilizing variables, data types, control
structures, functions, modules, and exception handling to engineer robust and efficient
code solutions. (L4)
2. apply Python programming concepts to solve a variety of computational problems (L3)
3. understand the principles of object-oriented programming (OOP) in Python, including
classes, objects, inheritance, polymorphism, and encapsulation, and apply them to design
and implement Python programs (L3)
4. become proficient in using commonly used Python libraries and frameworks such as
JSON, XML, NumPy, pandas (L2)
5. exhibit competence in implementing and manipulating fundamental data structures such
as lists, tuples, sets, dictionaries (L3)
UNTI-I:
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.
UNIT-II:
Functions: Built-In Functions, Commonly Used Modules, Function Definition and Calling the
function, return Statement and void Function, Scope and Lifetime of Variables, Default
Parameters, Keyword Arguments, *args and **kwargs, Command Line Arguments.
Strings: Creating and Storing Strings, Basic String Operations, Accessing Characters in String
by Index Number, String Slicing and Joining, String Methods, Formatting Strings.
Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In Functions
Used on Lists, List Methods, del Statement.
Sample Experiments:
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the substring is present in a given string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
12. Write a program to perform any 5 built-in functions by taking any list.
UNIT-III:
Dictionaries: Creating Dictionary, Accessing and Modifying key:value Pairs in Dictionaries,
Built-In Functions Used on Dictionaries, Dictionary Methods, del Statement.
Tuples and Sets: Creating Tuples, Basic Tuple Operations, tuple() Function, Indexing and
Slicing in Tuples, Built-In Functions Used on Tuples, Relation between Tuples and Lists,
Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set Methods, Frozenset.
Sample Experiments:
13. Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.
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 os.path 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:
18. Write a program to sort words in a file and put them in another file. The output files
should have only lower-case words, so any upper-case words from source must be
lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words and lines in a file.
21. Write a program to create, display, append, insert and reverse the order of the items in
the array.
22. Write a program to add, transpose and multiply two matrices.
23. 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.
UNIT-V:
Introduction to Data Science: Functional Programming, JSON and XML in Python, NumPy
with Python, Pandas.
Sample Experiments:
24. Python program to check whether a JSON string contains complex object or not.
25. Python Program to demonstrate NumPy arrays creation using array () function.
26. Python program to demonstrate use of ndim, shape, size, dtype.
27. Python program to demonstrate basic slicing, integer and Boolean indexing.
28. Python program to find min, max, sum, cumulative sum of array
29. Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame
and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib
Reference Books:
1. Gowri shankar S, Veena A., Introduction to Python Programming, CRC Press.
2. Python Programming, S Sridhar, J Indumathi, V M Hariharan, 2nd Edition, Pearson,
2024
3. Introduction to Programming Using Python, Y. Daniel Liang, Pearson.
UNIT– 1:
1. Write a program to find the largest element among three Numbers.
1 2. Write a Program to display all prime numbers within an interval 22-27
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.
UNIT- 2
7. Write a program to define a function with multiple return values.
2 8. Write a program to define a function using default arguments.
9. Write a program to find the length of the string without using 28-31
any library functions.
10. Write a program to check if the substring is present in a given
string or not.
11. Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
12. Write a program to perform any 5 built-in functions by taking
any list.
3 UNIT- 3
32-36
13. Write a program to create tuples (name, age, address, college)
for at least two members and concatenate the tuples and print the
concatenated tuples.
14. Write a program to count the number of vowels in a string (No
control flow allowed).
15. Write a program to check if a given key exists in a dictionary
or not.
16. Write a program to add a new key-value pair to an existing
dictionary.
17. Write a program to sum all the items in a given dictionary.
UNIT - 4 37-49
4 18. Write a program to sort words in a file and put them in another
file. The output files should have only lower-case words, so any
upper-case words from source must be lowered.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words
and lines in a file.
21. Write a program to create, display, append, insert and reverse
the order of the items in the array.
22. Write a program to add, transpose and multiply two matrices.
23. 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.
5 UNIT- 5 50-66
24. Python program to check whether a JSON string contains
complex object or not.
25. Python Program to demonstrate NumPy arrays creation using
array () function.
26. Python program to demonstrate use of ndim, shape, size, dtype.
27. Python program to demonstrate basic slicing, integer and
Boolean indexing.
28. Python program to find min, max, sum, cumulative sum of
array
29. Create a dictionary with at least five keys and each key
represent value as a list where this list contains at least ten values
and convert this dictionary as a pandas data frame and explore the
data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30. Select any two columns from the above data frame, and observe
the change in one attribute with respect to other attribute with
scatter and plot operations in matplotlib
UNTI-I: 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.
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.
1
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
• Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.
• Thrust Areas of Python
• Web Development. The programming language is used in back-end logic of web applications. ...
• Data Science. Data is the new oil and companies around the world have acknowledged it. ...
• Artificial intelligence and machine learning. ...
• Embedded applications. ...
Identifiers:
In Python, variables, functions, classes, modules and objects are identified using a name
known as an identifier. An identifier can start with an uppercase or lowercase character or
an underscore (_) followed by any number of underscores, letters and digits. All
identifiers in Python are case sensitive.
Example: weight=10
In the above example, weight is an identifier.
2
Keywords:
Keywords are the reserved words in Python. So keywords cannot be used as identifiers
or to name variables and functions. Few of the keywords are listed below.
Declaring a variable:
where var_name is the name given to the container holding the value specified as literal_value in
the syntax above.
Example: weight=10
In the above example, weight is the container holding the value 10 which can change during the
execution of the program.
Python may have data belonging to different types. Common data types used in programming are
listed below:
In the above example, no datatype was mentioned at the time of declaring variable. In Python,
the datatype of a variable is decided automatically at the time of execution based on the
value assigned to it. This is called as dynamic typing.
3
num=65 #line 1
num="A" #line 2
In line 1, variable num is assigned a value 65 which is an integer, so the data type
of num variable is integer in line 1.
In line 2, variable num is assigned a value “A” which is a string, so the data type of
the num variable is string in line 1.
Note: To check the datatype of the variable we can use type(var_name) which in turn returns
the datatype of the variable.
Example:
1. num=65
2. print(num,type(num))
3. num="A"
4. print(num,type(num))
Output:
65<class'int'>
A <class 'str'>
Python provides the input() built-in function to read an input from the user using the standard
input device (i.e. keyboard). The input() function always returns string data irrespective of
the type of data entered through the keyboard.
where,
var_name is the variable assigned with the string value which is read using input method.
Interactive statement is the statement displayed to the user expecting the response from them.
Example:
4
1. input_var=input("please enter the value")
2. print(input_var)
sample output:
Python provides the print() built-in function to display the output onto the standard output
device (i.e. Monitor)
where,
var_name1, var_name2 are the variable names or the literals you want to print or output
Statements
A statement is an instruction that the Python interpreter can execute. There are various types of
statements in Python, including:
1. Assignment Statement:
if x > 0:
print("x is positive")
elif x == 0:
5
print("x is zero")
else:
print("x is negative")
Loops:
• For Loop:
for i in range(5):
print(i)
While Loop:
while x > 0:
print(x)
x -= 1
• Function Definition:
def greet(name):
return f"Hello, {name}"
• Class Definition:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return "Woof!"
• Import Statement:
import math
from datetime import datetime
• Exception Handling:
try:
result = 10 / 0
except ZeroDivisionError:
6
print("Cannot divide by zero")
Expressions
An expression is a combination of values, variables, operators, and calls to functions that the
interpreter evaluates and produces another value. Expressions can be used wherever Python
expects a value
1. Arithmetic Expressions:
2 + 3 * 4 - 5 #
Results in 9
2. Boolean Expressions:
5 > 3 # True
x == 10 # Evaluates to True or False depending on the value of x
3. String Expressions:
4. Function Calls:
len("Python") # Results in 6
5. List Comprehensions:
6. Lambda Expressions:
Statements can contain expressions, and expressions can appear within statements.
For example:
x = 10 Assignment statement
y = x * 2 Assignment statement with an expression
7
if y > 15: Conditional statement with an expression
print("y is greater than 15") # Print statement
Understanding the difference between statements and expressions is crucial for writing efficient
and readable Python code. Statements control the flow of the program, while expressions
compute values
Variables:
In Python, variables are used to store data values. A variable is essentially a name that refers to a
value. Python is dynamically typed, which means that you don't have to declare the type of a
variable when you create one. The type of the variable is determined by the value assigned to it.
Here's a detailed overview of variables in Python:
To create a variable, you simply assign a value to a name using the = operator.
Example:
x = 5
name = "Alice"
is_active = True
user_name = "Alice"
user1 = "Bob"
_private_variable = "secret"
name = "Alice"
Name = "Bob"
8
5. Avoid using Python reserved keywords as variable names.
Types of Variables
Python variables can hold different types of values, and the type is determined at runtime. Here
are some common types:
1. Integer:
age = 30
2. Float:
price = 19.99
3. String:
name = "Alice"
4. Boolean:
is_active = True
5. List:
6. Tuple:
7. Dictionary:
8. Set:
unique_numbers = {1, 2, 3, 4, 5}
Variable Scope
The scope of a variable determines where in the code a variable can be accessed.
9
1. Local Scope: Variables created inside a function belong to the local scope of that
function and can only be used inside that function.
def my_function():
x = 10 # Local scope
print(x)
my_function()
print(x) # This will cause an error because x is not defined outside
the function
2. Global Scope: Variables created outside of all functions are in the global scope and can
be used anywhere in the code.
y = 20 # Global scope
def my_function():
print(y)
my_function()
print(y)
3. Global Keyword: To modify a global variable inside a function, you can use the global
keyword.
z = 30
def my_function():
global z
z = 40
my_function()
print(z) # This will print 40
Sometimes, you may need to convert a variable from one type to another.
1. Integer to String:
x = 10
y = str(x) # y is now "10"
2. String to Integer:
a = "5"
10
b = int(a) # b is now 5
3. String to Float:
c = "3.14"
d = float(c) # d is now 3.14
4. Integer to Float:
e = 7
f = float(e) # f is now 7.0
Operators:
In Python, operators are special symbols or keywords that are used to perform operations on
variables and values. Python provides a variety of operators that can be categorized into several
groups based on their functionality:
1. Arithmetic Operators
• Addition (+)
x = 5
y = 3
print(x + y) # Output: 8
• Subtraction (-)
print(x - y) # Output: 2
• Multiplication (*)
print(x * y) # Output: 15
• Division (/)
11
print(x // y) # Output: 1
• Modulus (%)
print(x % y) # Output: 2
• Exponentiation (**)
2. Comparison Operators
These operators are used to compare two values and return a Boolean result (True or False).
• Equal to (==)
3. Logical Operators
• AND (and)
12
• OR (or)
• NOT (not)
4. Assignment Operators
• Assignment (=)
z = 10
z += 5 # z is now 15
z -= 3 # z is now 12
z *= 2 # z is now 24
z /= 4 # z is now 6.0
z %= 2 # z is now 1.0
13
5. Bitwise Operators
• AND (&)
• OR (|)
• XOR (^)
• NOT (~)
6. Membership Operators
• IN (in)
list = [1, 2, 3, 4, 5]
print(3 in list) # Output: True
7. Identity Operators
These operators are used to compare the memory locations of two objects.
14
• IS (is)
a = [1, 2, 3]
b = a
print(a is b) # Output: True
c = [1, 2, 3]
print(a is not c) # Output: True
Understanding and using these operators effectively is crucial for performing various operations
and manipulating data in Python.
In Python, operator precedence and associativity determine the order in which operators are
evaluated in expressions.
Precedence
Operator precedence determines which operator is evaluated first in an expression with multiple
operators. Operators with higher precedence are evaluated before operators with lower
precedence.
1. Exponentiation: **
2. Unary plus, unary minus, and bitwise NOT: +, -, ~
3. Multiplication, division, floor division, and modulus: *, /, //, %
4. Addition and subtraction: +, -
5. Bitwise shift operators: <<, >>
6. Bitwise AND: &
7. Bitwise XOR: ^
8. Bitwise OR: |
9. Comparisons, including membership and identity tests: ==, !=, >, <, >=, <=, is, is not, in,
not in
10. Boolean NOT: not
11. Boolean AND: and
12. Boolean OR: or
15
Associativity
Associativity determines the order in which operators of the same precedence are evaluated.
Most operators in Python are left-associative, meaning they are evaluated from left to right. The
exponentiation operator (**) is right-associative, meaning it is evaluated from right to left.
• Exponentiation (**)
• Unary plus, unary minus, and bitwise NOT (+, -, ~)
• Boolean NOT (not)
Examples
x = 2 + 3 * 4
print(x) # Output: 14
In this example, multiplication (*) has higher precedence than addition (+), so 3 * 4 is evaluated
first, resulting in 12, and then 2 + 12 gives 14.
x = (2 + 3) * 4
print(x) # Output: 20
Parentheses have the highest precedence, so 2 + 3 is evaluated first, resulting in 5, and then 5 *
4 gives 20.
16
Example 3: Associativity
x = 2 ** 3 ** 2
print(x) # Output: 512
x = 5 - 3 + 2
print(x) # Output: 4
Both subtraction and addition are left-associative and have the same precedence. So, 5 - 3 is
evaluated first, resulting in 2, and then 2 + 2 gives 4.
Understanding operator precedence and associativity is crucial for writing clear and correct
Python code, especially in complex expressions. When in doubt, using parentheses to explicitly
define the evaluation order can help ensure your code behaves as expected.
In Python, data types specify the type of value a variable holds. Python has several built-in data
types that are used to handle different kinds of data. Here's a comprehensive overview of the
most common data types in Python:
1. Integer (int):
o Whole numbers, positive or negative, without decimals.
o Example:
python
Copy code
x = 10
y = -5
2. Float (float):
o Numbers, positive or negative, containing one or more decimals.
o Example:
python
Copy code
pi = 3.14
gravity = 9.81
17
3. String (str):
o Sequence of characters enclosed in single, double, or triple quotes.
o Example:
python
Copy code
name = "Alice"
greeting = 'Hello, world!'
paragraph = """This is a paragraph
that spans multiple lines."""
4. Boolean (bool):
o Represents one of two values: True or False.
o Example:
python
Copy code
is_active = True
has_passed = False
1. List (list):
o Ordered collection of items which can be of different types. Lists are mutable.
o Example:
python
Copy code
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", 3.14, True]
2. Tuple (tuple):
o Ordered collection of items which can be of different types. Tuples are immutable.
o Example:
python
Copy code
point = (10, 20)
colors = ("red", "green", "blue")
3. Set (set):
o Unordered collection of unique items.
o Example:
18
python
Copy code
unique_numbers = {1, 2, 3, 4, 5}
letters = {"a", "b", "c"}
4. Dictionary (dict):
o Unordered collection of key-value pairs.
o Example:
1. NoneType (None):
o Represents the absence of a value or a null value.
o Example:
x = None
2. Range (range):
o Represents an immutable sequence of numbers, commonly used for looping a specific
number of times in for loops.
o Example:
Type Conversion
Python allows you to convert values from one data type to another using type conversion
functions.
1. Integer to String:
x = 10
y = str(x) # y is now "10"
2. String to Integer:
a = "5"
b = int(a) # b is now 5
3. String to Float:
c = "3.14"
19
d = float(c) # d is now 3.14
4. Float to Integer:
e = 7.89
f = int(e) # f is now 7
5. List to Tuple:
list_example = [1, 2, 3]
tuple_example = tuple(list_example) # tuple_example is now (1, 2, 3)
6. Tuple to List:
tuple_example = (1, 2, 3)
list_example = list(tuple_example) # list_example is now [1, 2, 3]
7. List to Set:
list_example = [1, 2, 2, 3]
set_example = set(list_example) # set_example is now {1, 2, 3}
Understanding and effectively using these data types is fundamental to programming in Python.
Each data type has its own properties and is suited for different kinds of tasks.
Indentation: Indentation refers to the spaces or tabs used at the beginning of a line of code to
indicate that it is a part of a block of code. It is a crucial aspect of programming, especially in
languages like Python where indentation is used to define the structure and flow of the program.
Importance of Indentation
Comments: In Python, comments are used to explain code and make it more readable. They are
ignored by the Python interpreter and do not affect the execution of the program. There are two
main types of comments in Python: single-line comments and multi-line comments.
Single-Line Comments
Single-line comments start with the hash character (#) and extend to the end of the line.
20
This is a single-line comment
print("Hello, World!")
Multi-Line Comments
While Python does not have a specific syntax for multi-line comments, you can use multiple
single-line comments or triple-quoted strings (which are generally used for docstrings) to achieve
the same effect.
Multi-Line Comments
While Python does not have a specific syntax for multi-line comments, you can use multiple
single-line comments or triple-quoted strings (which are generally used for docstrings) to achieve
the same effect.
print("Hello, World!")
"""
"""
print("Hello, World!")
Docstrings
21
Docstrings are a special type of comment used to document modules, classes, functions, and
methods. They are written using triple quotes and are the first statement in the object being
documented.
def greet(name):
Parameters:.
Returns:
None
"""
print(f"Hello, {name}!")
greet("Alice")
READING INPUT
Reading input in Python can be done using the built-in input() function. This function reads a
line from the standard input (usually from the keyboard) and returns it as a string.
Basic Usage
The input() function can be used to prompt the user for input.
Example:
name = input("Enter your name: ")
print(f"Hello, {name}!")
22
23
UNIT-1
Program 01: Write a program to find the largest element among three Numbers
Source Code:
num1 = 10
• num2 = 14
• num3 = 12
•
• #num1 = float(input("Enter first number: "))
• #num2 = float(input("Enter second number: "))
• #num3 = float(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:
The Largest number is 14
Program 2: Write a Program to display all prime numbers within an interval
Source code:
lower = 900
upper = 1000
if num > 1:
if (num % i) == 0:
24
break
else:
print(num)
Output:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
Program 03
Source code:
x=5
y = 10
25
#y = input('Enter value of y: ')
Output:
Program 04
Source code:
i) Arithmetic Operators
a = 21
b = 10
# Addition
print ("a + b : ", a + b)
# Subtraction
print ("a - b : ", a - b)
# Multiplication
print ("a * b : ", a * b)
# Division
print ("a / b : ", a / b)
# Modulus
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)
26
Output
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Relational Operators:
Source code:
a=4
b=5
# Equal
print ("a == b : ", a == b)
# Not Equal
print ("a != b : ", a != b)
# Greater Than
print ("a > b : ", a > b)
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Output:
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
27
iii)Assignment Operators
# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
print ("a //= 3 : ", a)
Output:
a += 5 : 15
a -= 5 : 10
a *= 5 : 50
a /= 5 : 10.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
Program 5:
28
print("Addition of two complex numbers : ",(4+3j)+(3-7j))
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
print("Multiplication of two complex numbers : ",(4+3j)*(3-7j))
print("Division of two complex numbers : ",(4+3j)/(3-7j))
Output:
Addition of two complex numbers : (7-4j)
Subtraction of two complex numbers : (1+10j)
Multiplication of two complex numbers : (33-19j)
Division of two complex numbers : (-0.15517241379310348+0.6379310344827587j)
Program 06:
Write a program to print multiplication table of a given number.
num = 9
Output:
9x1=9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90
29
UNIT-2
Program no.7
Write a program to define a function with multiple return values.
def name():
return "John","Armin"
Program no. 8:
sum = a + b
print('Sum:', sum)
add numbers(2, 3)
Output: Sum: 5
Program 9: Write a program to find the length of the string without using any library
functions.
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
30
Output:
Program 10:
Source code:
substring="python"
if substring in string:
print("Yes")
else:
print("False")
Output:
Yes
Program 11:
def main():
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
31
print("After addition (append 6):", my_list)
if __name__ == "__main__":
main()
Output:
Program no.12
def main():
# Example list
my_list = [3, 1, 7, 2, 5]
32
# 2. max() - Maximum element in the list
sorted_list = sorted(my_list)
if __name__ == "__main__":
main()
Output:
33
UNIT-3
Program 13:
Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
def main():
member1 = ('Alice', 25, '123 Main St, City A', 'ABC University')
member2 = ('Bob', 22, '456 Elm St, City B', 'XYZ College')
# Concatenating tuples
print("Concatenated Tuple:")
print(concatenated_tuple)
if __name__ == "__main__":
main()
Output:
Concatenated Tuple:
('Alice', 25, '123 Main St, City A', 'ABC University', 'Bob', 22, '456 Elm St, City B', 'XYZ
College')
Program 14:
Write a program to count the number of vowels in a string (No control flow allowed).
Source code:
def count_vowels(s):
34
# Define vowels as a set
return vowel_count
def main():
# Input string
num_vowels = count_vowels(input_string)
if __name__ == "__main__":
main()
Output:
Program 15:
Source code:
35
def check_key(dictionary, key):
if key in dictionary:
else:
# Example usage:
check_key(my_dict, 'b') .
check_key(my_dict, 'd')
Output:
Program 16:
dictionary[key] = value
return dictionary
# Example dictionary
my_dict = {
"name": "Alice",
"age": 30,
36
# New key-value pair to add
new_key = "occupation"
new_value = "Engineer"
print(updated_dict)
Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'occupation': 'Engineer'}
Program 17:
def sum_dictionary_items(dictionary):
return sum(dictionary.values())
my_dict = {
"item1": 10,
"item2": 20,
"item3": 30,
"item4": 40
37
total_sum = sum_dictionary_items(my_dict)
Output:
38
UNIT-4
Program 18:
Write a program to sort words in a file and put them in another file. The output files
should have only lower-case words, so any upper-case words from source must be lowered.
try:
text = src.read()
words = text.split()
sorted_words = sorted(lower_words)
dest.write(word + '\n')
except FileNotFoundError:
except Exception as e:
39
# Example usage
source_file = 'input.txt'
destination_file = 'output.txt'
sort_words_in_file(source_file, destination_file)
Output
apple
apple
banana
banana
grape
mango
orange
Program 19:
def print_lines_in_reverse(filename):
try:
reversed_line = line.rstrip('\n')[::-1]
print(reversed_line)
except FileNotFoundError:
40
except Exception as e:
# Example usage
filename = 'input.txt'
print_lines_in_reverse(filename)
Output
Hello World
Python Programming
File Handling
dlroW olleH
gnimmargorP nohtyP
gnildnaH eliF
Program 20:
Python program to compute the number of characters, words and lines in a file.
def count_file_stats(filename):
try:
lines = file.readlines()
num_lines = len(lines)
num_words = 0
num_chars = 0
41
for line in lines:
num_chars += len(line)
num_words += len(line.split())
print(f"Lines : {num_lines}")
print(f"Words : {num_words}")
print(f"Characters : {num_chars}")
except FileNotFoundError:
except Exception as e:
# Example usage
filename = 'input.txt'
count_file_stats(filename)
Output
Python is fun.
Lines :2
Words :8
Characters : 52
Program 21:
42
Write a program to create, display, append, insert and reverse the order of the items in the
array.
print("Original Array:")
print(arr.tolist())
arr.append(60)
print(arr.tolist())
print(arr.tolist())
arr.reverse()
print(arr.tolist())
43
Output
Original Array:
Program 22:
A=[
[1, 2, 3],
[4, 5, 6]
B=[
[7, 8, 9],
44
# Function to add two matrices
result = []
for i in range(len(X)):
row = []
for j in range(len(X[0])):
row.append(X[i][j] + Y[i][j])
result.append(row)
return result
def transpose_matrix(M):
rows = len(M)
cols = len(M[0])
result = []
for i in range(len(X)):
row = []
for j in range(len(Y[0])):
val = 0
for k in range(len(Y)):
45
row.append(val)
result.append(row)
return result
# Transpose matrices
transpose_A = transpose_matrix(A)
transpose_B = transpose_matrix(B)
# Display results
print("Matrix A:")
for row in A:
print(row)
print("\nMatrix B:")
for row in B:
print(row)
print("\nA + B:")
print(row)
46
print("\nTranspose of A:")
print(row)
print("\nTranspose of B:")
print(row)
print("\nA * Transpose(B):")
print(row)
Output
Matrix A:
[1, 2, 3]
[4, 5, 6]
Matrix B:
[7, 8, 9]
A + B:
47
Transpose of A:
[1, 4]
[2, 5]
[3, 6]
Transpose of B:
[7, 10]
[8, 11]
[9, 12]
A * Transpose(B):
[50, 68]
[122, 167]
Program 23:
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.
import math
# Base class
class Shape:
def area(self):
return 0
def perimeter(self):
return 0
48
# Subclass for Circle
class Circle(Shape):
self.radius = radius
def area(self):
def perimeter(self):
class Square(Shape):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Subclass for Triangle (Assuming a simple triangle with three sides given)
class Triangle(Shape):
49
def __init__(self, a, b, c): # a, b, c are sides of the triangle
self.a = a
self.b = b
self.c = c
def perimeter(self):
def area(self):
# Heron's formula
s = self.perimeter() / 2
# Example usage
circle = Circle(5)
square = Square(4)
triangle = Triangle(3, 4, 5)
print("Circle:")
print("\nSquare:")
print("Area:", square.area())
print("Perimeter:", square.perimeter())
50
print("\nTriangle:")
print("Perimeter:", triangle.perimeter())
Output
Circle:
Area: 78.54
Perimeter: 31.42
Square:
Area: 16
Perimeter: 16
Triangle:
Area: 6.0
Perimeter: 12
51
UNIT-5
Program 24:
Python program to check whether a JSON string contains complex object or not.
import json
def contains_complex_object(json_str):
try:
data = json.loads(json_str)
def is_complex(obj):
return True
return False
return False
def check_recursive(obj):
if is_complex(obj):
if isinstance(obj, dict):
if check_recursive(value):
return True
52
if check_recursive(item):
return True
return True
return False
return check_recursive(data)
except json.JSONDecodeError:
return False
# Test Examples
Output
53
Example 3 (Nested Dict): True
Program 25:
import numpy as np
# 1. Create a 1D array
print("1D Array:")
print(arr1)
print("\n2D Array:")
print(arr2)
# 3. Create a 3D array
arr3 = np.array([
])
print("\n3D Array:")
print(arr3)
54
# 4. Array with specified data type
print(arr4)
Output
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
[1 2 3]
Program 26:
import numpy as np
55
# Create a 2D array (matrix)
print("Array:")
print(arr)
Output
Array:
[[1 2 3]
[4 5 6]]
56
Number of dimensions (ndim): 2
Program 27:
import numpy as np
print("Original Array:")
print(arr)
print(sliced_arr)
print(int_indexed_arr)
57
# 3. Boolean Indexing - Extract elements greater than 5
bool_indexed_arr = arr[bool_mask]
print(bool_indexed_arr)
Output
Original Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[2 3 4]
[6 7 8]]
[3 8]
[ 6 7 8 9 10 11 12]
Program 28:
import numpy as np
58
arr = np.array([1, 2, 3, 4, 5, 6])
min_val = np.min(arr)
max_val = np.max(arr)
sum_val = np.sum(arr)
cumulative_sum = np.cumsum(arr)
print("Array:", arr)
Output
Array: [1 2 3 4 5 6]
Minimum value: 1
Maximum value: 6
59
Sum of array: 21
Program 29:
Create a dictionary with at least five keys and each key represent value as a list where this
list contains at least ten values and convert this dictionary as a pandas data frame and
explore the data through the data frame as follows:
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Hannah', 'Isaac', 'Jack'],
'Age': [23, 34, 45, 23, 22, 34, 25, 28, 29, 30],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'San Antonio', 'San Diego',
'Dallas', 'Austin', 'Jacksonville'],
'Salary': [50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000, 130000, 140000],
'Department': ['HR', 'IT', 'Sales', 'Marketing', 'Finance', 'IT', 'HR', 'Sales', 'Marketing', 'Finance']
df = pd.DataFrame(data)
print(df.head())
60
# b) Data selection operations
print("\n'Name' column:")
print(df['Name'])
print(df[['Name', 'Age']])
print(df.iloc[2])
# Select a specific value (e.g., value in the 'City' column for row with index 5)
print(df.at[5, 'City'])
# Filter the data (e.g., select rows where 'Age' is greater than 30)
# Select a specific row and column using .loc (e.g., Age of person named 'Alice')
print("\nAge of Alice:")
61
print(df.loc[df['Name'] == 'Alice', 'Age'])
Output
'Name' column:
0 Alice
1 Bob
2 Charlie
3 David
4 Eva
5 Frank
6 Grace
7 Hannah
8 Isaac
9 Jack
Name Age
62
0 Alice 23
1 Bob 34
2 Charlie 45
3 David 23
4 Eva 22
5 Frank 34
6 Grace 25
7 Hannah 28
8 Isaac 29
9 Jack 30
Name Charlie
Age 45
City Chicago
Salary 70000
Department Sales
San Antonio
63
2 Charlie 45 Chicago 70000 Sales
Age of Alice:
0 23
Program 30:
Select any two columns from the above data frame, and observe the change in one attribute
with respect to other attribute with scatter and plot operations in matplotlib
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Hannah', 'Isaac', 'Jack'],
'Age': [23, 34, 45, 23, 22, 34, 25, 28, 29, 30],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix', 'San Antonio', 'San Diego',
'Dallas', 'Austin', 'Jacksonville'],
'Salary': [50000, 60000, 70000, 80000, 90000, 100000, 110000, 120000, 130000, 140000],
'Department': ['HR', 'IT', 'Sales', 'Marketing', 'Finance', 'IT', 'HR', 'Sales', 'Marketing', 'Finance']
64
# Convert dictionary to Pandas DataFrame
df = pd.DataFrame(data)
age = df['Age']
salary = df['Salary']
plt.figure(figsize=(10, 5))
# Scatter plot
plt.xlabel('Age')
plt.ylabel('Salary')
plt.grid(True)
plt.xlabel('Age')
plt.ylabel('Salary')
65
plt.grid(True)
plt.tight_layout()
plt.show()
66