Python Lab Programs

Index

Note some of these programs are self-written and not validated by a faculty member. Although these programs are correct and should work in practical exams, please use it at your own RISK!!!!!

-Shelton Coutinho

Part A

  1. Check if a number belongs to the Fibonacci Sequence
  2. Solve Quadratic Equations
  3. Find the sum of n natural numbers
  4. Display Multiplication Tables
  5. Check if a given number is a Prime Number or not
  6. Implement a sequential search
  7. Create a calculator program
  8. Explore string functions
  9. Implement Selection Sort
  10. Implement Stack
  11. Read and write into a file

Part B

  1. Demonstrate usage of basic regular expression
  2. Demonstrate use of advanced regular expressions for data validation.
  3. Demonstrate use of List
  4. Demonstrate use of Dictionaries
  5. Create SQLite Database and Perform Operations on Tables
  6. Create a GUI using Tkinter module
  7. Demonstrate Exceptions in Python
  8. Drawing Line chart and Bar chart using Matplotlib
  9. Drawing Histogram and Pie chart using Matplotlib
  10. Create Array using Num Py and Perform Operations on Array
  11. Create Data Frame from Excel sheet using Pandas and Perform Operations on Data Frames

Important Question (Viva)

Programs

1.Check if a number belongs to the Fibonacci Sequence

import math

def ips(x):
    s = int(math.sqrt(x))
    return s*s==x

n = int(input('Enter n: '))
if(ips(5*n*n+4) or ips(5*n*n-4) == True):
    print(n, "is a Fibonacci number")
else:
    print(n, "is not a Fibonacci number")

2. Solve Quadratic Equations

import cmath

a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

d = (b**2) - (4*a*c)

sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solutions are {0} and {1}'.format(sol1,sol2))

3. Find the sum of n natural numbers

n = int(input('Enter n: '))
if(n<0):
    print('Enter Positive number')
else:
    sum = n * (n + 1) // 2
    print(f'The sum of the first {n} natural numbers is {sum}')

4. Display Multiplication Tables

num = int(input('Enter a number: '))

for i in range(1, 11):
    print(f'{num} x {i} = {num * i}')

5. Check if a given number is a Prime Number or not

num = int(input('Enter a number: '))

if num > 1:
    for i in range(2, num):
        if (num % i) == 0:
            print(f'{num} is not a prime number')
            break
    else:
        print(f'{num} is a prime number')
else:
    print(f'{num} is not a prime number')

6. Implement a sequential search

n= int(input('Enter length: '))
arr = []
for i in  range(n):
    arr.append(int(input((f"Enter element {i+1}: "))))
x = int(input("Enter search element: "))
for i in range(0, n):
        if arr[i] == x:
            print(f"Element found at {i+1} location")
            break
else:
    print("Element not found")

7. Create a calculator program

a = int(input("Enter a: "))
b = int(input("Enter b: "))
print("Enter operation to be performed")
c = int(input("1. Add\n2. Substract\n3. Divide\n4. Multiply\n"))
if c==1:
    print(f"{a} + {b} = {a+b}")
elif c==2:
    print(f"{a} - {b} = {a-b}")
elif c==3:
    print(f"{a} / {b} = {a/b}")
elif c==4:
    print(f"{a} * {b} = {a*b}")

8. Explore string functions

str = "Hello World!"
print("Original String: ", str)
print("Upper case: ", str.upper())
print("Swap case of the charector: ", str.swapcase())
print("Lower case: ", str.lower())
print("Replace o with x: ", str.replace("o", "x"))
print("Convert first character to upper case and rest to lowercase: ", str.capitalize())

9. Implement Selection Sort

def selection_sort(arr):
    for i in range(len(arr)):
        min_idx = i
        for j in range(i+1, len(arr)):
            if arr[min_idx] > arr[j]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
print("Sorted array:", selection_sort(arr))

10. Implement Stack

def push(n):
    if len(a)<s:
        a.append(n)
        print(f"Pushed {n} in Stack")
    else:
        print("Stack is full")

def display():
    print("Stack elements are: ")
    for i in range(len(a)):
        print(a[i])

def pop(n):
    if len(a)>0:
        print(f"Poped {a[n]} in Stack")
        a.pop(n)
    else:
        print("Stack is empty")

a =[]
s = 3
push(1)
push(2)
push(3)
display()
pop(1)
display()

