0% found this document useful (0 votes)
0 views17 pages

R23 Mech Python

The document outlines a series of experiments designed to introduce Python programming, covering installation, basic syntax, functions, data structures like lists, tuples, dictionaries, and sets. Each experiment includes objectives, tasks, and example programs demonstrating key concepts and operations. The document serves as a comprehensive guide for beginners to learn and practice Python programming.

Uploaded by

bslsdevi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views17 pages

R23 Mech Python

The document outlines a series of experiments designed to introduce Python programming, covering installation, basic syntax, functions, data structures like lists, tuples, dictionaries, and sets. Each experiment includes objectives, tasks, and example programs demonstrating key concepts and operations. The document serves as a comprehensive guide for beginners to learn and practice Python programming.

Uploaded by

bslsdevi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Experiment 1: Introduction to Python

- Objective: Install Python and set up the development environment.


- Tasks:
- Install Python and an IDE (e.g., PyCharm, VSCode, or Jupyter Notebook).
To install Python and an IDE like PyCharm, Visual Studio Code (VS Code), or Jupyter Notebook, you
can:
1. Install Python:
 Go to the official Python website:
Navigate to https://www.python.org/downloads/ and download the latest stable version of Python for your
operating system (Windows, macOS, Linux).
 Run the installer:
Double-click the downloaded file and follow the on-screen instructions to install Python on your system.
 Add Python to your PATH:
