Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
24 views

Python Practical

Uploaded by

sanjayantonio5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python Practical

Uploaded by

sanjayantonio5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

RATHINAM TECHZONE

DEPARTMENT OF INFORMATION TECHNOLOGY

RECORD NOTE BOOK


23BIT2CP - Core Practical - Python Programming

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 :

UNIVERSITY REGISTER NUMBER: ………………………………..

Certified that this is the bonafide record of work done by the above student in the

Laboratory during the year 2023-2024.

Head of the Department Staff-in-Charge

Submitted for the Practical Examination held on

Internal Examiner External Examiner

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).

9. If the choice is valid, get two numbers from the user.

10. If the user entered a valid choice, perform the selected operation on the two
numbers.

11. If the user entered an invalid choice, print an error message.

12. Call the calculator() function to start the program.

5
Program:
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y != 0:
return x / y
else:
return "Error: Cannot divide by zero"

def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

if choice in ['1', '2', '3', '4']:


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

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:

To create Python program using different String functions.

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))

replaced_string = input_string.replace("Hello", "Hi")


print("9. Replaced string: {}".format(replaced_string))

stripped_string = " Some text with spaces "


stripped_result = stripped_string.strip()
print("10. Stripped result: {}".format(stripped_result))

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))

input_string = "Hello, this is a Python string example."


string_functions_demo(input_string)

10
Output:

1. Length of the string: 39


2. Uppercase: HELLO, THIS IS A PYTHON STRING EXAMPLE.
3. Lowercase: hello, this is a python string example.
4. Capitalized: Hello, this is a python string example.
5. Count of 'python': 0
6. Starts with 'Hello': True
7. Ends with 'world': False
8. Index of 'is': 9
9. Replaced string: Hi, this is a Python string example.
10. Stripped result: Some text with spaces
11. Words in the string: ['Hello,', 'this', 'is', 'a', 'Python', 'string', 'example.']
12. Joined string: Hello,-this-is-a-Python-string-example.
13. Alphanumeric check: False
14. Alphabetic check: False
15. Digit check: False
16. Lowercase check: False
17. Uppercase check: False
18. Swapped case: hELLO, THIS IS A pYTHON STRING EXAMPLE.
19. Title case: Hello, This Is A Python String Example.
20. Titlecased check: False

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.

4. If a smaller element is found, min_index is updated to the index of the smaller


element.

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

arr = [64, 25, 12, 22, 11]


sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_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.

2. Define functions push(), pop(), peek(), is_empty(), and


display_stack() to perform the corresponding stack operations.

3. In the main() function: a. Display a menu of stack operations. b. Get


user input and perform the corresponding stack operation based on
the user's choice. c. Repeat steps a and b until the user quits.
4. Call main() if the program is run as a script.
Program:

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")

choice = int(input("Enter your choice (1/2/3/4/5/6): "))

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:

To Read and Write into a file using Python Program.

Algorithm:

1. Open a file named `'example.txt'` in write mode using the `open()`


function with `'w'` mode.
2. Prompt the user to input a line using the `input()` function and store it
in the variable `line`.
3. Write the content of the `line` variable to the file using the `write()`
method associated with the file object `file`.
4. Close the file automatically using the `with` statement block when
exiting the block.
5. Open the `'example.txt'` file again, this time in read mode (`'r'`) using
the `open()` function with `'r'` mode.
6. Read the entire content of the file into the `content` variable using the
`read()` method associated with the file object `file`.
7. Close the file automatically using the `with` statement block when
exiting the block.
8. Print the content of the `content` variable, which contains the entire
content of the file.

19
Program:

with open('example.txt', 'w') as file:


line = input("Enter a line:")
file.write(line) # Write a line to the file

with open('example.txt', 'r') as file:


content = file.read() # Read the entire file

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:

person = {"name": "John Doe", "age": 30, "city": "New York",


"occupation": "Software Engineer"}
print("Person's Information:")
print(person)

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.

5: Inside the context manager, create a csv.writer object named "writer"


using the open file object.

6: Use the writer.writerows() method to write the entire data list to the
CSV file.

7: Upon exiting the context manager, the file will be automatically


closed.

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'

with open(csv_file_path, mode='w', newline='', encoding='utf-8') as


csv_file:
writer = csv.writer(csv_file)

writer.writerows(data)

print(f"CSV file '{csv_file_path}' created successfully.")

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'.

2: Import the "operator" module to facilitate accessing dictionary values


by key.

3: Create a column getter using "operator.itemgetter()" to extract the 'age'


column from each dictionary in the data.

4: Define a function named "select_from_data" to perform a SELECT


operation on the data based on a given criteria.

5: Within the "select_from_data" function, use the built-in "filter()"


function along with a lambda function to filter the data based on the
specified criteria.

25
6: Define an example SQL-like query string "query" for selecting rows
where age is greater than or equal to 25.

7: Parse the query by creating a dictionary "criteria" where keys are


obtained using the column getter and values are the ages of the
corresponding rows in the data.

8: Execute the SELECT query by calling the "select_from_data" function


with the data and criteria.

9: Print a descriptive message indicating "Query Result".

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")

def select_from_data(data, criteria):


return list(filter(lambda x: criteria[column_getter(x)] > 25, data))

query = "SELECT * FROM data WHERE age >= 25"

criteria = {column_getter(row): row["age"] for row in data}

result = select_from_data(data, criteria)

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:

1: Define two lists of dictionaries: "table1" and "table2", representing


relational tables with related information. "table1" contains data about
individuals and their department IDs, while "table2" contains data about
departments and their corresponding IDs.

2: Define a function named "inner_join" to perform an INNER JOIN


operation between two tables based on a specified join key.

4: Within the "inner_join" function, use a list comprehension to iterate


through each combination of rows from "table1" and "table2". For each
combination, merge the dictionaries using dictionary unpacking (the ""
operator) if the join keys match.

5: Execute the INNER JOIN operation by calling the "inner_join"


function with "table1", "table2", and the join key ("dept_id").

6: Print a descriptive message indicating "Inner Join Result".

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"}
]

def inner_join(table1, table2, join_key):


return [{**row1, **row2} for row1 in table1 for row2 in table2 if
row1[join_key] == row2[join_key]]

result = inner_join(table1, table2, "dept_id")

print("Inner Join Result:")


for row in result:
print(row)

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:

def divide_numbers(x, y):


try:
result = x / y
print("The result of", x, "divided by", y, "is:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

try:
divide_numbers(10,0)
except Exception as e:
print("An exception occurred:", e)

Output:

Error: Division by zero is not allowed.

31
Result:
The program is executed successfully and the expected output is
obtained.

32

You might also like