0% found this document useful (0 votes)
299 views36 pages

Solution Python Programming Practical List

The document provides answers to 12 questions on Python programming. It includes Python programs for basic arithmetic and string operations, calculating GCD and LCM, binary and decimal conversions, designing a calculator using control statements, demonstrating call by value and reference, creating classes and objects, explaining inheritance types, using getter and setter methods, importing packages and performing operations, importing datasets using NumPy and Pandas to perform statistical operations, building a GUI application, connecting a GUI to a database using SQL and Pandas, and a program for client-server programming.

Uploaded by

Rehan Pathan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
299 views36 pages

Solution Python Programming Practical List

The document provides answers to 12 questions on Python programming. It includes Python programs for basic arithmetic and string operations, calculating GCD and LCM, binary and decimal conversions, designing a calculator using control statements, demonstrating call by value and reference, creating classes and objects, explaining inheritance types, using getter and setter methods, importing packages and performing operations, importing datasets using NumPy and Pandas to perform statistical operations, building a GUI application, connecting a GUI to a database using SQL and Pandas, and a program for client-server programming.

Uploaded by

Rehan Pathan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 36

Python Programming Practical List

Q1.Write a python program for

i) Perform basic arithmetic operation on given number. 


Ans :-
N1 = int(input("Enter the first number :- \t "));
N2 = int(input("Enter the second number :-\t "));
print("Addition of two Numbers is :-\t ", (N1 + N2));
print("Subtraction of two Numbers is:-\t ", (N1 - N2));
print("Multiplication of two Numbers is :-\t ", (N1 * N2));
print("Division of two Numbers is :- \t", (N1 / N2));
# Sample Output:-
ii) Perform basic string operation on given string.
Ans:-
# First String operation :-
str1 = "Hello";
str2 = 'Hello';
str3 = '''Hello''';
print(str1, str2, str3);

# Second String operation :-


str4 = "Walchand";
str5 = "College";
string_combined = str4 + " " + str5;
print(string_combined);

#Third string operation :-


str6 = "Hello ";
print(str6 * 2);
print(str6 * 4);

#Fourth string operation:-


string = "Hello World! I am from 'INDIA'";
print(string);

# Sample Output:-
iii) Find GCD and LCM of given number.
Ans:-
print("Enter two Numbers:-\t ");
N1 = int(input());
N2 = int(input());
if(N1 > N2):
lcm = N1;
else:
lcm = N2;
while True:
if(lcm % N1 == 0 and lcm % N2 == 0):
break;
else:
lcm = lcm +1;
print("LCM = (" + str(N1) + "," + str(N2) + ") = ", lcm);
print("\nEnter two Numbers:-\t");
n1 = int(input());
n2 = int(input());
if(n1 > n2):
gcd = n1;
else:
gcd = n2;
while True:
if(n1 % gcd == 0 and n2 % gcd == 0):
break;
else:
gcd = gcd - 1;

print("GCD = (" + str(n1) + "," + str(n2) + ") = ",gcd);

# Sample Output:-
iv).Convert binary to decimal and vice versa.
Ans:-
#conversion of binary to decimal number
b_num = list(input("Entet a binary number:-\t "))
value = 0
for i in range(len(b_num)):
digit = b_num.pop()
if digit == '1':
value = value + pow(2, i)
print("The decimal value of the number is :-\t", value)

#conversion of decimal to binary number


