Experiment 1: Introduction to Python
Install Python and an IDE (e.g., Spyder, PyCharm, VSCode, or Jupyter
Notebook).
Step-by-step guide to install Python and Spyder IDE using Anaconda:
1. Download and Install Anaconda
Anaconda is a distribution of Python and R, specifically designed for data science and scientific
computing. It comes with popular tools like Spyder, Jupyter Notebook, and others. Here’s how to
install it:
Step 1: Download Anaconda
Go to the official Anaconda website.
Click on Download.
Choose the correct version for your operating system (Windows, macOS, or Linux).
Download the installer based on your system architecture (32-bit or 64-bit).
Step 2: Install Anaconda
For Windows:
1. Run the .exe file you downloaded.
2. Follow the installation prompts. You can choose the default settings
(recommended).
3. If prompted to add Anaconda to the system PATH environment, you can opt to
skip this (the Anaconda Navigator will handle it).
Step 3: Open Anaconda Navigator
After installation is complete, launch Anaconda Navigator:
Windows: Search for "Anaconda Navigator" in the Start Menu.
macOS/Linux: Open Anaconda Navigator from the Applications or using a terminal by
typing:
bash
Copy code
anaconda-navigator
2. Install Spyder IDE in Anaconda
Spyder IDE comes pre-installed with the Anaconda distribution, but if it isn’t, or if you need to
update it, follow these steps.
Step 1: Check for Spyder in Anaconda Navigator
Open Anaconda Navigator.
Look for Spyder in the "Home" tab.
If it’s listed, click on the Launch button next to it.
Step 2: Install/Update Spyder (if needed)
If Spyder isn’t installed or you want to update to the latest version:
Open the Environments tab in Anaconda Navigator.
Select your environment (or create a new one if needed).
Search for Spyder in the list of available packages.
Click the checkbox next to Spyder, then click Apply to install it.
Write and run a simple "Hello, World!" program.
Basic Python syntax and semantics
1. Variables and Data Types
In Python, you can assign values to variables without specifying their types explicitly. Python
automatically infers the type based on the value.
# Variables and basic data types
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean
print(x, y, name, is_active)
# Output: 10 3.14 Alice True
2. Arithmetic Operations
Python supports basic arithmetic operations like addition, subtraction, multiplication, division,
and more.
# Arithmetic operations
a=5
b=2
add = a + b # Addition
sub = a - b # Subtraction
mul = a * b # Multiplication
div = a / b # Division (floating point)
mod = a % b # Modulus (remainder)
exp = a ** b # Exponentiation (5^2)
print(add, sub, mul, div, mod, exp)
# Output: 7, 3, 10, 2.5, 1, 25
3. Conditional Statements
Python uses if, elif, and else for conditional branching.
# Conditional statements
age = 20
if age < 18:
print("You are a minor.")
elif age < 65:
print("You are an adult.")
else:
print("You are a senior citizen.")
# Output: You are an adult.
4. Loops
Python supports for and while loops for iteration.
a. For Loop
A for loop is used to iterate over sequences like lists, strings, or ranges.
# For loop with range
for i in range(1, 6):
print(i)
# Output: 1 2 3 4 5
b. While Loop
A while loop runs as long as a condition is true.
# While loop
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1 2 3
Experiment 2: Basic Python Programming
1. Write a program that asks the user for a weight in kilograms and converts it to pounds.
There are 2.2 pounds in a kilogram.
Code:
kilograms=float(input("Enter Weight in Kilograms: "))
pounds=2.2*kilograms
print("Weight in Pounds: ",pounds)
OUTPUT:
Enter Weight in Kilograms: 600
Weight in Pounds: 1320.
2. Write a program that asks the user to enter three numbers (use three separate input
statements). Create variables called total and average that hold the sum and average of the
three numbers and print out the values of total and average.
Code:
n1=int(input("Enter First Number: "))
n2=int(input("Enter Second Number: "))
n3=int(input("Enter Third Number: "))
total=n1+n2+n3
average=total/3
print("Total= ",total) print("Average= ",average)
OUTPUT:
Enter First Number: 50
Enter Second Number: 65
Enter Third Number: 78
Total= 193
Average= 64.33333333333333
3.) Write a program that uses a for loop to print the numbers 8, 11, 14, 17, 20, . . . , 83, 86,
89.
Code:
for i in range(8,90,3):
print(i,end=" ")
OUTPUT :
8 11 14 17 20 23 26 29 32 35 38 41 44 47 50 53 56 59 62 65 68 71 74 77 80 83 86 89
4.) Write a program that asks the user to enter a word and prints out whether that word
contains any vowels.
Code:
word=input("Enter a Word: ")
vowel='aeiouAEIOU'
flag=0
for i in vowel:
if i in word:
flag=1
break
if flag==1:
print("Word Contain Vowel")
else: print("Word not Contain Vowel")
OUTPUT: Enter a Word: CRY Word not Contain Vowel
Experiment 3: Functions and Modules –
Functions:
A block of program code which can be reused. It is an organized block of code that can perform
a single, specific, and a well defined task.
In Python, functions can accept different types of arguments, such as positional arguments,
keyword arguments, and default arguments. Functions can also return different types of values,
such as single values, multiple values, or even collections (like lists or dictionaries).
Here’s how to define and call functions with various types of arguments and return values:
1. Function with Positional Arguments
Positional arguments are the most common type, where the order of arguments matters.
# Function with positional arguments
def add_numbers(a, b):
return a + b
# Calling the function
result = add_numbers(5, 3) # Pass values by position
print(result) # Output: 8
2. Function with Default Arguments
You can set default values for parameters. If no argument is provided, the default value is used.
# Function with default arguments
def greet(name="Guest"):
return f"Hello, {name}!"
# Calling the function
print(greet()) # Output: Hello, Guest!
print(greet("Alice")) # Output: Hello, Alice!
3. Function with Keyword Arguments
Keyword arguments are passed with the parameter name, so the order doesn’t matter.
# Function with keyword arguments
def describe_person(name, age, city):
return f"{name} is {age} years old and lives in {city}."
# Calling the function
description = describe_person(name="Bob", age=25, city="New York")
print(description) # Output: Bob is 25 years old and lives in New York.
Python modules:
A module is .py extension file which has the definition of all the functions and variables
that we can use in other programs.
Modules allows to reuse one or more function in the program, even in the programs in
which those functions have not been defined.
The program which wants to use functions and variables defined in the module will use
import keyword to link or import the module or the .py file.
Python comes with a vast standard library of built-in modules, providing a wide range of
functionalities that you can use without having to install third-party libraries. These built-in
modules handle everything from mathematics and file I/O to working with dates and times, and
more.
Here are some key built-in modules, along with examples of how to use them:
1. math
Provides mathematical functions like trigonometry, logarithms, and constants like π (pi).
Example:
import math
print(math.sqrt(16)) # Outputs 4.0
print(math.pi) # Outputs 3.141592653589793
2. datetime
Deals with dates and times, allowing for date arithmetic and formatting.
Example:
from datetime import datetime
now = datetime.now()
print(now) # Outputs the current date and time
3. random
Generates pseudo-random numbers for simulations, games, or simple random operations.
Example:
import random
print(random.randint(1, 10)) # Outputs a random integer between 1 and 10
1. Write a function called sum_digits that is given an integer num and returns the sum of
the digits of num.
CODE:
def sum_digits(num):
sum=0 while(num>0):
sum=sum+num%10
num=num//10
return sum
x=int(input("Enter a number: "))
s=sum_digits(x) print("Sum of digits: ",s)
OUTPUT: Enter a number: 153 Sum of digits: 9
2. Write a script that imports and utilizes at least two different standard library modules.
CODE:
import datetime
import math
# Get the current date and time
current_datetime = datetime.datetime.now()
print(f"Current date and time: {current_datetime}")
# Perform some math operations
number = 16
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")
3. Write a function called number_of_factors that takes an integer and returns how many
factors the number has.
CODE:
def number_of_factors(n):
fact_count=0
for i in range(1,n+1):
if(n%i==0):
fact_count+=1
return fact_count
n=int(input("Enter an integer: "))
x=number_of_factors(n)
print("factors count is",x)
OUTPUT:
Enter an integer: 14 factors count is 4
Experiment 4: Lists and Tuples:
In Python, lists and tuples are both sequence data structures that can store collections of items.
Lists are mutable, meaning they can be modified after creation, while tuples are immutable and
cannot be modified once created. Here’s a guide on creating, modifying, and iterating over both
types:
1. Creating Lists and Tuples
List: Created using square brackets [] or with list() function.
Tuple: Created using parentheses () or with tuple() function.
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
2. Modifying Lists
Lists can be modified in several ways:
Appending items: Adds an item to the end of the list.
Inserting items: Adds an item at a specified index.
Updating items: Changes an item at a specific index.
Removing items: Removes an item by value or by index.
# Append an item
my_list.append(6) # [1, 2, 3, 4, 5, 6]
# Insert an item at index 2
my_list.insert(2, 'new') # [1, 2, 'new', 3, 4, 5, 6]
# Update the first item
my_list[0] = 10 # [10, 2, 'new', 3, 4, 5, 6]
# Remove by value
my_list.remove('new') # [10, 2, 3, 4, 5, 6]
# Remove by index (pop)
removed_item = my_list.pop(1) # Removes item at index 1, list becomes [10, 3, 4, 5, 6]
3. Attempting to Modify Tuples (Immutability)
Tuples are immutable, meaning you cannot change their elements directly. However, you can
create a new tuple by combining slices and additions, or by converting it to a list temporarily.
# Attempting to change a tuple will raise an error:
# my_tuple[0] = 10 # Raises a TypeError
# Workaround: convert to list, modify, then convert back to tuple
temp_list = list(my_tuple)
temp_list[0] = 10
my_tuple = tuple(temp_list) # (10, 2, 3, 4, 5)
4. Iterating Over Lists and Tuples
Both lists and tuples support iteration using a for loop.
# Iterating over a list
for item in my_list:
print(item)
# Iterating over a tuple
for item in my_tuple:
print(item)
5. Other Common Operations
Length: Get the number of items with len().
Slicing: Extract a subset.
Concatenation: Combine two lists or tuples.
Membership Test: Check if an item exists.
# Length
print(len(my_list)) # 5
# Slicing
sub_list = my_list[1:4] # [3, 4, 5]
# Concatenation
new_list = my_list + [7, 8] # [10, 3, 4, 5, 6, 7, 8]
# Membership Test
print(3 in my_list) # True
Lists and tuples offer flexibility for storing and managing data collections in Python, with lists
being ideal for mutable collections and tuples best suited for fixed data.
1. Write a program that generates a list of 20 random numbers between 1 and 100. (a)
Print the list.(b) Print the average of the elements in the list.(c) Print the largest and
smallest values in the list.(d) Print the second largest and second smallest entries in the
list(e) Print how many even numbers are in the list.
CODE:
import random
l=[]
for i in range(20):
l.append(random.randint(1,100))
print("List: ",l)
print("Average: ", round(sum(l)/len(l),2))
print("Largest Value in List: ",max(l))
print("Smallest Value in List: ",min(l))
l1=sorted(l)
print( " Second Largest Value in List: ",l1[-2])
print("Smallest Value in List: ",l1[1])
count=0
for i in l:
if i%2==0:
count+=1
print("Number of Even Numbers in the list: ",count)
OUTPUT: List: [69, 11, 20, 55, 7, 33, 94, 38, 42, 82, 26, 32, 15, 78, 81, 78, 57, 22, 50, 46]
Average: 46.8
Largest Value in List: 94
Smallest Value in List: 7
Second Largest Value in List: 82
Smallest Value in List: 11
Number of Even Numbers in the list: 12
2. Write a program that removes any repeated items from a list so that each item appears
at most once. For instance, the list [1,1,2,3,4,3,0,0] would become [1,2,3,4,0].
CODE:
l=list(map(int,input("Enter the elements into list with duplication: ").split(',')))
s=[]
for i in l:
if i not in s:
s.append(i)
print(s)
OUTPUT: Enter the elements into list with duplication: 1,1,2,56,78,56,1
[1, 2, 56, 78]
Experiment 5: Dictionaries and Sets
Dictionaries in Python are collections of key-value pairs, where each unique key maps to a
specific value. They are mutable, allowing you to add, modify, and delete items.
1. Creating Dictionaries
Using curly braces: {} with key-value pairs separated by colons.
Using dict() function.
# Creating a dictionary with curly braces
person = {"name": "Alice", "age": 30, "city": "New York"}
# Creating a dictionary with dict() function
person = dict(name="Alice", age=30, city="New York")
2. Accessing Dictionary Elements
You can access values by their keys. If a key doesn’t exist, it will raise a KeyError, but you can
use the .get() method to handle missing keys gracefully.
# Accessing values
name = person["name"] # "Alice"
# Accessing values with .get() (returns None if the key doesn’t exist)
age = person.get("age") # 30
height = person.get("height") # None
3. Adding and Updating Dictionary Elements
To add a new key-value pair or update an existing one, use the assignment syntax.
# Adding a new key-value pair
person["profession"] = "Engineer"
# Updating an existing key
person["age"] = 31
4. Removing Dictionary Elements
Dictionaries offer several methods for removing elements:
del: Deletes a specific key.
.pop(): Removes a key and returns its value.
.popitem(): Removes the last inserted key-value pair.
.clear(): Empties the dictionary.
# Deleting a key
del person["city"]
# Removing a key with .pop()
profession = person.pop("profession") # "Engineer"
# Removing the last item with .popitem()
last_item = person.popitem() # ("age", 31)
# Clearing the dictionary
person.clear()
5. Iterating Over Dictionaries
You can iterate over keys, values, or key-value pairs:
# Sample dictionary
person = {"name": "Alice", "age": 31, "city": "New York"}
# Iterating over keys
for key in person:
print(key)
# Iterating over values
for value in person.values():
print(value)
# Iterating over key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
6. Dictionary Comprehensions
Like list comprehensions, dictionaries support comprehensions for generating or transforming
dictionaries.
# Creating a dictionary of squares
squares = {n: n ** 2 for n in range(1, 6)}
# Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Filtering dictionary elements
ages = {"Alice": 25, "Bob": 30, "Charlie": 35}
adults = {k: v for k, v in ages.items() if v >= 30}
# Result: {'Bob': 30, 'Charlie': 35}
7. Merging Dictionaries
You can merge dictionaries using the update() method or the | operator (Python 3.9+).
# Using .update()
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
# Result: {"a": 1, "b": 3, "c": 4}
# Using | operator (Python 3.9+)
dict3 = dict1 | dict2
# Result: {"a": 1, "b": 3, "c": 4}
8. Common Dictionary Methods
.keys(): Returns a view of all keys.
.values(): Returns a view of all values.
.items(): Returns a view of key-value pairs.
keys = person.keys() # dict_keys(['name', 'age', 'city'])
values = person.values() # dict_values(['Alice', 31, 'New York'])
items = person.items() # dict_items([('name', 'Alice'), ('age', 31), ('city', 'New York')])
Sets in Python are unordered collections of unique elements. They are particularly useful
when you need to eliminate duplicates or perform mathematical set operations like union,
intersection, and difference.
1. Creating Sets
Using curly braces {}.
Using the set() function.
# Creating a set with curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set with the set() function
another_set = set([1, 2, 3, 3, 4, 5])
# Duplicate elements are removed, so another_set will be {1, 2, 3, 4, 5}
2. Basic Set Operations
Adding and Removing Elements
.add(): Adds an element to the set.
.remove(): Removes an element (raises KeyError if it doesn’t exist).
.discard(): Removes an element without an error if it doesn’t exist.
.pop(): Removes and returns an arbitrary element.
my_set = {1, 2, 3}
# Adding elements
my_set.add(4) # {1, 2, 3, 4}
# Removing elements
my_set.remove(2) # {1, 3, 4}
my_set.discard(10) # No error, even if 10 is not in the set
# Popping an element (removes an arbitrary element)
removed_element = my_set.pop() # removes 1, resulting in {3, 4}
Checking Membership
Check if an element exists in a set with the in keyword.
print(3 in my_set) # True
print(10 in my_set) # False
3. Mathematical Set Operations
Union
Combines elements from both sets without duplicates.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Using | operator
union_set = set_a | set_b # {1, 2, 3, 4, 5}
# Using union() method
union_set = set_a.union(set_b) # {1, 2, 3, 4, 5}
Intersection
Finds common elements between two sets.
# Using & operator
intersection_set = set_a & set_b # {3}
# Using intersection() method
intersection_set = set_a.intersection(set_b) # {3}
Difference
Finds elements in one set but not in the other.
# Using - operator
difference_set = set_a - set_b # {1, 2}
# Using difference() method
difference_set = set_a.difference(set_b) # {1, 2}
Symmetric Difference
Finds elements in either set, but not in both (elements that are unique to each set).
# Using ^ operator
symmetric_diff_set = set_a ^ set_b # {1, 2, 4, 5}
# Using symmetric_difference() method
symmetric_diff_set = set_a.symmetric_difference(set_b) # {1, 2, 4, 5}
4. Other Common Set Methods
.copy(): Returns a shallow copy of the set.
.clear(): Empties the set.
.issubset(): Checks if one set is a subset of another.
.issuperset(): Checks if one set is a superset of another.
# Copying a set
copied_set = set_a.copy() # {1, 2, 3}
# Clearing a set
set_a.clear() # set_a becomes {}
# Subset and Superset checks
small_set = {1, 2}
big_set = {1, 2, 3, 4}
print(small_set.issubset(big_set)) # True
print(big_set.issuperset(small_set)) # True
5. Set Comprehensions
You can use set comprehensions to create sets dynamically.
# Creating a set of squares for numbers 1 to 5
squares = {x ** 2 for x in range(1, 6)}
# Result: {1, 4, 9, 16, 25}
Sets are powerful when you need to manage collections of unique items and perform set-
theoretic operations efficiently.
Experiment 6: Strings and File I/O
Python provides numerous built-in string methods to manipulate, search, and analyze strings.
Here’s a demonstration of some commonly used string methods.
1. Changing Case
str.upper() and str.lower()
Converts the entire string to uppercase or lowercase.
text = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
str.capitalize() and str.title()
capitalize(): Capitalizes the first character of the string.
title(): Capitalizes the first character of each word.
print(text.capitalize()) # "Hello world"
print(text.title()) # "Hello World"
str.swapcase()
Swaps the case of each character in the string.
print(text.swapcase()) # "hELLO wORLD"
2. String Search and Replace
str.find() and str.index()
find(): Returns the index of the first occurrence of a substring. Returns -1 if not found.
index(): Like find(), but raises a ValueError if the substring is not found.
text = "Hello World"
print(text.find("World")) # 6
print(text.find("Python")) # -1
print(text.index("World")) # 6
# print(text.index("Python")) # Raises ValueError
str.replace()
Replaces all occurrences of a substring with another substring.
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text) # "Hello Python"
3. Checking String Properties
str.isalpha(), str.isdigit(), str.isalnum()
isalpha(): Returns True if all characters are alphabetic.
isdigit(): Returns True if all characters are digits.
isalnum(): Returns True if all characters are alphanumeric (letters and numbers).
print("Hello".isalpha()) # True
print("123".isdigit()) # True
print("Hello123".isalnum()) # True
str.isspace(), str.isupper(), str.islower()
isspace(): Returns True if the string contains only whitespace characters.
isupper(): Returns True if all characters are uppercase.
islower(): Returns True if all characters are lowercase.
print(" ".isspace()) # True
print("HELLO".isupper()) # True
print("world".islower()) # True
4. String Splitting and Joining
str.split()
Splits a string into a list of substrings based on a delimiter (space by default).
text = "Hello World"
words = text.split() # ["Hello", "World"]
print(words)
csv_text = "apple,banana,cherry"
fruits = csv_text.split(",") # ["apple", "banana", "cherry"]
print(fruits)
str.join()
Joins elements of an iterable (like a list) into a single string, using the string as the delimiter.
words = ["Hello", "World"]
joined_text = " ".join(words) # "Hello World"
print(joined_text)
5. Trimming Whitespace
str.strip(), str.lstrip(), str.rstrip()
strip(): Removes whitespace from both ends of the string.
lstrip(): Removes whitespace from the beginning (left side).
rstrip(): Removes whitespace from the end (right side).
text = " Hello World "
print(text.strip()) # "Hello World"
print(text.lstrip()) # "Hello World "
print(text.rstrip()) # " Hello World"
6. String Formatting
str.format()
Formats a string by replacing placeholders with specified values.
name = "Alice"
age = 30
text = "My name is {} and I am {} years old.".format(name, age)
print(text) # "My name is Alice and I am 30 years old."
# Using f-strings (Python 3.6+)
text = f"My name is {name} and I am {age} years old."
print(text) # "My name is Alice and I am 30 years old."
7. String Alignment
str.center(), str.ljust(), str.rjust()
center(width): Centers the string within a specified width.
ljust(width): Left-aligns the string within a specified width.
rjust(width): Right-aligns the string within a specified width.
text = "Hello"
print(text.center(10, "-")) # "--Hello---"
print(text.ljust(10, "-")) # "Hello-----"
print(text.rjust(10, "-")) # "-----Hello"
8. Encoding and Decoding
str.encode() and str.decode()
encode(): Converts a string to bytes using a specified encoding.
decode(): Converts bytes back to a string.
text = "Hello"
encoded_text = text.encode("utf-8")
print(encoded_text) # b'Hello'
decoded_text = encoded_text.decode("utf-8")
print(decoded_text) # "Hello"
In Python, reading from and writing to text files can be easily accomplished using the built-in
open() function, which allows files to be accessed in different modes, such as read ('r'), write
('w'), and append ('a'). Here are some examples:
1. Writing to a Text File
This program opens a file in write mode and writes multiple lines of text to it. If the file doesn’t
exist, it will be created. If it does exist, the contents will be overwritten.
# Writing to a file
filename = "example.txt"
with open(filename, "w") as file:
file.write("Hello, World!\n")
file.write("This is a text file.\n")
file.write("Each line is written separately.\n")
print(f"Data written to {filename}")
2. Appending to a Text File
This program opens a file in append mode to add text without overwriting the existing contents.
# Appending to a file
filename = "example.txt"
with open(filename, "a") as file:
file.write("This line is appended to the file.\n")
print(f"Data appended to {filename}")
3. Reading from a Text File
This program reads the entire contents of a text file and prints them to the console.
# Reading from a file
filename = "example.txt"
with open(filename, "r") as file:
content = file.read()
print("File contents:")
print(content)
4. Reading a File Line by Line
This program reads a file line by line, which is helpful for large files.
filename = "example.txt"
with open(filename, "r") as file:
print("File contents:")
for line in file:
print(line, end="") # `end=""` avoids adding an extra newline
5. Reading and Writing Lists of Strings to a File
If you have a list of strings, you can write each item to a new line in a file and later read it back
into a list.
# List of strings to write
lines = ["First line", "Second line", "Third line"]
# Writing a list of strings to a file
filename = "lines.txt"
with open(filename, "w") as file:
for line in lines:
file.write(line + "\n")
# Reading the list of strings back from the file
with open(filename, "r") as file:
lines_from_file = [line.strip() for line in file] # Using strip() to remove newline characters
print("Read lines from file:")
print(lines_from_file)
6. Using write() with User Input
You can write data to a file using user input.
filename = "user_data.txt"
with open(filename, "w") as file:
while True:
line = input("Enter text to write to the file (or type 'quit' to stop): ")
if line.lower() == 'quit':
break
file.write(line + "\n")
print(f"User data written to {filename}")
7. Error Handling with File Operations
Handling errors is a good practice, especially when dealing with files.
filename = "non_existent_file.txt"
try:
with open(filename, "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print(f"The file {filename} does not exist.")
except IOError:
print("An error occurred while accessing the file.")
Explanation of Modes
'r': Read (default mode). Opens the file for reading; the file must exist.
'w': Write. Opens the file for writing, creating a new file if it doesn’t exist or truncating
(overwriting) if it does.
'a': Append. Opens the file for writing, creating a new file if it doesn’t exist, and
appending data to the end if it does.
'r+': Read and write. Opens the file for both reading and writing.
1. Write a program that reads a file consisting of email addresses, each on its own line.
Your program should print out a string consisting of those email addresses separated by
semicolons.
CODE: file=open(input("Enter file name: "),'r')
Lines=file.readlines()
for line in range(len(Lines)):
if(line==len(Lines)-1):
print('{}'.format(Lines[line].strip()))
else: print('{}'.format(Lines[line].strip()),end=";")
OUTPUT: Enter the file name: ME.txt
ramana@gmail.com;raju@gmail.com;krishne@gmail.com;kiran@gmail.com;ganesh@gm
ail.co m
2. Write a program that reads a list of temperatures from a file called temps.txt, converts
those temperatures to Fahrenheit, and writes the results to a file called ftemps.txt.
CODE:
file1 = open('temps.txt', 'r')
lines = file1.readlines()
file2 = open('ftemps.txt', 'w')
for i in range(len(lines)):
c=lines[i].strip()
f=round((float(c)*1.8)+32,2)
file2.write(str(f)+"\n")
file2.close()
OUTPUT:
Experiment 7: Error Handling and Exceptions
In Python, the try, except, else, and finally blocks are used to handle exceptions and
manage error situations gracefully. Here’s how each block works:
try: Code that might raise an exception is placed inside this block.
except: This block handles the exception if it occurs.
else: This block executes if the code in the try block does not raise an exception.
finally: This block executes no matter what, whether an exception occurred or not. It is
often used for cleanup actions.
Example 1: Basic Exception Handling
This program demonstrates a simple division operation with exception handling.
def divide_numbers():
try:
num1 = float(input("Enter the numerator: "))
num2 = float(input("Enter the denominator: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Please enter valid numbers.")
else:
print(f"The result of {num1} / {num2} = {result}")
finally:
print("Execution of the divide_numbers function is complete.")
divide_numbers()
Example 2: File Operations
This program reads from a file and handles potential file-related errors.
def read_file(filename):
try:
file = open(filename, 'r')
content = file.read()
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except IOError:
print("Error: An error occurred while reading the file.")
else:
print("File contents:")
print(content)
finally:
try:
file.close()
print("File closed successfully.")
except NameError:
print("File was never opened, so no need to close it.")
filename = "example.txt" # Change this to a file that exists or does not exist
read_file(filename)
Example 3: User Input with Exception Handling
This program continuously asks for user input until valid data is provided or the user decides to
exit.
def get_integer():
while True:
try:
number = int(input("Enter an integer (or type 'exit' to quit): "))
except ValueError:
print("Error: That's not a valid integer. Please try again.")
else:
print(f"You entered the integer: {number}")
break # Exit the loop if a valid integer is entered
finally:
print("Attempt to enter an integer is complete.")
get_integer()
Example 4: Multiple Exceptions
This example demonstrates handling multiple exceptions in a single try block.
def process_input():
try:
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
result = num1 / num2
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
else:
print(f"The result of {num1} / {num2} is {result}")
finally:
print("Finished processing input.")
process_input()
Explanation of Each Block
try: The code that might throw an exception is placed here. If an exception occurs,
Python stops executing the try block and jumps to the except block.
except: Handles the exception. You can specify the type of exception to catch (e.g.,
ZeroDivisionError or ValueError) or use a generic except to catch all exceptions.
else: Executes only if no exceptions were raised in the try block. It's useful for code that
should run only when the try was successful.
finally: Runs regardless of whether an exception occurred. It's typically used for cleanup
activities like closing files or releasing resources.
Experiment 8: Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of
"objects," which can contain both data (attributes) and methods (functions). OOP organizes
software design around these objects, enabling easier code maintenance, reusability, and
scalability.
Key Concepts in OOP
1. Class: A blueprint for creating objects (a particular data structure).
2. Object: An instance of a class.
3. Encapsulation: Bundling data and methods that operate on the data within one unit, like
a class.
4. Abstraction: Hiding complex implementation details and showing only the essentials.
5. Inheritance: Allowing a class to inherit properties and methods from another class.
6. Polymorphism: Allowing objects to be treated as instances of their parent class, enabling
one interface to be used for a general class of actions.
Example Program:
Simple OOP with a BankAccount class.
# Define a class called BankAccount
class BankAccount:
# Constructor (initialization method)
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder # Public attribute
self._balance = balance # Protected attribute
# Method to deposit money
def deposit(self, amount):
if amount > 0:
self._balance += amount
print(f"{amount} deposited. New balance: {self._balance}")
else:
print("Deposit amount must be positive.")
# Method to withdraw money
def withdraw(self, amount):
if amount > 0 and amount <= self._balance:
self._balance -= amount
print(f"{amount} withdrawn. New balance: {self._balance}")
else:
print("Invalid withdrawal amount or insufficient funds.")
# Method to display balance
def get_balance(self):
return self._balance
# Create an object (instance) of the BankAccount class
account = BankAccount("Alice", 1000)
# Perform operations
account.deposit(500) # Deposits money
account.withdraw(200) # Withdraws money
print("Final balance:", account.get_balance())
Output:
500 deposited. New balance: 1500
200 withdrawn. New balance: 1300
Final balance: 1300
Experiment 9: Libraries and Packages
In Python, libraries and packages are essential for organizing and reusing code. Libraries are
collections of modules that provide specific functionalities, and packages are directories of
modules that can contain other packages, allowing for organized, modular code.
Libraries and Packages
1. Library: A collection of modules or pre-written code that provides specific functionality.
Python includes a standard library with modules like math, random, and datetime.
2. Package: A collection of modules organized in directories with an __init__.py file, which
allows them to be imported as a single unit.
Using a Library and Package:
For this example, let's use the math library, which is part of Python’s standard library, and
numpy package, a powerful package for numerical computations.
1. Installing a Package: To use numpy, you may need to install it first using:
bash
pip install numpy
2. Sample Program: Using math and numpy to perform calculations.
Here’s a program that demonstrates using the math library and numpy package.
# Importing libraries
import math # Standard library
import numpy as np # Third-party package
# Using the math library for trigonometric operations
angle = 45
radians = math.radians(angle) # Convert degrees to radians
sin_value = math.sin(radians)
cos_value = math.cos(radians)
print(f"Sin({angle}°): {sin_value}")
print(f"Cos({angle}°): {cos_value}")
# Using numpy for array operations
array1 = np.array([1, 2, 3, 4])
array2 = np.array([5, 6, 7, 8])
# Perform element-wise addition
sum_array = np.add(array1, array2)
print("Element-wise sum of arrays:", sum_array)
# Calculate mean of the array
mean_value = np.mean(sum_array)
print("Mean of the resulting array:", mean_value)
Output:
Sin(45°): 0.7071067811865475
Cos(45°): 0.7071067811865476
Element-wise sum of arrays: [ 6 8 10 12]
Mean of the resulting array: 9.0
Experiment 10: Working with Data
Working with data in Python often involves using libraries and packages designed specifically
for data manipulation and analysis. The pandas library is one of the most widely used tools for
this purpose, providing powerful tools for data cleaning, analysis, and visualization.
Sample Program: Working with Data using Pandas
A simple program that:
1. Loads data from a CSV file.
2. Cleans and manipulates the data.
3. Performs basic data analysis.
4. Displays the results.
Step 1: Install Pandas (if you haven't already)
To install pandas, you can use:
bash
pip install pandas
Step 2: Sample Data
Assume we have a file called data.csv with the following contents:
csv
Name,Age,City,Salary
Alice,30,New York,70000
Bob,25,Los Angeles,60000
Charlie,35,Chicago,80000
David,40,New York,90000
Eve,29,Los Angeles,72000
Step 3: Working with Data
Program that loads this CSV, performs data manipulation, and calculates some statistics.
import pandas as pd
# Load data from CSV
data = pd.read_csv('data.csv')
# Display the first few rows of the data
print("Data Overview:")
print(data.head())
# Data Cleaning: Remove any rows with missing values
data = data.dropna()
# Data Manipulation
# 1. Add a new column 'Salary in Thousands' by dividing the Salary column by 1000
data['Salary in Thousands'] = data['Salary'] / 1000
# 2. Filter data for employees in New York
ny_data = data[data['City'] == 'New York']
# 3. Calculate the average age of employees in the dataset
average_age = data['Age'].mean()
# 4. Calculate the average salary by city
average_salary_by_city = data.groupby('City')['Salary'].mean()
# Display results
print("\nUpdated Data with 'Salary in Thousands':")
print(data)
print("\nData for Employees in New York:")
print(ny_data)
print("\nAverage Age of Employees:", average_age)
print("\nAverage Salary by City:")
print(average_salary_by_city)
Output:
Data Overview:
Name Age City Salary
0 Alice 30 New York 70000
1 Bob 25 Los Angeles 60000
2 Charlie 35 Chicago 80000
3 David 40 New York 90000
4 Eve 29 Los Angeles 72000
Updated Data with 'Salary in Thousands':
Name Age City Salary Salary in Thousands
0 Alice 30 New York 70000 70.0
1 Bob 25 Los Angeles 60000 60.0
2 Charlie 35 Chicago 80000 80.0
3 David 40 New York 90000 90.0
4 Eve 29 Los Angeles 72000 72.0
Data for Employees in New York:
Name Age City Salary Salary in Thousands
0 Alice 30 New York 70000 70.0
3 David 40 New York 90000 90.0
Average Age of Employees: 31.8
Average Salary by City:
City
Chicago 80000.0
Los Angeles 66000.0
New York 80000.0
Name: Salary, dtype: float64
Experiment 11: Web Scraping and APIs
Working with APIs in Python
APIs (Application Programming Interfaces) are the most reliable way to retrieve structured data
from online sources, as they are designed for data access.
Key Tasks:
Access and parse data from RESTful APIs
Process and analyze JSON data from APIs
Step-by-Step Guide
Step 1: Set Up Your Environment
Make sure you have a working environment with Python and some essential libraries. Use:
bash
pip install requests
pip install beautifulsoup4
Optional: Install pandas and json if you plan on analyzing the data more thoroughly:
bash
pip install pandas
Step 2: Access and Parse Data from RESTful APIs
1. Identify a RESTful API to Work With
Look for an API that provides useful data, like:
o OpenWeatherMap (for weather data)
o CoinGecko (for cryptocurrency prices)
o NASA API (for space and astronomy data)
2. Register and Obtain API Key (if required)
Some APIs require an API key for access. Follow their registration steps to get your
unique API key.
3. Make Requests to the API
Use the requests library to send GET requests to the API endpoint. Here’s a basic
template:
import requests
# Example: Accessing OpenWeatherMap API (Replace with your API key and city)
url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": "London",
"appid": "your_api_key"
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
data = response.json()
print(data)
else:
print("Failed to retrieve data:", response.status_code)
Step 3: Process and Analyze JSON Data from APIs
1. Extract Useful Information
Access specific values within the JSON data structure by using dictionary keys.
2. Analyze or Clean Data (Optional)
If your data is complex, use the pandas library for better organization.
import pandas as pd
# Convert JSON data to DataFrame (useful for large or nested data)
df = pd.json_normalize(data)
print(df.head())
3. Visualize Data (Optional)
Use libraries like matplotlib or seaborn for basic visualization.
import matplotlib.pyplot as plt
# Plot an example graph if the API returns time series data (like cryptocurrency prices)
plt.plot(df["time"], df["price"])
plt.xlabel("Time")
plt.ylabel("Price")
plt.title("Cryptocurrency Price Over Time")
plt.show()
Web Scraping in Python
When no API is available, you can use web scraping to extract data directly from websites.
Make sure to follow the website's robots.txt file and respect their terms of service.
While APIs are ideal for structured data, sometimes you may need to scrape data from websites
without APIs. Use BeautifulSoup for this:
1. Send a Request to the Web Page
from bs4 import BeautifulSoup
url = "http://example.com"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, "html.parser")
print(soup.prettify())
2. Parse and Extract Data
Use HTML tags and classes to find the data you need.
# Example: Find all headlines on the page
headlines = soup.find_all("h1")
for headline in headlines:
print(headline.text)
Note: Follow ethical guidelines when web scraping—always check the website’s robots.txt file
and terms of service.
Experiment 12: Databases
Working with databases is essential for many applications, allowing you to store and manipulate
structured data efficiently. In Python, we can use libraries like sqlite3 (for SQLite databases) or
SQLAlchemy (for relational databases like MySQL, PostgreSQL) to interact with databases.
To work with databases in Python, the sqlite3 module is a great starting point because it allows
you to set up and manipulate an SQL database directly from Python without needing a separate
server. Here’s a basic guide to help you with Experiment 12, working with databases in Python.
1. Setting Up a Database and Connecting
import sqlite3
# Connect to a database (or create one if it doesn’t exist)
connection = sqlite3.connect('experiment12.db')
# Create a cursor object to execute SQL commands
cursor = connection.cursor()
2. Creating Tables
Once connected, you can create a table in the database. Here’s an example of creating a table
called students.
# SQL command to create a table
create_table_query = '''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
'''
# Execute the command
cursor.execute(create_table_query)
3. Inserting Data
You can insert data into the table using INSERT INTO.
# Sample data to insert
insert_query = 'INSERT INTO students (name, age, grade) VALUES (?, ?, ?)'
data = [
('Alice', 20, 'A'),
('Bob', 22, 'B'),
('Charlie', 21, 'A')
# Insert multiple records
cursor.executemany(insert_query, data)
connection.commit() # Save changes
4. Querying Data
Retrieve data using SELECT commands.
# Retrieve all records
select_query = 'SELECT * FROM students'
cursor.execute(select_query)
# Fetch all records
rows = cursor.fetchall()
for row in rows:
print(row)
5. Updating and Deleting Data
To update data in a database, use UPDATE, and to delete records, use DELETE.
# Update a record
update_query = 'UPDATE students SET grade = ? WHERE name = ?'
cursor.execute(update_query, ('A+', 'Bob'))
connection.commit()
# Delete a record
delete_query = 'DELETE FROM students WHERE name = ?'
cursor.execute(delete_query, ('Charlie',))
connection.commit()
6. Closing the Connection
After you’re done, close the connection.
# Close the cursor and connection
cursor.close()
connection.close()
Sample Program
Here’s a complete example combining the above steps.
import sqlite3
# Connect to database
connection = sqlite3.connect('experiment12.db')
cursor = connection.cursor()
# Create table
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
''')
# Insert data
data = [
('Alice', 20, 'A'),
('Bob', 22, 'B'),
('Charlie', 21, 'A')
cursor.executemany('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', data)
connection.commit()
# Query data
cursor.execute('SELECT * FROM students')
print("Data in students table:")
for row in cursor.fetchall():
print(row)
# Update data
cursor.execute('UPDATE students SET grade = ? WHERE name = ?', ('A+', 'Bob'))
connection.commit()
# Delete data
cursor.execute('DELETE FROM students WHERE name = ?', ('Charlie',))
connection.commit()
# Close connection
cursor.close()
connection.close()
Retrieving Data
Retrieve data using SELECT queries. You can use different conditions, sorting, and
grouping.
a. Retrieve All Records
cursor.execute('SELECT * FROM students')
all_students = cursor.fetchall()
for student in all_students:
print(student)
b. Retrieve Specific Columns
Retrieve only the name and grade of each student:
cursor.execute('SELECT name, grade FROM students')
students = cursor.fetchall()
for student in students:
print(student)
c. Retrieve Data with Conditions (WHERE Clause)
Retrieve students who have a grade of "A":
cursor.execute("SELECT * FROM students WHERE grade = 'A'")
a_students = cursor.fetchall()
for student in a_students:
print(student)
d. Sorting Data (ORDER BY Clause)
Retrieve all students sorted by age in descending order:
cursor.execute('SELECT * FROM students ORDER BY age DESC')
sorted_students = cursor.fetchall()
for student in sorted_students:
print(student)
e. Limiting the Number of Results (LIMIT Clause)
Retrieve the top two students with the highest age:
cursor.execute('SELECT * FROM students ORDER BY age DESC LIMIT 2')
top_two_students = cursor.fetchall()
for student in top_two_students:
print(student)
f. Advanced Queries
i. Count Records
Count the number of students:
cur.sor.execute('SELECT COUNT(*) FROM students')
count = cursor.fetchone()[0]
print("Total students:", count)
ii. Group By and Aggregate Functions
Get the number of students in each grade:
cursor.execute('''
SELECT grade, COUNT(*)
FROM students
GROUP BY grade
''')
grade_counts = cursor.fetchall()
for grade, count in grade_counts:
print(f"Grade {grade}: {count} students")
iii. Finding Maximum, Minimum, Average
Find the average age of students:
cursor.execute('SELECT AVG(age) FROM students')
average_age = cursor.fetchone()[0]
print("Average age:", average_age)