DEPARTMENT OF
COMPUTER SCIENCE
PRACTICAL RECORD
Name :
Register Number :
Subject Code : 23UCSCCP01
Subject Title : _ Python Lab
Year / Sem :
ACADEMIC YEAR: 2023 – 2024
Certificate
This is to certify that the practical record “Python Lab” is a bonafide
work done by
Reg. No. _ submitted to the Department of
Computer Applications, during the academic year 2023 - 2024.
SUBJECT IN-CHARGE HEAD OF THE DEPARTMENT
(Mrs.M.SNEHA)
Submitted for University Practical Examination held on
INTERNAL EXAMINER EXTERNAL EXAMINER
INDEX
S.No. DATE TITLE PAGE NO. SIGNATURE
Variables, Constants, and I/O
1 Statements
2 Operators in Python
3 Conditional Statements
4 Loops
Jump Statements
5
6 Functions
7 Recursion
8 Arrays
Strings
9
10 Modules
Lists
11
12 Tuples
13 Dictionaries
14 File Handling
/
Ex 1: Variables, Constants, and I/O Statements
Aim:
To understand the concept of variables, constants, and
input/output statements in Python.
Algorithm:
1. Start
2. Declare and initialize variables.
3. Print a welcome message.
4. Prompt the user to enter their name.
5. Read the user's name from the keyboard.
6. Print a personalized greeting message using the user's name.
7. Perform arithmetic operations using variables and constants.
8. Print the results of the arithmetic operations.
9. End
Program:
# Variable, Constants, and I/O Statements
# Constants
PI = 3.14159
# Variables
radius = 0
area = 0
# Print welcome message
print("Welcome to the Python Lab!")
# Read user's name
name = input("Enter your name: ")
# Print personalized greeting
print("Hello,", name + "!")
# Read the radius from the user
radius = float(input("Enter the radius of a circle: "))
# Calculate area
area = PI * radius * radius
# Print the area
print("The area of the circle is:", area)
# Perform arithmetic operations
result = area * 2
result += 10
result -= 5
# Print the result
print("The final result is:", result)
Output:
Welcome to the Python Lab!
Enter your name: John
Hello, John!
Enter the radius of a circle: 5
The area of the circle is: 78.53975
The final result is: 162.0795
Result:
The program demonstrates the use of variables, constants, and I/O
statements in Python. It calculates the area of a circle and performs
arithmetic operations on the result.
Ex 2: Operators in Python
Aim:
To understand and utilize various operators in Python.
Algorithm:
1. Start
2. Declare variables.
3. Perform arithmetic operations using operators.
4. Perform comparison operations.
5. Perform logical operations.
6. Perform assignment operations.
7. End
Program:
# Operators in Python
# Arithmetic Operators
x = 10
y=3
print("Arithmetic Operators:")
print("x + y =", x + y)
print("x - y =", x - y)
print("x * y =", x * y)
print("x / y =", x / y)
print("x % y =", x % y)
print("x ** y =", x ** y)
print("x // y =", x // y)
# Comparison Operators
a=5
b=8
print("\n Comparison Operators:")
print("a == b is", a == b)
print("a != b is", a != b)
print("a > b is", a > b)
print("a < b is", a < b)
print("a >= b is", a >= b)
print("a <= b is", a <= b)
# Logical Operators
p = True
q = False
print("\n Logical Operators:")
print("p and q is", p and q)
print("p or q is", p or q)
print("not p is", not p)
# Assignment Operators
x = 10
x += 5
print("\n Assignment Operators:")
print("x += 5, x =", x)
y=7
y *= 2
print("y *= 2, y =", y)
Output:
Arithmetic Operators:
x + y = 13
x- y = 7
x * y = 30
x / y = 3.3333333333333335
x%y=1
x ** y = 1000
x // y = 3
Comparison Operators:
a == b is False
a != b is True
a > b is False
a < b is True
a >= b is False
a <= b is True
Logical Operators:
p and q is False
p or q is True
not p is False
Assignment Operators:
x += 5, x = 15
y *= 2, y = 14
Result:
The program demonstrates the usage of arithmetic, comparison,
logical, and assignment operators in Python.
Ex 3: Conditional Statements
Aim:
To understand the concept of conditional statements in Python.
Algorithm:
1. Start
2. Declare variables.
3. Prompt the user to enter a number.
4. Read the number from the user.
5. Check if the number is positive, negative, or zero using if-elif-else
statements.
6. Print the corresponding message based on the number's value.
7. End
Program:
# Conditional Statements
# Prompt the user to enter a number
num = float(input("Enter a number: "))
# Check if the number is positive, negative, or zero
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Output 1:
Enter a number: 5
The number is positive.
Output 2:
Enter a number: -2
The number is negative.
Output 3:
Enter a number: 0
The number is zero
Result:
The program determines whether a given number is positive,
negative, or zero using conditional statements.
Ex 4: Loops
Aim:
To understand and utilize loops in Python.
Algorithm:
1. Start
2. Initialize a variable.
3. Use a while loop to iterate until a condition is met.
4. Perform desired operations within the loop.
5. Update the variable.
6. Print the result.
7. End
Program:
# Loops
# Initialize the variable
count = 1
# Use a while loop to iterate until the count reaches 5
while count <= 5:
print("Count:", count)
count += 1
# Print the result
print("Loop finished.")
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Loop finished.
Result:
The program demonstrates the usage of a while loop to iterate a
specific number of times.
Ex 5: Jump Statements
Aim:
To understand and utilize jump statements in Python.
Algorithm:
1. Start
2. Use a for loop to iterate over a range of numbers.
3. Check for a condition using an if statement.
4. Use a jump statement to alter the flow of the loop.
5. Print the result.
6. End
Program:
# Jump Statements
# Use a for loop to iterate over a range of numbers
for num in range(1, 6):
# Check if the number is divisible by 3
if num % 3 == 0:
# Skip the current iteration
continue
# Print the number
print("Number:", num)
# Print the result
print("Loop finished.")
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Loop finished.
Result:
The program demonstrates the usage of a jump statement (continue)
to skip a specific iteration within a loop.
Ex 6: Functions
Aim:
To understand and utilize functions in Python.
Algorithm:
1. Start
2. Define a function.
3. Call the function.
4. Pass arguments to the function.
5. Perform desired operations within the function.
6. Return a value from the function.
7. Print the result.
8. End
Program:
# Functions
# Define a function to calculate the square of a number
def square(number):
result = number ** 2
return result
# Call the function and print the result
num = 5
square_result = square(num)
print("Square of", num, "is:", square_result)
Output:
Square of 5 is: 25
Result: The program demonstrates the usage of functions to calculate the
square of a number.
Ex 7: Recursion
Aim:
To understand and utilize recursion in Python.
Algorithm:
1. Start
2. Define a recursive function.
3. Define a base case for the recursion.
4. Call the function recursively with a modified parameter.
5. Perform desired operations within the function.
6. Return a value.
7. Print the result.
8. End
Program:
# Recursion
# Define a recursive function to calculate the factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Call the function and print the result
num = 5
factorial_result = factorial(num)
print("Factorial of", num, "is:", factorial_result)
Output:
Factorial of 5 is: 120
Result:
The program demonstrates the usage of recursion to calculate
Ex 8: Arrays
Aim:
To understand and utilize arrays in Python.
Algorithm:
1. Start
2. Import the array module.
3. Create an array.
4. Initialize the array with elements.
5. Access and modify array elements.
6. Print the array.
7. End
Program:
# Arrays
import array as arr
# Create an array of integers
numbers = arr.array('i', [1, 2, 3, 4, 5])
# Access and modify array elements
print("Array elements:")
for num in numbers:
print(num)
numbers[2] = 6
# Print the modified array
print("Modified array:")
for num in numbers:
print(num)
Output:
Array elements:
Modified array:
Result:
The program demonstrates the usage of arrays in Python to store
and manipulate a collection of elements.
Ex 9: Strings
Aim:
To understand and utilize strings in Python.
Algorithm:
1. Start
2. Initialize a string variable.
3. Access and modify characters in the string.
4. Perform string concatenation.
5. Perform string slicing.
6. Print the result.
7. End
Program:
# Strings
# Initialize a string variable
message = "Hello, World!"
# Access and modify characters in the string
print("First character:", message[0])
print("Modified string:", message[:5] + "Python")
# Perform string concatenation
name = "Alice"
greeting = "Hello, " + name + "!"
print(greeting)
# Perform string slicing
substring = message[7:12]
print("Substring:", substring)
Output:
First character: H
Modified string: HelloPython
Hello, Alice!
Substring: World
Result:
The program demonstrates the usage of strings in Python, including
accessing and modifying characters, string concatenation, and string
slicing.
Ex 10: Modules
Aim:
To understand and utilize modules in Python.
Algorithm:
1. Start
2. Import a module.
3. Use functions or variables from the module.
4. Print the result.
5. End
Program:
# Modules
# Import the math module
import math
# Use functions from the math module
print("Square root of 16:", math.sqrt(16))
print("Value of pi:", math.pi)
print("Factorial of 5:", math.factorial(5))
Output:
Square root of 16: 4.0
Value of pi: 3.141592653589793
Factorial of 5: 120
Result:
The program demonstrates the usage of modules in Python,
specifically the math module, to perform mathematical operations.
Ex 11: Lists
Aim:
To understand and utilize lists in Python.
Algorithm:
1. Start
2. Create a list with elements.
3. Access and modify list elements.
4. Perform list operations such as appending, extending, and removing
elements.
5. Print the result.
6. End
Program:
# Lists
# Create a list
fruits = ["apple", "banana", "orange"]
# Access and modify list elements
print("First fruit:", fruits[0])
fruits[1] = "grape"
# Perform list operations
fruits.append("mango")
fruits.extend(["pineapple", "watermelon"])
fruits.remove("orange")
# Print the list
print("Modified list:", fruits)
Output:
First fruit: apple
Modified list: ['apple', 'grape', 'banana', 'mango', 'pineapple',
'watermelon']
Result:
The program demonstrates the usage of lists in Python. It creates a
list, accesses and modifies elements, performs list operations like
appending, extending, and removing elements, and prints the modified
list.
Ex 12: Tuples
Aim:
To understand and utilize tuples in Python.
Algorithm:
1. Start
2. Create a tuple with elements.
3. Access tuple elements.
4. Perform tuple operations such as concatenation and slicing.
5. Print the result.
6. End
Program:
# Tuples
# Create a tuple
numbers = (1, 2, 3, 4, 5)
# Access tuple elements
print("First number:", numbers[0])
# Perform tuple operations
numbers_concatenated = numbers + (6, 7, 8)
numbers_sliced = numbers[2:5]
# Print the results
print("Concatenated tuple:", numbers_concatenated)
print("Sliced tuple:", numbers_sliced)
Output:
First number: 1
Concatenated tuple: (1, 2, 3, 4, 5, 6, 7, 8)
Sliced tuple: (3, 4, 5)
Result:
The program demonstrates the usage of tuples in Python. It creates
a tuple, accesses elements, performs tuple operations such as
concatenation and slicing, and prints the results.
Ex 13: Dictionaries
Aim:
To understand and utilize dictionaries in Python.
Algorithm:
1. Start
2. Create a dictionary with key-value pairs.
3. Access dictionary values using keys.
4. Modify dictionary values.
5. Perform dictionary operations such as adding new key-value pairs and
removing items.
6. Print the result.
7. End
Program:
# Dictionaries
# Create a dictionary
student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
# Access dictionary values using keys
print("Student name:", student["name"])
print("Student age:", student["age"])
# Modify dictionary values
student["age"] = 21
student["major"] = "Data Science"
# Perform dictionary operations
student["university"] = "XYZ University"
del student["major"]
# Print the dictionary
print("Modified dictionary:", student)
Output:
Student name: Alice Student age: 20 Modified dictionary: {'name':
'Alice', 'age': 21, 'university': 'XYZ University'}
Result:
The program demonstrates the usage of dictionaries in Python. It
creates a dictionary with key-value pairs, accesses values using keys,
modifies dictionary values, performs dictionary operations such as adding
new key-value pairs and removing items, and prints the modified
dictionary.
Ex 14: File Handling
Aim:
To understand file handling operations in Python.
Algorithm:
1. Start
2. Prompt the user to enter a filename.
3. Open the file in write mode.
4. Write data to the file.
5. Close the file.
6. Open the file in read mode.
7. Read and display the contents of the file.
8. Close the file.
9. End
Program:
# File Handling
# Prompt the user to enter a filename
filename = input("Enter the filename: ")
# Open the file in write mode
file = open(filename, 'w')
# Write data to the file
file.write("This is some sample text.")
file.write("\nThis is another line of text.")
# Close the file
file.close()
# Open the file in read mode
file = open(filename, 'r')
# Read and display the contents of the file
print("Contents of the file:")
print(file.read())
# Close the file
file.close()
Output:
Enter the filename: test.txt
Contents of the file:
This is some sample text.
This is another line of text.
Result:
The program demonstrates file handling operations in Python. It
writes data to a file and then reads and displays the contents of the file.