0% found this document useful (0 votes)
10 views12 pages

Python Programming Practical Exercises

The document contains a series of practical Python programming exercises authored by Khushali M. Vadodariya, covering various topics such as basic input/output, control structures, functions, data validation, and graphical user interface (GUI) creation. It includes code snippets for tasks like checking for multiples, calculating averages, creating plots with matplotlib, and building registration forms with Tkinter. Additionally, it demonstrates file transfer between client and server using sockets and database interaction with MySQL.

Uploaded by

jadavm940
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views12 pages

Python Programming Practical Exercises

The document contains a series of practical Python programming exercises authored by Khushali M. Vadodariya, covering various topics such as basic input/output, control structures, functions, data validation, and graphical user interface (GUI) creation. It includes code snippets for tasks like checking for multiples, calculating averages, creating plots with matplotlib, and building registration forms with Tkinter. Additionally, it demonstrates file transfer between client and server using sockets and database interaction with MySQL.

Uploaded by

jadavm940
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python

PRACTICAL

Khushali M. Vadodariya
LECTURER OM VVIM COLLEGE
PYTHON

Practical: 1
1. Write a program to display “Hello” if a number entered by user is a
multiple of five, otherwise print “Bye”.
num = int(input("Enter a number:"))
if num%5==0:
print("Hello")
else:
print("Bye")

2. Write a program to display the last digit of a number.


num = int(input("Enter a number:"))
print("Last digit of number is:",num%10)

3. Write a program to display maximum number out of 3 number.


def maximum(a, b, c):
list = [a, b, c]
return max(list)
# Driven code
x = int(input("Enter First number"))
y = int(input("Enter Second number"))
z = int(input("Enter Third number"))
print("Maximum Number is ::>",maximum(x, y, z))

4. Prints all the numbers from 0 to 6 except 3 and 6.


for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
print("\n")

5. Write a Python program that accepts a string and calculates the number
of digits and letters.

s = input("Input a string")
d=l=0
for c in s:
if [Link]():
d=d+1
elif [Link]():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)

By | Khushali Vadodariya 1|Page


PYTHON

6. Write a Python program to check the validity of passwords input by users.