During installation, ensure you select the option to add Python to your system's PATH environment
variable, allowing you to run Python commands from your terminal directly.
2. Choose and Install an IDE:
 PyCharm:
 Download: Visit the JetBrains website (https://www.jetbrains.com/pycharm/download/)
and download the appropriate version of PyCharm based on your operating system and
whether you want the Community (free) or Professional edition.
 Install: Run the installer and follow the prompts to set up PyCharm.
 Visual Studio Code (VS Code):
 Download: Go to https://code.visualstudio.com/ and download the VS Code installer for
your system.
 Install: Run the installer and follow the instructions.
 Install Python extension: Once installed, open VS Code, go to the extensions tab
(Ctrl+Shift+X), search for "Python" and install the official Python extension by Microsoft.
 Jupyter Notebook:
 Install via pip: Open your terminal and run the command pip install jupyter to install
Jupyter Notebook using the Python package installer (pip).
 Launch: Once installed, you can launch Jupyter Notebook by running jupyter notebook in
your terminal, which will open a web interface where you can create and run notebooks.

- Write and run a simple "Hello, World!" program.


Program:
print("Hello, World!")

Output:
Hello, World!

- Understand and demonstrate basic Python syntax and semantics.


Program:
# Arithmetic operators: +, -, *, /, %, //, **
a = 10
b=3

print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.3333333333333335 (float division)
print(a // b) # Integer division: 3
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000

Output:
13
7
30
3.3333333333333335
3
1
1000

Experiment 2: Basic Python Programming


- Objective: Learn basic programming constructs in Python.
- Tasks:
- Create programs using variables, data types, and operators.
Program:
# Assigning values to variables
x=6 # integer
y = 4.13 # float
name = "CIST" # string
is_active = True # boolean
print(x, type(x))
print(y, type(y))
print(name, type(name))
print(is_active, type(is_active))

output:

6 <class 'int'>
4.13 <class 'float'>
CIST <class 'str'>
True <class 'bool'>

- Implement basic input and output functions.


- Write programs using control structures (if statements, for loops, while loops).

Program:
# Conditional logic using if-else statements
num = 5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Output:
Positive number

# Using a for loop to iterate over a range of numbers


for i in range(5):
print(i)

Output:
0
1
2
3
4

# Using a while loop


count = 0
while count < 5:
print(count)
count += 1 # Increment the counter

Output:
0
1
2
3
4

Experiment 3: Functions and Modules


- Objective: Understand functions and module usage in Python.
- Tasks:
- Define and call functions with different types of arguments and return values.

Program:
# Defining and calling a function
def greet(name):
return f"Hello, {name}!"
print(greet("CIST"))

Output:
Hello, CIST!
Program:
def add(x,y):
return x+y

print(add(5,4))

Output:
9

Explore and use built-in Python modules.


- Write a script that imports and utilizes at least two different standard library modules.

Program:

# Importing the required modules


import random
import datetime
import time

# Generate a random number between 1 and 10


random_number = random.randint(1, 10)
print(f"Random Number: {random_number}")

# Get the current date and time


current_datetime = datetime.datetime.now()
print(f"Current Date and Time: {current_datetime}")

# Pause execution for a random number of seconds (using the random number generated)
print(f"Waiting for {random_number} seconds...")
time.sleep(random_number)

# After the wait, print a message


print(f"Done! Waited for {random_number} seconds.")

Output:
Random Number: 9
Current Date and Time: 2024-9-18 15:44:26.994288
Waiting for 9 seconds...
Done! Waited for 9 seconds.

Experiment 4: Lists and Tuples


- Objective:Work with Python lists and tuples.
- Tasks:
- Create, modify, and iterate over lists and tuples.

Program:
# Create a list
my_list = [10, 20, 30, 40, 50]
print("Original List:", my_list)

# Modify the list (adding, removing, and updating elements)


my_list.append(60) # Add an element
my_list.remove(30) # Remove an element
my_list[2] = 100 # Update an element at index 2
print("Modified List:", my_list)

# Iterate over the list


print("Iterating over the list:")
for item in my_list:
print(item)

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)
print("\nOriginal Tuple:", my_tuple)

# Tuples are immutable, so we cannot modify them directly. However, we can create a new tuple.
new_tuple = my_tuple + (6,) # Adding an element to a tuple (creates a new tuple)
print("Modified Tuple (new tuple created):", new_tuple)

# Iterate over the tuple


print("Iterating over the tuple:")
for item in my_tuple:
print(item)

Output:
Original List: [10, 20, 30, 40, 50]
Modified List: [10, 20, 100, 50, 60]
Iterating over the list:
10
20
100
50
60

Original Tuple: (1, 2, 3, 4, 5)


Modified Tuple (new tuple created): (1, 2, 3, 4, 5, 6)
Iterating over the tuple:
1
2
3
4
5
- Perform list comprehensions to create new lists.
Program:
# Example 1: Create a list of squares using list comprehension
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print("Squares:", squares)

Output:
Squares: [1, 4, 9, 16, 25]

Program:
# Example 2: Create a list of even numbers using list comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
print("Even Numbers:", even_numbers)

OutPut:
Even Numbers: [2, 4]

# Example 3: Create a list of tuples (number, square) using list comprehension


number_square_tuples = [(x, x**2) for x in numbers]
print("Number-Square Tuples:", number_square_tuples)

Output:
Number-Square Tuples: [(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

# Example 4: Create a new list from a string, containing only vowels


my_string = "hello world"
vowels = [char for char in my_string if char in 'aeiou']
print("Vowels in string:", vowels)

Output:
Vowels in string: ['e', 'o', 'o']

# Example 5: Create a list of numbers that are divisible by both 2 and 3 using list comprehension
div_by_2_and_3 = [x for x in range(1, 21) if x % 2 == 0 and x % 3 == 0]
print("Numbers divisible by 2 and 3:", div_by_2_and_3)

Output:
Numbers divisible by 2 and 3: [6, 12, 18]

- Demonstrate the immutability of tuples.


Program:
# Create a tuple
my_tuple = (10, 20, 30)
print("Original Tuple:", my_tuple)
# Trying to modify an element (this will raise an error)
try:
my_tuple[1] = 40 # Attempting to modify the second element
except TypeError as e:
print("Error:", e)

# Demonstrating that a tuple cannot be changed


print("Tuple after trying to modify:", my_tuple)

# Tuples are immutable, so we cannot add elements directly, but we can create a new tuple
new_tuple = my_tuple + (40, 50) # Concatenate a new tuple
print("New Tuple after concatenation:", new_tuple)

# Deleting an element from a tuple is not allowed


try:
del my_tuple[0] # Attempting to delete the first element
except TypeError as e:
print("Error:", e)

# Showing that the original tuple is still intact


print("Tuple after trying to delete an element:", my_tuple)

Output:
ERROR!
Original Tuple: (10, 20, 30)
Error: 'tuple' object does not support item assignment
Tuple after trying to modify: (10, 20, 30)
New Tuple after concatenation: (10, 20, 30, 40, 50)
ERROR!
Error: 'tuple' object doesn't support item deletion
Tuple after trying to delete an element: (10, 20, 30)

Experiment 5: Dictionaries and Sets


- Objective: Explore dictionaries and sets in Python.
- Tasks:
- Create and manipulate dictionaries.
Program:
# 1. Creating a dictionary
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science",
"grade": "A"
}
print("Original Dictionary:", student)
# 2. Accessing dictionary values
print("Student Name:", student["name"]) # Accessing by key
print("Student Major:", student.get("major")) # Using get() method

# 3. Adding a new key-value pair


student["graduation_year"] = 2024
print("Dictionary after adding 'graduation_year':", student)

# 4. Modifying an existing value


student["grade"] = "A+"
print("Dictionary after modifying 'grade':", student)

# 5. Removing a key-value pair


removed_major = student.pop("major") # Removes 'major' and returns its value
print("Dictionary after removing 'major':", student)
print("Removed Major:", removed_major)

# 6. Checking if a key exists


if "age" in student:
print("Age is present in the dictionary.")

# 7. Iterating over the dictionary (keys, values, items)


print("\nIterating over dictionary:")
for key, value in student.items():
print(f"{key}: {value}")

# 8. Getting all keys and values separately


keys = student.keys() # Get all keys
values = student.values() # Get all values
print("\nKeys:", list(keys))
print("Values:", list(values))

# 9. Clearing the dictionary


student.clear()
print("Dictionary after clearing:", student)

Output:
Original Dictionary: {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade': 'A'}
Student Name: Alice
Student Major: Computer Science
Dictionary after adding 'graduation_year': {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade':
'A', 'graduation_year': 2024}
Dictionary after modifying 'grade': {'name': 'Alice', 'age': 22, 'major': 'Computer Science', 'grade': 'A+',
'graduation_year': 2024}
Dictionary after removing 'major': {'name': 'Alice', 'age': 22, 'grade': 'A+', 'graduation_year': 2024}
Removed Major: Computer Science
Age is present in the dictionary.

Iterating over dictionary:


name: Alice
age: 22
grade: A+
graduation_year: 2024

Keys: ['name', 'age', 'grade', 'graduation_year']


Values: ['Alice', 22, 'A+', 2024]
Dictionary after clearing: {}

- Use dictionary comprehension.


Program:
# 1. Create a dictionary of squares using dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squares_dict = {x: x**2 for x in numbers}
print("Dictionary of squares:", squares_dict)

# 2. Create a dictionary from two lists using dictionary comprehension


keys = ['name', 'age', 'major']
values = ['Alice', 22, 'Computer Science']
student_dict = {keys[i]: values[i] for i in range(len(keys))}
print("Student Dictionary:", student_dict)

# 3. Filter a dictionary using dictionary comprehension (only keep even numbers and their squares)
original_dict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
even_squares_dict = {k: v for k, v in original_dict.items() if k % 2 == 0}
print("Filtered Dictionary (only even numbers):", even_squares_dict)

# 4. Create a dictionary where the keys are numbers and values are whether they are odd or even
odd_even_dict = {x: ('even' if x % 2 == 0 else 'odd') for x in range(1, 6)}
print("Odd/Even Dictionary:", odd_even_dict)

Output:
Dictionary of squares: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Student Dictionary: {'name': 'Alice', 'age': 22, 'major': 'Computer Science'}
Filtered Dictionary (only even numbers): {2: 4, 4: 16}
Odd/Even Dictionary: {1: 'odd', 2: 'even', 3: 'odd', 4: 'even', 5: 'odd'}
- Create and perform operations on sets.
Output:
# 1. Creating sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}
print("Set A:", set_a)
print("Set B:", set_b)

# 2. Adding an element to a set


set_a.add(6)
print("Set A after adding 6:", set_a)

# 3. Removing an element from a set


set_a.remove(2) # Removes element 2 (raises KeyError if element is not found)
print("Set A after removing 2:", set_a)

# 4. Discarding an element (no error if element doesn't exist)


set_a.discard(10) # No error even if 10 is not in the set
print("Set A after discarding 10 (non-existent):", set_a)

# 5. Set Union
union_set = set_a.union(set_b) # OR set_a | set_b
print("Union of Set A and Set B:", union_set)

# 6. Set Intersection
intersection_set = set_a.intersection(set_b) # OR set_a & set_b
print("Intersection of Set A and Set B:", intersection_set)

# 7. Set Difference (elements in set_a but not in set_b)


difference_set = set_a.difference(set_b) # OR set_a - set_b
print("Difference of Set A and Set B (A - B):", difference_set)

# 8. Set Symmetric Difference (elements in either set_a or set_b but not both)
symmetric_difference_set = set_a.symmetric_difference(set_b) # OR set_a ^ set_b
print("Symmetric Difference of Set A and Set B:", symmetric_difference_set)
# 9. Checking for subset and superset relationships
set_c = {4, 5}
print("Set C is a subset of Set A:", set_c.issubset(set_a)) # True if set_c is a subset of set_a
print("Set A is a superset of Set C:", set_a.issuperset(set_c)) # True if set_a is a superset of set_c

# 10. Checking for disjoint sets (no common elements)


print("Set A and Set B are disjoint:", set_a.isdisjoint({9, 10})) # True if no elements are shared

Output:

Set A: {1, 2, 3, 4, 5}
Set B: {4, 5, 6, 7, 8}
Set A after adding 6: {1, 2, 3, 4, 5, 6}
Set A after removing 2: {1, 3, 4, 5, 6}
Set A after discarding 10 (non-existent): {1, 3, 4, 5, 6}
Union of Set A and Set B: {1, 3, 4, 5, 6, 7, 8}
Intersection of Set A and Set B: {4, 5, 6}
Difference of Set A and Set B (A - B): {1, 3}
Symmetric Difference of Set A and Set B: {1, 3, 7, 8}
Set C is a subset of Set A: True
Set A is a superset of Set C: True
Set A and Set B are disjoint: True

Experiment 6: Strings and File I/O


- Objective: Manipulate strings and perform file I/O operations.
- Tasks:
- Demonstrate various string methods.
Program:
# Sample string
text = " Hello, World! "

# Demonstrating string methods

# 1. upper() - Converts all characters to uppercase


print("Uppercase:", text.upper())

# 2. lower() - Converts all characters to lowercase


print("Lowercase:", text.lower())

# 3. strip() - Removes leading and trailing whitespaces


print("Stripped:", text.strip())

# 4. replace() - Replaces a substring with another


print("Replaced 'World' with 'Python':", text.replace("World", "Python"))
# 5. split() - Splits the string at spaces (default separator)
print("Split:", text.split())

# 6. join() - Joins elements of a list into a single string


words = ["Hello", "Python", "World"]
print("Joined:", " ".join(words))

# 7. find() - Finds the index of the first occurrence of a substring


print("Index of 'World':", text.find("World"))

# 8. count() - Counts the occurrences of a substring


print("Count of 'l':", text.count("l"))

# 9. startswith() - Checks if the string starts with a given substring


print("Starts with 'Hello':", text.startswith("Hello"))

# 10. endswith() - Checks if the string ends with a given substring


print("Ends with 'World!':", text.endswith("World!"))

# 11. isalpha() - Checks if the string contains only alphabetic characters


print("Is alphabetic:", text.strip().isalpha()) # After stripping spaces

# 12. isdigit() - Checks if the string contains only digits


numeric_string = "12345"
print("Is digit:", numeric_string.isdigit())

# 13. title() - Converts the first letter of each word to uppercase


print("Title case:", text.title())

# 14. capitalize() - Capitalizes the first letter of the string


print("Capitalized:", text.capitalize())

# 15. rfind() - Finds the last occurrence of a substring


print("Last index of 'l':", text.rfind('l'))

Output:
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Stripped: Hello, World!
Replaced 'World' with 'Python': Hello, Python!
Split: ['Hello,', 'World!']
Joined: Hello Python World
Index of 'World': 9
Count of 'l': 3
Starts with 'Hello': False
Ends with 'World!': False
Is alphabetic: False
Is digit: True
Title case: Hello, World!
Capitalized: hello, world!
Last index of 'l': 12

- Write programs to read from and write to text files.

Program:
# Program to write to a text file
# Data to write to the file
data = """Hello, World!
This is a sample text file.
Python makes file handling easy!"""
# Open the file in write mode
with open("sample.txt", "w") as file:
# Write the data to the file
file.write(data)
print("Data has been written to sample.txt")

# Program to read from a text file

# Open the file in read mode


with open("sample.txt", "r") as file:
# Read the entire file content
content = file.read()

# Print the content of the file


print("Content of the file:")
print(content)

Output:

Hello, World!
This is a sample text file.
Python makes file handling easy!

Data has been written to sample.txt

Content of the file:


Hello, World!
This is a sample text file.
Python makes file handling easy!

- Work with different file formats, including CSV and JSON.


Program:

1. Working with CSV Files

Program to Write and Read CSV Files:

python
Copy code
import csv

# Data to write to the CSV file


data = [
["Name", "Age", "City"],
["Alice", 28, "New York"],
["Bob", 23, "Los Angeles"],
["Charlie", 35, "Chicago"]
]

# Writing to a CSV file


with open("people.csv", "w", newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
print("Data has been written to 'people.csv'.")

# Reading from the CSV file


with open("people.csv", "r") as file:
reader = csv.reader(file)
print("\nContent of 'people.csv':")
for row in reader:
print(row)

Output
Data has been written to 'people.csv'.

Content of 'people.csv':
['Name', 'Age', 'City']
['Alice', '28', 'New York']
['Bob', '23', 'Los Angeles']
['Charlie', '35', 'Chicago']

2. Working with JSON Files

Program to Write and Read JSON Files:

python
Copy code
import json

# Data to write to the JSON file


data = {
"employees": [
{"name": "Alice", "age": 28, "city": "New York"},
{"name": "Bob", "age": 23, "city": "Los Angeles"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
}

# Writing to a JSON file


with open("employees.json", "w") as file:
json.dump(data, file, indent=4)
print("\nData has been written to 'employees.json'.")

# Reading from the JSON file


with open("employees.json", "r") as file:
loaded_data = json.load(file)

print("\nContent of 'employees.json':")
print(json.dumps(loaded_data, indent=4))

Output
Data has been written to 'employees.json'.

Content of 'employees.json':
{
"employees": [
{
"name": "Alice",
"age": 28,
"city": "New York"
},
{
"name": "Bob",
"age": 23,
"city": "Los Angeles"
},
{
"name": "Charlie",
"age": 35,
"city": "Chicago"
}
]
}

Experiment 7: Error Handling and Exceptions


- Objective: Implement error handling in Python programs.
- Tasks:
- Write programs using try, except, else, and finally blocks.
Program:
def divide_numbers(a, b):
try:
# Try to divide two numbers
result = a / b
except ZeroDivisionError:
# Handle division by zero error
print("Error: Division by zero is not allowed.")
else:
# This will execute if no exception occurs
print(f"Result: {a} / {b} = {result}")
finally:
# This will always execute
print("Execution of division completed.")

# Test cases
print("Test case 1:")
divide_numbers(10, 2)

print("\nTest case 2:")


divide_numbers(10, 0)

Output:

Test case 1:
ERROR!
Result: 10 / 2 = 5.0
Execution of division completed.

Test case 2:
Error: Division by zero is not allowed.
Execution of division completed.

- Handle specific exceptions.


Program:

def divide_numbers():
try:
# Take two inputs from the user and try to divide them
a = int(input("Enter the numerator: "))
b = int(input("Enter the denominator: "))
result = a / b
except ZeroDivisionError:
# Handle the case where division by zero is attempted
print("Error: Division by zero is not allowed.")
except ValueError:
# Handle the case where the input is not a valid integer
print("Error: Please enter valid integers.")
else:
# No exception occurred, print the result
print(f"Result: {a} / {b} = {result}")
finally:
# This will always execute, regardless of exceptions
print("Execution completed.")

# Run the function


divide_numbers()

Output:

Enter the numerator: 5


Enter the denominator: 0
ERROR!
Error: Division by zero is not allowed.

Create and raise custom exceptions.


Experiment 8:Object-Oriented Programming (OOP)
- Objective: Understand and implement OOP concepts in Python.
- Tasks:
- Define classes and create objects.
- Demonstrate inheritance and polymorphism.
- Use class and instance variables in programs.
Experiment 9:Libraries and Packages
- Objective: Utilize third-party libraries and create Python packages.
- Tasks:
- Install and use libraries like NumPy and Pandas.
- Create a simple Python package and distribute it.
- Work with virtual environments to manage dependencies.
Experiment 10: Working with Data
-Objective: Perform data manipulation and visualization.
- Tasks:
- Use Pandas to load, manipulate, and analyze datasets.
- Create visualizations using Matplotlib and Seaborn.
- Conduct basic data analysis tasks and summarize findings.
Experiment 11: Web Scraping and APIs
- Objective: Extract data from the web and interact with APIs.
- Tasks:
- Access and parse data from RESTful APIs.
- Process and analyze JSON data from APIs.
Experiment 12: Databases
- **Objective:** Work with databases in Python.
- **Tasks:**
- Connect to a database using SQLite and SQLAlchemy.
- Perform CRUD operations on the database.
- Write queries to manage and retrieve data.

You might also like