11. Read and write into a file

import os

def create_file(fn):
    try:
        with open(fn, 'w') as f:
            f.write('Hello World!\n')
        print("File "+fn+" created successfully")
    except IOError:
        print("Couldnt create.")

def read_file(fn):
    try:
        with open(fn, 'r') as f:
            contents = f.read()
        print(contents)
    except IOError:
        print("Error: could not read file")

def append_file(fn, txt2):
    try:
        with open(fn, 'a') as f:
            f.write(txt2)
        print(txt2, ' : string appended in ',fn)
    except IOError:
        print("Error could not append file.")

def delete_file(fn):
    try:
        os.remove(fn)
        print("File "+fn+" deleted successfully.")
    except IOError:
        print("Error: could not delete file")

fn = "example.txt"
nfn = "new_example.txt"
create_file(fn)
read_file(fn)
append_file(fn, 'This text is appended.')
print("After Appending contents of file are: ")
read_file(fn)
delete_file(fn)

Part B

1. Demonstrate usage of basic regular expression

import re

txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)
if x:
    print("Yes! We have a match!")
else:
    print("No match")

x = re.sub("\s", "9", txt)
print(x)

x = re.findall("ai", txt)
print(x)

2. Demonstrate use of advanced regular expressions for data validation.

import re

def isValid(n, e):
    x = re.match("(0|91)?[6-9][0-9]{9}", n)
    y = re.match(r"[^@]+@[^@]+\.[^@]+", e)
    return x, y

n = input("Enter phone number: ")
e = input("Enter email: ")
x, y = isValid(n, e)
if(len(n) > 13):
    print("Invalid input number of digits more than 12")
elif x:
    print("Valid number")
else:
    print("Not Valid number")
if y:
    print("is Valid email address")
else:
    print("Not Valid email address")

3. Demonstrate use of List

list1 = [10, 20, "python", 15.9, 30]
list2 = ["Amy", "Ryan", "Henry", "Emma"]
list3 = [9, 8, 7]

print("Repetition of the list")
print(list1*2)

print("Concatenation of the list")
print(list1+list2)

print("Length of the list")
print(len(list1))

print("Appending elements of the list")
list2.append("Eleven")
print(list2)

print("Extending the list")
list1.extend(list3)
print(list1)

4. Demonstrate use of Dictionaries

dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

dict2 = dict1.copy()
print(dict2)

dict1.clear()
print(dict1)

print(dict2.get(1))

print(dict2.items())

print(dict2.keys())

dict2.pop(4)
print(dict2)

dict2.popitem()
print(dict2)

dict2.update({3: "Scala"})
print(dict2)

print(dict2.values())

5. Create SQLite Database and Perform Operations on Tables

import sqlite3

con = sqlite3.connect('database.db')
cursor = con.cursor()

cursor.execute('''create table employees
               (id int,
                name text,
                age int,
                address text,
                salary int);''')
print("Table created")

cursor.execute("insert into employees values(1, 'Chandler', 21, 'NewYork', 20000)")
cursor.execute("insert into employees values(2, 'Pheobe', 22, 'NewYork', 30000)")
cursor.execute("insert into employees values(3, 'Monika', 24, 'NewYork', 45000)")

data = cursor.execute("select * from employees")

for row in data:
    print(row)

6. Create a GUI using Tkinter module

Option 1 (learn any one program)

#simple version
import tkinter as tk

root = tk.Tk()

label = tk.Label(root, text="Hello, world!")

button = tk.Button(root, text="Click me", command=root.destroy)

label.pack()
button.pack()

root.mainloop()

Option 2

#little complex version
from tkinter import *

root = Tk()
root.geometry("500x500")

lb1 = Label(root, text = "Enter name: ").pack()
en1 = Entry(root).pack()

lb2 = Label(root, text = "Enter Email: ").pack()
en2 = Entry(root).pack()

lb3 = Label(root, text = "Select Gender: ").pack()
Radiobutton(root, text="Male", value = 1).pack()
Radiobutton(root, text="Female", value = 2).pack()
Radiobutton(root, text="Other", value = 3).pack()

lb4 = Label(root, text = "Select country: ").pack()
c = ("US", "In", "Ne", "Ge")
cv = StringVar()
dl = OptionMenu(root, cv, *c).pack()
cv.set("US")