defdecimalToBinary(num):
ifnum> 1:
decimalToBinary(num // 2)
print(num % 2, end='')
number = int(input("\nEnter any decimal number:-\t "))
print("The Binary value of the number is :-\t",)
decimalToBinary(number)
# Sample Output :-

Q 2. Write a python program for design a


calculator using various control statements.
Ans:-
# Program make a simple calculator

# This function adds two numbers


def add(x, y):
return x + y
# This function subtracts two numbers
def subtract(x, y):
return x - y

# This function multiplies two numbers


def multiply(x, y):
return x * y

# This function divides two numbers


def divide(x, y):
return x / y

print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
# take input from the user
choice = input("Enter your choice: ")
# check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))

elif choice == '2':


print(num1, "-", num2, "=", subtract(num1, num2))

elif choice == '3':


print(num1, "*", num2, "=", multiply(num1, num2))

elif choice == '4':


print(num1, "/", num2, "=", divide(num1, num2))

# check if user wants another calculation


# break the while loop if answer is no
next_calculation = input("Let's do next calculation?
(yes/no): ")
ifnext_calculation == "no":
break
else:
print("Invalid Input")

#Output :-
Q3. Write a python program for Call by value and
call by reference.
Ans:-
# call by value

string = "Python"
def test(string):
string = "PythonPractical"
print("Inside function : ", string)
test(string)
print("Outside function : ", string)

# call by reference

def call(list):
list.append(100)
print("Iside function: ", list)
mylist = [10, 50, 20, 90, 70]
call(mylist)
print("Outside function : ", mylist)

#Output:-
Q4. Write a python program for creating a class,
object and constructor. Compare the
performance with cpp.
Ans:-
class addition:
def add(self, a, b):
add = a + b
return add
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
obj = addition()
add = obj.add(a, b)
print("Addition is : ", add)

#Output:-
Q5. Write a python program to elaborate inheritance
and its types. . Compare the performance with cpp.
Ans:-
#parent class
class Above:
i=5
def fun1(self):
print("In the parent Class...")

#subclass
class Below(Above):
i=10
def fun2(self):
print("In the Child Class...")

temp1=Below()
temp2=Above()
temp1.fun1()
temp1.fun2()
temp2.fun1()
print(temp1.i)
print(temp2.i)
#temp2.fun2()
#Output:-

Q6. Write a python program for getter method and


setter method.
Ans:-
class Geek:
def __init__(self, age = 0):
self._age = age
# getter method
def get_age(self):
returnself._age

# setter method
defset_age(self, x):
self._age = x

raj = Geek()

# setting the age using setter


raj.set_age(21)

# retrieving age using getter


print(raj.get_age())

print(raj._age)

#Output:-
Q7. Write a python program to import various
packages and perform various operations.
Ans:-
def up():
print("UP:lucknow")
defmp():
print("MP:bhopal")

import india.states
def main():
india.states.up()
india.states.mp()
main()

#Output:-
Q8. Write a python program to perform searching
and sorting operation by importing excel
sheet use switch case for various algorithms.
Ans:-
import pandas as pd
import numpy as np
from google.colab import files
uploaded = files.upload()
data = pd.read_excel("Salary.xlsx")
mode_data=data['Salary'].mode()
print(mode_data)
print(data.head())
df = pd.DataFrame(data)
print(df)
mean1 = df['SAL'].mean()
print ('Mean salary: ' + str(mean1))
sum1 = df['SAL'].sum()
print ('Sum of salaries: ' + str(sum1))
max1 = df['SAL'].max()
min1 = df['SAL'].min()
count1 = df['SAL'].count()
median1 = df['SAL'].median()
std1 = df['SAL'].std()
var1 = df['SAL']
print ('Max salary: ' + str(max1))
print ('Min salary: ' + str(min1))
print ('Count of salaries: ' + str(count1))
print ('Median salary: ' + str(median1))
print ('Std of salaries: ' + str(std1))
print ('Var of salaries: ' + str(var1))
print(data.iloc[0:2,:],"\n")
print(data.iloc[2])

#Output:-
Q9. Write a python program to import dataset using
Numpy and Panda libraries and perform
various statistical and logical operations on the
dataset.
Ans:-
importnumpy as np
import pandas as pd
a=np.array([1, 2, 3]) # Create a rank 1 array
print(a)
print(type(a))
print(a.ndim)
print(a.shape)
print(len(a))
arr=np.array([1,3,5,7,9])
s2=pd.Series(arr)
print(s2)
print(type(s2))

#Output:-
Q10. Write a python program to build GUI to create
an application.
Ans:-
# Import Module
fromtkinter import *
# create root window
root = Tk()
# root window title and dimension
root.title("Welcome to python")
# Set geometry(widthxheight)
root.geometry('350x200')
# adding a label to the root window
lbl = Label(root, text = "Are you a student?")
lbl.grid()
# function to display text when
# button is clicked
def clicked():
lbl.configure(text = "I just got clicked")
# button widget with red color text
# inside
btn = Button(root, text = "Click me" ,
fg = "red", command=clicked)
# set Button grid
btn.grid(column=1, row=0)
# Execute Tkinter
root.mainloop()
#Output:-
Q11. Write a python program to build connectivity
between GUI and database. Create
database using SQL and Panda library.
Ans:-
#connecting database
importmysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="Ujwala@2001"
)
print(db_connection)

#creating database in sql using python


importmysql.connector
db_connection = mysql.connector.connect(
host= "localhost",
user= "root",
passwd= "Ujwala@2001"
)
# creating database_cursor to perform SQL operation
db_cursor = db_connection.cursor()
# executing cursor with execute method and pass SQL
query
db_cursor.execute("CREATE DATABASE my_first_db")
# get list of all databases
db_cursor.execute("SHOW DATABASES")
#print all databases
fordb in db_cursor:
print(db)
Q12. Write a python program for client server
programming.
Ans:-
import socket # for socket
import sys

try:
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
print ("Socket successfully created")
exceptsocket.error as err:
print ("socket creation failed with error %s" %(err))

# default port for socket


port = 80

try:
host_ip = socket.gethostbyname('www.google.com')
exceptsocket.gaierror:

# this means could not resolve the host


print ("there was an error resolving the host")
sys.exit()

# connecting to the server


s.connect((host_ip, port))

print ("the socket has successfully connected to google")

#Output:-

You might also like