Python Programming Lab Record Manual
Python Programming Lab Record Manual
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:
Click on Download.
Choose the correct version for your operating system (Windows, macOS, or Linux).
For Windows:
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).
bash
Copy code
anaconda-navigator
Spyder IDE comes pre-installed with the Anaconda distribution, but if it isn’t, or if you need to
update it, follow these steps.
Click the checkbox next to Spyder, then click Apply to install it.
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
3. Conditional Statements
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.
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:
pounds=2.2*kilograms
OUTPUT:
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:
total=n1+n2+n3
average=total/3
OUTPUT:
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:
vowel='aeiouAEIOU'
flag=0
for i in vowel:
if i in word:
flag=1
break
if flag==1:
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:
Positional arguments are the most common type, where the order of arguments matters.
return a + b
print(result) # Output: 8
You can set default values for parameters. If no argument is provided, the default value is used.
def greet(name="Guest"):
Keyword arguments are passed with the parameter name, so the order doesn’t matter.
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
2. datetime
Deals with dates and times, allowing for date arithmetic and formatting.
Example:
now = datetime.now()
3. random
Example:
import random
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
2. Write a script that imports and utilizes at least two different standard library modules.
CODE:
import datetime
import math
current_datetime = datetime.datetime.now()
number = 16
square_root = math.sqrt(number)
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
x=number_of_factors(n)
OUTPUT:
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
2. Modifying Lists
# Append an item
my_list.append(6) # [1, 2, 3, 4, 5, 6]
# Remove by value
my_list.remove('new') # [10, 2, 3, 4, 5, 6]
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
# 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)
l1=sorted(l)
count=0
for i in l:
if i%2==0:
count+=1
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
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:
s=[]
for i in l:
if i not in s:
s.append(i)
print(s)
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
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
To add a new key-value pair or update an existing one, use the assignment syntax.
# Sample dictionary
person = {"name": "Alice", "age": 31, "city": "New York"}
6. Dictionary Comprehensions
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}
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
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
Checking Membership
Union
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Using | operator
union_set = set_a | set_b # {1, 2, 3, 4, 5}
Intersection
Difference
# Using - operator
difference_set = set_a - set_b # {1, 2}
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}
# Copying a set
copied_set = set_a.copy() # {1, 2, 3}
# Clearing a set
set_a.clear() # set_a becomes {}
5. Set Comprehensions
You can use set comprehensions to create sets dynamically.
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.swapcase()
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.
print(text.index("World")) # 6
# print(text.index("Python")) # Raises ValueError
str.replace()
print("Hello".isalpha()) # True
print("123".isdigit()) # True
print("Hello123".isalnum()) # True
str.split()
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.
5. Trimming Whitespace
6. String Formatting
str.format()
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."
7. String Alignment
text = "Hello"
print(text.center(10, "-")) # "--Hello---"
print(text.ljust(10, "-")) # "Hello-----"
print(text.rjust(10, "-")) # "-----Hello"
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:
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"
This program opens a file in append mode to add text without overwriting the existing contents.
# Appending to a file
filename = "example.txt"
print("File contents:")
print(content)
This program reads a file line by line, which is helpful for large files.
filename = "example.txt"
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.
filename = "lines.txt"
file.write(line + "\n")
lines_from_file = [line.strip() for line in file] # Using strip() to remove newline characters
print("Read lines from file:")
print(lines_from_file)
filename = "user_data.txt"
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")
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.
Lines=file.readlines()
if(line==len(Lines)-1):
print('{}'.format(Lines[line].strip()))
else: print('{}'.format(Lines[line].strip()),end=";")
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:
lines = file1.readlines()
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.
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.
def divide_numbers():
try:
except ZeroDivisionError:
except ValueError:
else:
finally:
divide_numbers()
This program reads from a file and handles potential file-related errors.
def read_file(filename):
try:
content = file.read()
except FileNotFoundError:
except IOError:
else:
print("File contents:")
print(content)
finally:
try:
file.close()
except NameError:
filename = "example.txt" # Change this to a file that exists or does not exist
read_file(filename)
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:
else:
finally:
get_integer()
def process_input():
try:
else:
finally:
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.
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.
Example Program:
class BankAccount:
if amount > 0:
self._balance += amount
self._balance -= amount
else:
def get_balance(self):
return self._balance
# Perform operations
Output:
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
Here’s a program that demonstrates using the math library and numpy package.
# Importing libraries
angle = 45
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
mean_value = np.mean(sum_array)
Output:
Sin(45°): 0.7071067811865475
Cos(45°): 0.7071067811865476
bash
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
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')
print("Data Overview:")
print(data.head())
data = data.dropna()
# Data Manipulation
# 1. Add a new column 'Salary in Thousands' by dividing the Salary column by 1000
average_age = data['Age'].mean()
average_salary_by_city = data.groupby('City')['Salary'].mean()
# Display results
print(data)
print(ny_data)
print(average_salary_by_city)
Output:
Data Overview:
City
Chicago 80000.0
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:
Step-by-Step Guide
Make sure you have a working environment with Python and some essential libraries. Use:
bash
Optional: Install pandas and json if you plan on analyzing the data more thoroughly:
bash
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"
if response.status_code == 200:
data = response.json()
print(data)
else:
import pandas as pd
print(df.head())
# 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.show()
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:
url = "http://example.com"
response = requests.get(url)
if response.status_code == 200:
print(soup.prettify())
headlines = soup.find_all("h1")
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.
import sqlite3
connection = sqlite3.connect('experiment12.db')
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.
create_table_query = '''
age INTEGER,
grade TEXT
'''
cursor.execute(create_table_query)
3. Inserting Data
You can insert data into the table using INSERT INTO.
insert_query = 'INSERT INTO students (name, age, grade) VALUES (?, ?, ?)'
data = [
cursor.executemany(insert_query, data)
4. Querying Data
cursor.execute(select_query)
rows = cursor.fetchall()
print(row)
To update data in a database, use UPDATE, and to delete records, use DELETE.
# Update a record
connection.commit()
# Delete a record
cursor.execute(delete_query, ('Charlie',))
connection.commit()
cursor.close()
connection.close()
Sample Program
import sqlite3
# Connect to database
connection = sqlite3.connect('experiment12.db')
cursor = connection.cursor()
# Create table
cursor.execute('''
age INTEGER,
grade TEXT
)
''')
# Insert data
data = [
cursor.executemany('INSERT INTO students (name, age, grade) VALUES (?, ?, ?)', data)
connection.commit()
# Query data
print(row)
# Update data
connection.commit()
# Delete data
connection.commit()
# Close connection
cursor.close()
connection.close()
Retrieving Data
Retrieve data using SELECT queries. You can use different conditions, sorting, and
grouping.
all_students = cursor.fetchall()
print(student)
students = cursor.fetchall()
print(student)
a_students = cursor.fetchall()
print(student)
sorted_students = cursor.fetchall()
top_two_students = cursor.fetchall()
print(student)
f. Advanced Queries
i. Count Records
count = cursor.fetchone()[0]
cursor.execute('''
FROM students
GROUP BY grade
''')
grade_counts = cursor.fetchall()
average_age = cursor.fetchone()[0]