Button(root, text="Register").pack()

root.mainloop()

7. Demonstrate Exceptions in Python

a = int(input("Enter a: "))
b = int(input("Enter b: "))

try:
    x = a / b
except ZeroDivisionError as e:
    print(f"An error occurred: {e}")
else:
    print(f"The result is {x}")
finally:
    print("This code will always be executed")

8. Drawing Line chart and Bar chart using Matplotlib. (Note: You will require a tips.csv file to be present in the same directory as your source code, for the program to work.)

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("tips.csv")

plt.plot(data['tip'])
plt.plot(data['size'])
plt.title("Scatter Plot")

plt.xlabel('Day')
plt.ylabel('Tip')

plt.show()

plt.bar(data['day'], data['tip'])
plt.title("BarChart")

plt.xlabel('Day')
plt.ylabel('Tip')

plt.show()

If you don’t know how to deal with a .csv file then use the program below.

import pandas as pd
import matplotlib.pyplot as pyp

gta = ["GTA I", "GTA II", "GTA III", "GTA IV"]
sales = [5, 20, 50, 20]

pyp.title("Scater plot")
pyp.plot(gta, sales)
pyp.xlabel("gta")
pyp.ylabel("sales")
pyp.show()

pyp.title("Bar chart")
pyp.bar(gta, sales)
pyp.xlabel("gta")
pyp.ylabel("sales")
pyp.show()

9. Drawing Histogram and Pie chart using Matplotlib

import pandas as pd
import matplotlib.pyplot as plt

gta = ["GTA V", "GTA IV", "GTA III", "GTA II"]
sales = [80, 40, 20, 10]

plt.title('Histogram')
plt.hist(sales)
plt.show()

plt.pie(sales, labels = gta)
plt.show()

10. Create Array using Num Py and Perform Operations on Array

import numpy as np

a = np.array([1, 2, 4, 3])

print("Add 1 to all elements: ", a+1)
print("Subtract 3 from all elements: ", a-3)
print("Multiply each value by 10: ", a*10)
print("Squaring each element: ", a**2)
a*=2
print("Doubled each element of original array: ", a)
a=np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
print("\nOriginal array:\n", a)
print("\nTranspose array:\n", a.T)

11. Create Data Frame from Excel sheet using Pandas and Perform Operations on Data Frames. (Note: You will require a CardioGoodFitness.xlsx file to be present in the same directory as your source code, for the program to work.)

# import pandas module
import pandas as pd

df = pd.read_excel("CardioGoodFitness.xlsx")
print("Original Database")
print(df.head())

print("\nSelecting a single column Age")
age = df["Age"]
print(age.head())

print("\nSelecting a single row")
male = df.loc[2]
print(male.head())

print("\nManipulate dataframe values")
Status = []
for i in range(len(df)):
    stat = df["Fitness"][3]<(df["Fitness"][i])
    Status.append(stat)
df["Health"] = Status
print(df.head())

print("\nFilter Data Entries")
Males = df[ df["Gender"] == "Male"]
print(Males.head())

Important Question (Viva)

1. Explain string function in python.
Ans: 
lower(): Converts all uppercase characters in a string into lowercase
upper(): Converts all lowercase characters in a string into uppercase
title(): Convert string to title case
swapcase(): Swap the cases of all characters in a string
capitalize(): Convert the first character of a string to uppercase

2. Define inheritance. Explain different types of inheritance in python.
Ans: 
Single inheritance enables a derived class to inherit properties from a single parent class, thus enabling code reusability and the addition of new features to existing code.
When a class can be derived from more than one base class this type of inheritance is called multiple inheritances. In multiple inheritances, all the features of the base classes are inherited into the derived class. 
When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

3. What are different looping statements in python.
Ans: For loop, while loop, nested loops, infinite while loop
4. Write characteristics of lists (Any 2-3 is enough).
Ans: Lists are ordered
List elements can be accessed by index
Lists are mutable
Lists can contain any arbitrary objects
Lists can be nested to arbitrary depth
Lists allow duplicate values
5. What are different decision making statements in python.
Ans: If else
6. What is Slicing?
Ans: You can return a range of characters by using the slice syntax.
Shelton Coutinho
Shelton Coutinho
Articles: 13

Leave a Reply

Your email address will not be published. Required fields are marked *