Validation:
 At least 1 letter between [a-z] and 1 letter between [A-Z].
 At least 1 number between [0-9].
 At least 1 character from [$#@].
 Minimum length 6 characters.
 Maximum length 16 characters.

import re
p= input("Input your password")
x = True
while x:
if (len(p)<6 or len(p)>16):
break
elif not [Link]("[a-z]",p):
break
elif not [Link]("[0-9]",p):
break
elif not [Link]("[A-Z]",p):
break
elif not [Link]("[$#@]",p):
break
elif [Link]("\s",p):
break
else:
print("Valid Password")
x=False
break

if x:
print("Not a Valid Password")

7. The sum_of_list function calculates the sum of the elements in a list using
recursion.

def sum_of_list(arr):
if not arr:
return 0
else:
return arr[0] + sum_of_list(arr[1:])

# Example usage of the sum_of_list function


my_list = [1, 2, 3, 4, 5]

By | Khushali Vadodariya 2|Page


PYTHON

result = sum_of_list(my_list)
print(f"The sum of the elements in the list {my_list} is {result}")

By | Khushali Vadodariya 3|Page


PYTHON

Practical: 2
1. Write a python program for addition of 2 numbers in which variable is not
exist than throws exception.
try:
x=input(int("Enter value:"))
print(x+y)
except Exception:
print("Variable not defined")

2. Write a python program for calculate Average of 2 List and in which 2 list is
not exist than raise AssertionError by using assert method.

def avg(marks):
assert len(marks)!=0
return sum(marks)/len(marks)
list1=[55,88,78,90]
print("Average of List1:",avg(list1))
list2=[]
print("Average of List2:",avg(list2))

By | Khushali Vadodariya 4|Page


PYTHON

Practical: 3
1. Write a python program for create 2 list and plot pie chart by using
matplotlib.

# Import libraries

from matplotlib import pyplot as plt

import numpy as np

# Creating dataset

cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR', 'MERCEDES']

data = [23, 17, 35, 29, 12, 41]

# Creating plot

fig = [Link](figsize =(10, 7))

[Link](data, labels = cars)

# show plot
[Link]()

2. Write a python program for subject ratio in % and show it in Bar chart by
using matplotlib.

import [Link] as pyplot

# Manual data setup


labels = ('Python', 'Java', 'JavaScript', 'C#', 'PHP', 'C,C++', 'R')
index = (1, 2, 3, 4, 5, 6, 7) # provides locations on x axis
sizes = [29.9, 19.1, 8.2, 7.3, 6.2, 5.9, 3.7]

# bar chart setup


[Link](index, sizes, color="#6c3376", tick_label=labels)

# layout configuration
[Link]('Usage in %')
[Link]('Programming Languages')

# Save the chart file


#[Link]('[Link]', dpi=300)

By | Khushali Vadodariya 5|Page


PYTHON

# Print the chart


[Link]()

By | Khushali Vadodariya 6|Page


PYTHON

Practical: 4
1. Write a python program for create Registration Form in python.

import tkinter as tk

window = [Link]()
[Link]("340x360")

[Link](text='Name').place(x=30, y=30)
name = [Link](text='name')
[Link](x=100, y=30)

[Link](text='Age').place(x=30, y=70)
age = [Link](text='age')
[Link](x=100, y=70)

[Link](text='City').place(x=30, y=110)
city = [Link](text='city')
[Link](x=100, y=110)

[Link](text='Email').place(x=30, y=150)
email = [Link](text='email')
[Link](x=100, y=150)

[Link](text='Password').place(x=30, y=190)
password = [Link](text='password', show='*')
[Link](x=100, y=190)

[Link](text='Gender').place(x=30, y=230)
rbtn1 = [Link](text='Male', variable="radio", value="male")
[Link](x=100, y=230)
rbtn2 = [Link](text='Female', variable="radio", value="female")
[Link](x=150, y=230)

[Link](text='Hobby').place(x=30, y=270)
chk1 = [Link](text='Read')
[Link](x=100, y=270)
chk2 = [Link](text='Write')
[Link](x=150, y=270)
chk3 = [Link](text='Paint')
[Link](x=200, y=270)
chk4 = [Link](text='Other')
[Link](x=250, y=270)

[Link](text='Register').place(x=100, y=310)

[Link]()

By | Khushali Vadodariya 7|Page


PYTHON

2. Write a python program for send image file between client and server.

 file_client.py

import socket

def send_file(ip, port, filename):


c = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link]((ip, port))

with open(filename, 'rb') as file:


data = [Link](1024)
while data:
[Link](data)
data = [Link](1024)

print("File sent successfully")

[Link]()

if __name__ == "__main__":
ip = "[Link]"
port = 12345
filename = "[Link]"
send_file(ip, port, filename)

 file_server.py
import socket

def receive_file(port, filename):


s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('[Link]', port))
[Link](1)

print("Server listening on port", port)

conn, addr = [Link]()


print(f"Connection from {addr}")

with open(filename, 'wb') as file:


data = [Link](1024)
while data:
[Link](data)
data = [Link](1024)

By | Khushali Vadodariya 8|Page


PYTHON

print("File received and saved successfully")

if __name__ == "__main__":
port = 12345
filename = "[Link]"
receive_file(port, filename)

By | Khushali Vadodariya 9|Page


PYTHON

Practical: 5

1. Write a python program for create Registration Form in python using


Mysql Database.

import tkinter as tk
from tkinter import messagebox as mb
import [Link] as db

myDb = [Link](
host="localhost",
user="root",
password="",
database="py_data"
)

myCursor = [Link]()

def result():
username = [Link]()
password = [Link]()

# insert into table


try:
[Link](f"INSERT INTO user_list (username, password) VALUES ('{username}',
'{password}')")
[Link]('Register', "Registered Successfully")
[Link](0, 'end')
[Link](0, 'end')
[Link]()
except Exception as e:
print(e)

window = [Link]()
[Link]("500x300")

