0% found this document useful (0 votes)
47 views

APP File

This document contains a bonafide certificate for an Advanced Programming Practices course completed by a student. It includes their name, registration number, branch, and semester. It also contains the signature of the lab in charge and head of the computer science department, verifying the student sat for the university examination. The rest of the document contains an index of 20 experiments completed as part of the course, listing the topic, date, and signature for each one. The experiments cover a range of programming paradigms and concepts like structured programming, object oriented programming, event driven programming, and parallel, concurrent, functional, and logic programming.

Uploaded by

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

APP File

This document contains a bonafide certificate for an Advanced Programming Practices course completed by a student. It includes their name, registration number, branch, and semester. It also contains the signature of the lab in charge and head of the computer science department, verifying the student sat for the university examination. The rest of the document contains an index of 20 experiments completed as part of the course, listing the topic, date, and signature for each one. The experiments cover a range of programming paradigms and concepts like structured programming, object oriented programming, event driven programming, and parallel, concurrent, functional, and logic programming.

Uploaded by

Sahil Pahwa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Advanced Programming Practices

(18CSC207J)

Submitted by:
Name:
Reg No:
Branch:

Sem-IV Year-II
( 20__ - 20__ )
BONAFIDE CERTIFICATE

Registration no. _______________


Certified to be the bonafide record of work done by _________________of 4
semester 2nd year B.TECH degree course in SRM INSTITUTE OF SCIENCE
AND TECHNOLOGY, NCR Campus of Department of Computer Science &
Engineering in ADVANCED PROGRAMMING PRACTICE (18CSC207J) during
the academic year 2022-2023.

Lab In charge Head of the Department


(CSE)

Submitted for university examination held on _____________ at SRM IST, NCR Campus.

Internal Examiner-I Internal Examiner-II


INDEX

Exp Topic Date Signature


No.

1 To find out whether the given number is even


or odd

2 Display Fibonacci Series using python

3 To Implement Inheritance in Python

4 Implement Inheritance in Python

5 To change color on click in TKinter

6 To show Declarative Programming in SQL


using Python

7 Check whether the number is prime number or


not.

8 Create process using multiprocessing

9 Create a set of process and submit a task of


squaring the number.

10 Create new threads by using threading library.

11 Program to demonstrate pure functions.

12 Program that will find the sum of all the


elements of a list using recursion.
13 Program to find factorial of a number using
pydatalog

14 Python program for a simple calculator.

15 Implement Tan trigonometric functions using


python

16 To make a simple Calculator GUI using Tkinter

17 To establish a TCP connection between Client


and Server python programs

18 To establish a UDP connection between Client


and Server python programs

19 To Implement Deterministic Finite Automata


using python

20 To Implement Non-Deterministic Finite


Automata using python
Experiment-1
Structured Programming

Aim: To find out whether the given number is even or odd

Source Code:

x=int(input("Enter the number"))


if x % 2 == 0:
print("The number is even.")
else:
print(“The number is odd”)

Output:
Experiment-2
Structured Programming

Aim: Display Fibonacci Series using python

Source Code:

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output:
Experiment-3
Procedural Programming

Aim: Implement various types of functions in python

Source Code:
# Function with no return and no parameters
result = 23

def main():
add(2,3,result)
print(get_result())
print(get_difference(3,1))
# keyword argument usage
keyword_arg(y = "a", x = "b")

variable_length(2,2,3,4,5,5,k = 5, j = 4)

# function function with parameter but no return


def add(a,b,r):
pass

# function with no parameter but return


def get_result():
global result
return result

# function with parameter and return


def get_difference(x,y):
return x-y

# function with default arguments


def keyword_arg(x,y, defa = "Default value"):
print(f"The value of x is{x} and the value of y is {y}")
print(f"The value of the default argument def is: {defa}")

def variable_length(x,*args,**kwargs):
print("The value of keyword argument x is: ",x)
print("Following are the values inside args:")
for i in args:
print("\t",i)
for k, v in kwargs.items():
print(k, '=', v)

if __name__ == "__main__":
main()

Output:
Experiment-4
Object Oriented Programming

Aim: Implement Inheritance in Python

Source Code:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

employed = None

def say_name(self):
print("My name is ", self.name, "and my employement status is:", self.employed)

class Employee(Person):
def __init__(self, name, age):
super().__init__(name, age)
self.employed = True

if __name__ == "__main__":
p1 = Person("Raj", 24)
e1 = Employee("Raju", 26)

e1.say_name()
p1.say_name()

Output:
Experiment-5
Event Driven Programming

Aim: To change color on click in TKinter

