Python Practical
Python Practical
NAME :
REGISTER NUMBER :
YEAR/SEMESTER :
ACADEMIC YEAR :
1
RATHINAM TECHNICAL CAMPUS
RATHINAM TECHZONE
POLLACHI MAIN ROAD, EACHANARI, COIMBATORE-641021.
BONAFIDE CERTIFICATE
NAME :
ACADEMIC YEAR :
YEAR/SEMESTER :
BRANCH :
Certified that this is the bonafide record of work done by the above student in the
2
S.No Date Experiment Name Marks Staff Sign
3
S.No Date Experiment Name Marks Staff Sign
4
Ex No:1
Date: Simple Calculator
1.QUESTION
Create a calculator program using Python.
Aim:
To Create a calculator program using Python.
Algorithm:
1. Start the program by defining four functions: add(), subtract(), multiply(), and
divide(). Each function takes two arguments, x and y.
2. Define the add() function. It adds the two numbers and returns the result.
3. Define the subtract() function. It subtracts the second number from the first and
returns the result.
4. Define the multiply() function. It multiplies the two numbers and returns the
result.
5. Define the divide() function. It divides the first number by the second number. If
the second number is zero, it returns an error message. Otherwise, it returns the
result.
6. Define the calculator() function. This is the main function of the program.
7. In the calculator() function, print a welcome message and prompt the user to
select an operation.
8. Get the user's choice and check if it is a valid choice (1, 2, 3, or 4).
10. If the user entered a valid choice, perform the selected operation on the two
numbers.
5
Program:
def add(x, y):
return x + y
def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid Input")
6
calculator()
Output:
Simple Calculator
Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 2
Enter second number: 2
2.0 + 2.0 = 4.0
Result:
The program is executed successfully and the expected output is
7
obtained.
Ex No:2
Date: String Functions
2.Question:
Create Python program using different String functions.
Aim:
Algorithm:
1. Define a function called string_functions_demo that takes a
string as an argument.
2. Calculate the length of the input string and print it.
3. Convert the input string to uppercase and print it.
4. Convert the input string to lowercase and print it.
5. Capitalize the first letter of the input string and print it.
6. Count the number of occurrences of the substring "python" in the
input string and print it.
7. Check if the input string starts with the substring "Hello" and
print the result.
8. Check if the input string ends with the substring "world" and
print the result.
9. Find the index of the substring "is" in the input string and print it.
10. Replace the substring "Hello" with "Hi" in the input string and
print the result.
11. Strip leading and trailing whitespaces from the string " Some text
with spaces " and print the result.
12. Split the input string into a list of words and print the list.
13. Join the elements of the list of words into a string using "-" as the
separator and print the result.
14. Check if all characters in the input string are alphanumeric and
print the result.+
15. Check if all characters in the input string are alphabetic and print
the result.
8
16. Check if all characters in the input string are digits and print the
result.
17. Check if all characters in the input string are lowercase and print
the result.
18. Check if all characters in the input string are uppercase and print
the result.
19. Swap the case of all characters in the input string and print the
result.
20. Convert the first letter of each word in the input string to
uppercase and print the result.
21. Check if the input string is titlecased and print the result.
Program:
def string_functions_demo(input_string):
length = len(input_string)
print("1. Length of the string: {}".format(length))
uppercase_string = input_string.upper()
print("2. Uppercase: {}".format(uppercase_string))
lowercase_string = input_string.lower()
print("3. Lowercase: {}".format(lowercase_string))
capitalized_string = input_string.capitalize()
print("4. Capitalized: {}".format(capitalized_string))
substring = "python"
count = input_string.count(substring)
print("5. Count of '{}': {}".format(substring, count))
starts_with = "Hello"
starts_with_check = input_string.startswith(starts_with)
print("6. Starts with '{}': {}".format(starts_with, starts_with_check))
ends_with = "world"
ends_with_check = input_string.endswith(ends_with)
print("7. Ends with '{}': {}".format(ends_with, ends_with_check))
index = input_string.find("is")
9
print("8. Index of 'is': {}".format(index))
words = input_string.split()
print("11. Words in the string: {}".format(words))
joined_string = "-".join(words)
print("12. Joined string: {}".format(joined_string))
alphanumeric_check = input_string.isalnum()
print("13. Alphanumeric check: {}".format(alphanumeric_check))
alphabetic_check = input_string.isalpha()
print("14. Alphabetic check: {}".format(alphabetic_check))
digit_check = input_string.isdigit()
print("15. Digit check: {}".format(digit_check))
lowercase_check = input_string.islower()
print("16. Lowercase check: {}".format(lowercase_check))
uppercase_check = input_string.isupper()
print("17. Uppercase check: {}".format(uppercase_check))
swapped_case_string = input_string.swapcase()
print("18. Swapped case: {}".format(swapped_case_string))
title_case_string = input_string.title()
print("19. Title case: {}".format(title_case_string))
titlecased_check = input_string.istitle()
print("20. Titlecased check: {}".format(titlecased_check))
10
Output:
Result:
The program is executed successfully and the expected output is
11
obtained.
Ex No:3
Date: Selection Sort
3. Question:
Implement Selection sort algorithm using Python Program.
Aim:
To Implement selection Sort Algorithm Using Python Program.
Algorithm:
1. The selection sort algorithm sorts an array by repeatedly finding the minimum
element from the unsorted part of the array and putting it in the correct position in the
sorted part of the array.
2. The algorithm starts by initializing a variable min_index to the first index of the
array.
3. It then loops through the rest of the array (range(i + 1, n)) and checks if the
current element is smaller than the element at min_index.
5. After checking all the elements in the current iteration, the algorithm swaps the
elements at i and min_index.
6. This process is repeated for all the elements in the array until it is sorted.
Program:
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
12
return arr
Output:
Result:
13
The program is executed successfully and the expected output is
obtained.
Ex No:4
Date: Stack Operations
4. Question:
Implement stack Operation using Python Program
Aim:
To Implement stack Operation using Python Program
Algorithm:
1. Initialize an empty stack as a list.
stack = []
def push():
item = input("Enter a value to push onto the stack: ")
stack.append(item)
def pop():
if len(stack) == 0:
print("Error: Stack is empty")
return None
else:
14
return stack.pop()
def peek():
if len(stack) == 0:
print("Error: Stack is empty")
return None
else:
return stack[-1]
def is_empty():
return len(stack) == 0
def display_stack():
print("Stack:", stack)
def main():
while True:
print("\nStack Operations")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Check if empty")
print("5. Display stack")
print("6. Quit")
if choice == 1:
push()
elif choice == 2:
print("Popped:", pop())
elif choice == 3:
print("Peek:", peek())
15
elif choice == 4:
print("Empty:", is_empty())
elif choice == 5:
display_stack()
elif choice == 6:
break
else:
print("Invalid choice. Please enter a number between 1 and 6.")
main()
Output:
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 1
Enter a value to push onto the stack: 58
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 1
Enter a value to push onto the stack: 45
Stack Operations
1. Push
16
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 1
Enter a value to push onto the stack: 69
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 2
Popped: 69
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 3
Peek: 45
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
17
Enter your choice (1/2/3/4/5/6): 4
Empty: False
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 5
Stack: ['58', '45']
Stack Operations
1. Push
2. Pop
3. Peek
4. Check if empty
5. Display stack
6. Quit
Enter your choice (1/2/3/4/5/6): 6
Result:
18
The program is executed successfully and the expected output is
obtained.
Ex No:5
Date: Read and Write Into a File
Question:
5. )Read and Write into a file using Python Program.
Aim:
Algorithm:
19
Program:
print(content)
Output:
Enter a line: Hi there how are you?
Hi there how are you?
Result:
20
The program is executed successfully and the expected output is
obtained.
Ex No:6
Date: Use of Dictionaries
6) Question:
Demonstrate use of Dictionaries in Python Program
Aim:
To Demonstrate use of Dictionaries in Python Program
Algorithm:
1: define a dictionary named “person” containing information about a
person
2: print a descriptive message indicating “person’s information”
3: print the content of the “person” dictionary
4: print a message indicting “Accessing specific information “
6: Print a message indicating "Modifying occupation".
7: Update the value of the "occupation" key in the "person" dictionary to
"Data Scientist".
8: Print the updated value of the "occupation" key.
9: Print a message indicating "Adding new information".
10: Add new key-value pairs ("email" and "phone") to the "person"
dictionary.
11:Print the updated content of the "person" dictionary.
12:Print a message indicating "Removing 'city' from the information".
13: Delete the "city" key and its corresponding value from the "person"
dictionary.
14: Print the updated content of the "person" dictionary.
Program:
21
print("\nAccessing specific information:")
print("Name:", person["name"])
print("Age:", person["age"])
print("City:", person["city"])
print("Occupation:", person["occupation"])
print("\nModifying occupation...")
person["occupation"] = "Data Scientist"
print("Updated occupation:", person["occupation"])
print("\nAdding new information...")
person["email"] = "john.doe@example.com"
person["phone"] = "123-456-7890"
print("Updated Person's Information:")
print(person)
print("\nRemoving 'city' from the information...")
del person["city"]
print("Updated Person's Information:")
print(person)
Output:
Person's Information:
{'name': 'John Doe', 'age': 30, 'city': 'New York', 'occupation': 'Software
Engineer'}
Accessing specific information:
Name: John Doe
Age: 30
City: New York
Occupation: Software Engineer
Modifying occupation...
Updated occupation: Data Scientist
Adding new information...
Updated Person's Information:
{'name': 'John Doe', 'age': 30, 'city': 'New York', 'occupation': 'Data
Scientist', 'email': 'john.doe@example.com', 'phone': '123-456-7890'}
Removing 'city' from the information...
Updated Person's Information:
{'name': 'John Doe', 'age': 30, 'occupation': 'Data Scientist', 'email':
'john.doe@example.com', 'phone': '123-456-7890'}
22
Result:
The program is executed successfully and the expected output is
obtained.
Ex No:7
Date: CSV File Operation
7)Question:
Create Comma Separate Files (CSV), Load CSV files into internal Data
Structure.
Aim:
To Create Comma Separate Files (CSV), Load CSV files into internal
Data Structure.
Algorithm:
1: Import the CSV module to work with CSV files.
2: Define a list called "data" containing lists of data rows. Each sublist
represents a row in the CSV file, with the first sublist being the header
row.
3: Specify the file path where the CSV file will be created.
4: Open the CSV file in write mode using a context manager ("with"
statement) to ensure proper file handling. Specify 'utf-8' encoding for
compatibility.
6: Use the writer.writerows() method to write the entire data list to the
CSV file.
23
8: Print a confirmation message indicating the successful creation of the
CSV file along with its file path.
Program:
import csv
data = [
['Name', 'Age', 'City'],
['Aman', 28, 'Pune'],
['Poonam', 24, 'Jaipur'],
['Bobb', 32, 'Delhi']
]
csv_file_path = 'exampl.csv'
writer.writerows(data)
Output:
CSV file 'exampl.csv' created successfully.
Result:
24
The program is executed successfully and the expected output is
obtained.
Ex No:8
Date: Sql Select Statement
8)Question:
Write script to work like a SQL SELECT statement for internal Data
Structure made in
earlier exercise.
Aim:
To Write script to work like a SQL SELECT statement for internal Data
Structure made in
earlier exercise.
Algorithm:
1: Define a list of dictionaries named "data" containing information about
individuals, where each dictionary represents a row of data with keys 'id',
'name', and 'age'.
25
6: Define an example SQL-like query string "query" for selecting rows
where age is greater than or equal to 25.
10: Iterate through the result and print each row to display the selected
data.
Program:
import operator
data = [
{"id": 1, "name": "John", "age": 30},
{"id": 2, "name": "Alice", "age": 63},
{"id": 3, "name": "Bob", "age": 35},
{"id": 4, "name": "Emily", "age": 28}
]
column_getter = operator.itemgetter("age")
print("Query Result:")
for row in result:
print(row)
26
Output:
Query Result:
{'id': 1, 'name': 'John', 'age': 30}
{'id': 2, 'name': 'Alice', 'age': 63}
{'id': 3, 'name': 'Bob', 'age': 35}
{'id': 4, 'name': 'Emily', 'age': 28}
27
Result:
The program is executed successfully and the expected output is
obtained.
Ex No:9
Date: Sql Inner Join
9) Question
Write script to work like a SQL Inner Join for an internal Data Structure
made in earlier exercise.
Aim:
To Write script to work like a SQL Inner Join for an internal Data
Structure made in earlier exercise.
Algorithm:
28
7: Iterate through the result of the INNER JOIN operation and print each
merged row to display the joined data.
Program:
table1 = [
{"id": 1, "name": "John", "age": 30, "dept_id": 1},
{"id": 2, "name": "Alice", "age": 25, "dept_id": 2},
{"id": 3, "name": "Bob", "age": 35, "dept_id": 1},
{"id": 4, "name": "Emily", "age": 28, "dept_id": 3}
]
table2 = [
{"dept_id": 1, "department": "HR"},
{"dept_id": 2, "department": "IT"},
{"dept_id": 3, "department": "Finance"}
]
Output:
Inner Join Result:
{'id': 1, 'name': 'John', 'age': 30, 'dept_id': 1, 'department': 'HR'}
{'id': 2, 'name': 'Alice', 'age': 25, 'dept_id': 2, 'department': 'IT'}
{'id': 3, 'name': 'Bob', 'age': 35, 'dept_id': 1, 'department': 'HR'}
{'id': 4, 'name': 'Emily', 'age': 28, 'dept_id': 3, 'department': 'Finance'}
29
Result:
The program is executed successfully and the expected output is
obtained.
Ex No:10
Date: Exception in Python
10)Question:
Demonstrate Exceptions in Python.
Aim:
To Demonstrate Exceptions in Python.
Algorithm:
1. Start execution of the program.
2. Define a function named `divide_numbers` which takes two arguments
`x` and `y`.
3. Within the function, start a `try` block.
4. Inside the `try` block, attempt to divide `x` by `y` and assign the result
to a variable named `result`.
5. Print a message indicating the result of the division operation.
6. If a `ZeroDivisionError` occurs during division by zero, catch the
exception.
7. Within the `except` block for `ZeroDivisionError`, print an error
message indicating that division by zero is not allowed.
8. End the `try-except` block.
9. Outside the function definition, start a `try-except` block.
10. Within this block, call the `divide_numbers` function with arguments
`10` and `0`.
11. If an exception occurs during the function call, catch it and assign it to
the variable `e`.
12. Print a message indicating that an exception occurred, along with the
details of the exception.
13. End the `try-except` block.
14. End execution of the program.
30
Program:
try:
divide_numbers(10,0)
except Exception as e:
print("An exception occurred:", e)
Output:
31
Result:
The program is executed successfully and the expected output is
obtained.
32