ulabel = [Link](text='Username')
[Link](x=30, y=30)

plabel = [Link](text='Password')
[Link](x=30, y=70)

uentry = [Link](text='Username')
[Link](x=100, y=30)

pentry = [Link](text='Password', show='*')


[Link](x=100, y=70)

By | Khushali Vadodariya 10 | P a g e
PYTHON

btn = [Link](text='Login', command=result)


[Link](x=100, y=110)

[Link]()

By | Khushali Vadodariya 11 | P a g e

Common questions

Powered by AI

The Python program uses regular expressions to validate the password. The program checks for five conditions: the length of the password must be between 6 and 16 characters, it must contain at least one lowercase letter, one uppercase letter, one digit, and one special character from the set [$#@]. It also ensures there are no spaces in the password. If all these checks pass, the password is considered valid .

Exception handling in Python, through try-except blocks, is significant in managing runtime errors that may occur due to undefined variables. It allows the program to continue executing by catching exceptions and executing alternative code paths (e.g., printing error messages). This mechanism ensures program stability since failure to define variables doesn’t lead to crashes but is handled gracefully, providing feedback to the user or programmer about the nature of the error encountered .

The assert statement in the program checks that the list provided has a non-zero length before attempting to calculate the average. It serves as a preventative error-checking mechanism, guaranteeing that division by zero is avoided in the average calculation. If the list is empty, assert triggers an AssertionError, indicating the precondition for computing the average was not met, thus maintaining the integrity of the computation process .

The program demonstrates iterating over numbers from 0 to 6 using a for loop. It uses an if condition within the loop to check if the current number is 3 or 6. If so, the continue statement is executed to skip the current iteration, thus effectively filtering out and excluding these numbers from being printed. This results in printing all numbers in the range except 3 and 6 .

To create a bar chart displaying programming language usage percentages, one needs to start by defining the data set with labels representing each programming language and their corresponding usage percentages. In matplotlib, the pyplot.bar() function is used to create the bars. Labels are specified for each bar, and the size list determines the bar heights. Additional chart configurations like labeling the x-axis and y-axis ('Programming Languages' and 'Usage in %') and scene configuration are undertaken before using pyplot.show() to display the bar chart .

The process of sending a file from a client to a server using sockets involves multiple steps. The client first creates a socket using IPv4 and TCP protocols and connects to the server's IP and port. It opens the file to be sent in binary read mode and sends its data in chunks (typically 1024 bytes) across the connection. On the server side, a socket is created and bound to the designated port, then it listens for incoming connections. Upon accepting a connection, the server opens a file for writing in binary mode and writes the received data chunks into this file until all data is received .

Without assertions, the program may attempt to calculate the average of an empty list, leading to a division by zero error, which would cause the program to crash. This unexpected termination highlights the importance of defending preconditions. Assertions serve as an early indication that the list is adequate for average calculation, making the process robust against invalid data configurations. Without such checks, the program lacks proactive error prevention, increasing the risk of unhandled exceptions .

Using tkinter, a GUI registration form can be created by first initializing a main window with tk.Tk() and setting its geometry. The form fields such as 'Name', 'Age', 'City', etc., are created using tk.Label for labeling and tk.Entry for input fields. Additionally, buttons and checkboxes are added for additional form features. tk.Button is used for the registration button, while tk.Checkbutton and tk.Radiobutton allow for selecting options. The main event loop is started with tk.mainloop() to make the GUI window interactive .

The Python technique used is exception handling, utilizing try-except blocks. In the program for calculating the sum of two numbers, exception handling is employed to catch exceptions when variables do not exist. If the attempt to perform operations on undefined variables occurs, the except block is executed, printing a message indicating that the variable is not defined, thereby preventing the program from crashing .

The recursive function sum_of_list calculates the sum of list elements by first checking if the list is empty. If it is empty, the function returns 0, which is the base case. If not, it takes the first element of the list, adds it to the result of a recursive call to sum_of_list with the rest of the list (excluding the first element), effectively breaking down the list until it reaches an empty sublist and can sum the elements together .

You might also like