Source Code:
from tkinter import *
obj = Tk()
obj.title("event")
obj.geometry("200x200")
def show(e):
obj.configure(background="pink")
def show1(e):
obj.configure(background="yellow")
def show2(e):
obj.configure(background="green")
b1=Button(obj,text ="click me",font=(„Times New Roman‟,20))
b1.bind("<Button-1>",show)
b1.bind("<Button-2>",show1)
b1.bind("<Button-3>",show2)
b1.pack()
obj.mainloop()

Output:
Experiment-6
Declarative Programming

Aim: To show Declarative Programming in SQL using Python

Source Code:
import sqlite3

conn = sqlite3.connect('geeks2.db')

cursor = conn.cursor()

table ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),


SECTION VARCHAR(255));"""
cursor.execute(table)

cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')


cursor.execute('''INSERT INTO STUDENT VALUES ('Shyam', '8th', 'B')''')
cursor.execute('''INSERT INTO STUDENT VALUES ('Baburao', '9th', 'C')''')

print("Data Inserted in the table: ")


data=cursor.execute('''SELECT * FROM STUDENT''')
for row in data:
print(row)

conn.commit()
conn.close()
Output:
Experiment-7
Imperative Programming

Aim:Check whether the number is prime number or not.

Source Code:
num=int(input("Enter an number:"))
if(num==1):
print(num," is not a prime number")
elif(num==2):
print(num,"is a prime number")
else:
for i in range(2,int(num/2)):
if(num%i==0):
flag=0
break
if(flag==1):
print(num,"is a prime number")
else:
print(num," is not a prime number")

Output:
Experiment-8
Parallel Programming

Aim:- Create process using multiprocessing

Source Code:
import multiprocessing
import time
class Process(multiprocessing.Process):
def __init__(self, id):
super(Process, self).__init__()
self.id = id
def run(self):
time.sleep(1)
print("I'm the process with id: {}".format(self.id))
if __name__ == '__main__':
p = Process(0)
p.start()
p.join()
p = Process(1)
p.start()
p.join()

Output:
Experiment-9
Structured Programming

Aim: Create a set of process and submit a task of squaring the


number.

Source Code:
import multiprocessing
import time
def square(x):
return x * x

if __name__ == '__main__':
pool = multiprocessing.Pool()
pool = multiprocessing.Pool(processes=4)
inputs = [0,1,2,3,4]
outputs = pool.map(square, inputs)
print("Input: {}".format(inputs))
print("Output: {}".format(outputs))

Output:
Experiment-10
Concurrent Programming

Aim: Create new threads by using threading library.

Source Code:
import threading
def print_cube(num):
print("Cube: {}".format(num*num*num))
def print_square(num):
print("Square: {}\n".format(num*num))
if __name__ == "__main__":
t1=threading.Thread(target=print_square,args=(10,))
t2=threading.Thread(target=print_cube,args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Done!")

Output:
Experiment-11
Functional Programming

Aim: Program to demonstrate pure functions.

Source Code:
def pure_func(List):
New_List = []
for i in List:
New_List.append(i**2)
return New_List
Original_List = [1, 2, 3, 4]

Modified_List = pure_func(Original_List)
print("Original List:", Original_List)
print("Modified List:", Modified_List)

Output:
Experiment-12
Functional Programming

Aim: Program that will find the sum of all the elements of a list using
recursion.

Source Code:
def Sum(L, i, n, count):
if n <= i:
return count
count += L[i]
count = Sum(L, i + 1, n, count)
return count
L = [1, 2, 3, 4, 5]
count = 0
n = len(L)
print(Sum(L, 0, n, count))

Output:
Experiment -13
Logic programming

Aim: Program to find factorial of a number using pydatalog

Source code :

from pyDatalog import pyDatalog pyDatalog.create_terms('factorial, N')


factorial[N] = N*factorial[N-1]
factorial[1] = 1
print(factorial[2]==N)

Output
Experiment -14
Dependent Type Programming

Aim :Python program for a simple calculator.

Source code:
a = int(input("Enter First number : "))
b = int(input("Enter Second number : "))
operator = input("Enter mathematical operation : ")
flag=1
if operator == '+':
result = a + b
elif operator == '-':
result=a-b
elif operator == '*':
result=a*b
elif operator == '/':
result=a/b
elif operator == '^':
result=a**b
elif operator == '%':
result=a%b
elif operator == '//':
result=a//b
else:
print("Invalid Operation!!!")
flag=0
if flag == 1:
print(str(a)+operator+str(b)+" =",result)

OUTPUT
Experiment -15
Symbolic Programming

Aim: Implement Tan trigonometric functions using python

Source code:

import sympy as sym


x= sym.symbols('x')
y= sym.symbols('y')
c= sym.simplify(sym.sin(x)/sym.cos(x))
print(c)

Output:
Experiment-16
GUI Programming

Aim: To make a simple Calculator GUI using Tkinter

Source Code:
import tkinter as tk

root = tk.Tk()
root.geometry("600x400")
root.title("Simple Calculator")

def add():
number1 = int(entry_one.get())
number2 = int(entry_two.get())

label_answer.config(text = str(number1+number2))

def sub():
number1 = int(entry_one.get())
number2 = int(entry_two.get())

label_answer.config(text = str(number1-number2))

def mul():
pass
number1 = int(entry_one.get())
number2 = int(entry_two.get())

label_answer.config(text = str(number1*number2))

label_one = tk.Label(root, text = "Number 1: ")


label_two = tk.Label(root, text = "Number 2: ")

label_one.grid(row = 0, column = 0)
label_two.grid(row = 1, column = 0)
# Entry Box
entry_one = tk.Entry(root)
entry_two = tk.Entry(root)
entry_one.grid(row = 0, column =1)
entry_two.grid(row = 1, column =1)

# Buttons
button_add = tk.Button(root, text = "+", command = add)
button_sub = tk.Button(root, text = "-", command = sub)
button_mul = tk.Button(root, text = "*", command = mul)

button_add.grid(row = 3, column =0)


button_sub.grid(row = 3, column =1)
button_mul.grid(row = 3, column =2)

# Answer Label

label_answer = tk.Label(root)
label_answer.grid(row = 4, column = 0)

root.mainloop()

Output:
Experiment-17
Network Programming

Aim: To establish a TCP connection between Client and Server


python programs

Source Code:

TCP Client:
import socket

host_ip, server_port = "127.0.0.1", 9999


data = " Hello how are you?\n"

# Initialize a TCP client socket using SOCK_STREAM


tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
# Establish connection to TCP server and exchange data
tcp_client.connect((host_ip, server_port))
tcp_client.sendall(data.encode())

# Read data from the TCP server and close the connection
received = tcp_client.recv(1024)
finally:
tcp_client.close()

print ("Bytes Sent: {}".format(data))


print ("Bytes Received: {}".format(received.decode()))

TCP Server:
import socketserver

class Handler_TCPServer(socketserver.BaseRequestHandler):
def handle(self):
# self.request - TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} sent:".format(self.client_address[0]))
print(self.data)
# just send back ACK for data arrival confirmation
self.request.sendall("ACK from TCP Server".encode())

if __name__ == "__main__":
HOST, PORT = "localhost", 9999

# Init the TCP server object, bind it to the localhost on 9999 port
tcp_server = socketserver.TCPServer((HOST, PORT),
Handler_TCPServer)

# Activate the TCP server.


# To abort the TCP server, press Ctrl-C.
tcp_server.serve_forever()

Output:
Experiment-18
Network Programming

Aim: To establish a UDP connection between Client and Server


python programs

Source Code:

UDP Client:
import socket

msgFromClient = "Hello UDP Server"


bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("127.0.0.1", 20001)
bufferSize = 1024

# Create a UDP socket at client side


UDPClientSocket = socket.socket(family=socket.AF_INET,
type=socket.SOCK_DGRAM)

# Send to server using created UDP socket


UDPClientSocket.sendto(bytesToSend, serverAddressPort)
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)

UDP Server:
import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = str.encode(msgFromServer)

# Create a datagram socket


UDPServerSocket = socket.socket(family=socket.AF_INET,
type=socket.SOCK_DGRAM)

# Bind to address and ip


UDPServerSocket.bind((localIP, localPort))

print("UDP server up and listening")

# Listen for incoming datagrams


while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]

clientMsg = "Message from Client:{}".format(message)


clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)

# Sending a reply to client


UDPServerSocket.sendto(bytesToSend, address)

Output:
Experiment-19
Automata Programming

Aim: To Implement Deterministic Finite Automata using python

Source Code:

from automata.fa.dfa import DFA

dfa = DFA(
states={'q0', 'q1', 'q2'},
input_symbols={'0', '1'},
transitions={
'q0': {'0': 'q0', '1': 'q1'},
'q1': {'0': 'q0', '1': 'q2'},
'q2': {'0': 'q2', '1': 'q1'}
},
initial_state='q0',
final_states={'q1'}
)

for i in range(2):
my_input_str = input("Enter a string with 1's and 0's")
if dfa.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')

Output:
Experiment-20
Automata Programming

Aim: To Implement Non-Deterministic Finite Automata using python

Source Code:

from automata.fa.nfa import NFA


nfa = NFA(
states={'q0', 'q1', 'q2'},
input_symbols={'a', 'b'},
transitions={
'q0': {'a': {'q1'}},
'q1': {'a': {'q1'}, '': {'q2'}},
'q2': {'b': {'q0'}}
},
initial_state='q0',
final_states={'q1'}
)

for i in range(2):
my_input_str = input("Enter a string with a's and b's ")
if nfa.accepts_input(my_input_str):
print('accepted')
else:
print('rejected')
Output:

You might also like