Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

PythonLab_R-2019

The document is a lab manual for Python programming at Datta Meghe College of Engineering, detailing various experiments for students in the Information Technology department. It includes aims, theories, and sample code for exercises such as creating a calculator, checking Armstrong numbers, writing data to CSV files, and implementing inheritance. Each experiment is mapped to specific course outcomes (COs) to facilitate learning objectives.

Uploaded by

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

PythonLab_R-2019

The document is a lab manual for Python programming at Datta Meghe College of Engineering, detailing various experiments for students in the Information Technology department. It includes aims, theories, and sample code for exercises such as creating a calculator, checking Armstrong numbers, writing data to CSV files, and implementing inheritance. Each experiment is mapped to specific course outcomes (COs) to facilitate learning objectives.

Uploaded by

vaitypriyanshu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING

Department of Information Technology


LAB MANUAL

______________________________________________________________________________

Sub: - Python Lab Sem: IV Div: A and B

Sr Name of Experiment Mapping with COs


No.

1. Mini calculator CO1

2 Creations of menu in Python CO1

3. To check if the number is CO3


Armstrong number or not

4 Writing data into CSV file CO6

5. Write a program to learn Multilevel CO2


Inheritance

6. To learn single inheritance CO1

7. Write a program to create a class CO3


using Python

8. To create menu using Tkinter CO4

9. To implement a Python program for CO5


creation of Application using tkinter

10. To run module in python. CO6

11. To show Data visualization using CO6


Bar chart
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

Subject In charge

EXPERIMENT 01

Aim: Creation of Calculator

Theory: Operators in general are used to perform operations on values and


variables in Python.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x


The arithmetic operators are addition (+), subtraction (-), multiplication (*),
division (/), exponent (**), floor division (//) and modulus (%). The first four are
fairly simple; they are addition, subtraction, multiplication and division.

# This function adds two numbers

def add(x, y):

return x + y
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

# 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")
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

while True:

# Take input from the user

choice = input("Enter choice(1/2/3/4): ")

# 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))


DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

break

else:

print("Invalid Input")

Output
Select operation.

1.Add

2.Subtract

3.Multiply

4.Divide

Enter choice(1/2/3/4): 3

Enter first number: 15

Enter second number: 14

15.0 * 14.0 = 210.0

:
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 02:
Aim:

EXPERIMENT 03:
AIM:- To check if the number is Armstrong number or not.

THEORY:-

● What is Armstrong Number?

The armstrong number, also known as the narcissist number, is of special interest
to beginners. It kindles the curiosity of programmers just setting out with learning
a new programming language. In number theory, an armstrong number in a given
number base b is a number that is the sum of its own digits each raised to the
power of the number of digits.

To put it simply, if I have a 3-digit number then each of the digits is raised to the
power of three and added to obtain a number. If the number obtained equals the
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

original number then, we call that armstrong number. The unique property related
to the armstrong numbers is that it can belong to any base in the number system.
For example, in decimal number system, 153 is an armstrong number.

1^3+5^3+3^3=153

● Armstrong Number Logic

Let us understand the logic of obtaining an armstrong number.

Consider the 6 -digit number 548834 .Calculate the sum obtained by adding the
following terms.

5^6 + 4^6 + 8^6 + 8^6 + 3^6 + 4^6 = 548834

We obtain the same number when we add the individual terms. Therefore, it
satisfies the property.

● Armstrong Number Algorithm

We need two parameters to implement armstrong numbers. One being the number
of digits in the number, and second the sum of the digits raised to the power of
number of digits. Let us look at the algorithm to gain a better understanding:

Algorithm:

1. The number of digits in num is found out

2. The individual digits are obtained by performing num mod 10, where mod is the
remainder operation.
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

3. The digit is raised to the power of the number of digits and stored

4. Then the number is divided by 10 to obtain the second digit.

5. Steps 2,3 and 4 are repeated until the value of num is greater than 0

6. Once num is less than 0, end the while loop

7. Check if the sum obtained is same as the original number

8. If yes, then the number is an armstrong number

PROGRAM:-

# Python program to check if the number is an Armstrong number or not

# take input from the user

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

# initialize sum

sum = 0

# find the sum of the cube of each digit

temp = num

while temp > 0:

digit = temp % 10

sum += digit ** 3

temp //= 10

# display the result


DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

if num == sum:

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

OUTPUT:-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 04:
AIM:- Writing data into CSV file

THEORY:-

CSV (Comma Separated Values) is a simple file format used to store tabular data,
such as a spreadsheet or database. CSV file stores tabular data (numbers and text)
in plain text. Each line of the file is a data record. Each record consists of one or
more fields, separated by commas. The use of the comma as a field separator is the
source of the name for this file format.

Python provides an in-built module called csv to work with CSV files. There are
various classes provided by this module for writing to CSV:

● Using csv.writer class


● Using csv.DictWriter class
Using csv.writer class

csv.writer class is used to insert data to the CSV file. This class returns a writer
object which is responsible for converting the user’s data into a delimited string. A
csvfile object should be opened with newline='' otherwise newline characters
inside the quoted fields will not be interpreted correctly.
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

Syntax: csv.writer(csvfile, dialect=’excel’, **fmtparams)

Parameters:

csvfile: A file object with write() method.

dialect (optional): Name of the dialect to be used.

fmtparams (optional): Formatting parameters that will overwrite those specified in


the dialect. csv.writer class provides two methods for writing to CSV. They are
writerow() and writerows().

writerow(): This method writes a single row at a time. Field row can be written
using this method.

Syntax:

writerow(fields)

writerows(): This method is used to write multiple rows at a time. This can be used
to write rows list.

Syntax:

Writing CSV files in Python

writerows(rows)

PROGRAM:-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

import csv

# field names

fields = ['Name', 'Branch', 'Year', 'CGPA']

# data rows of csv file

rows = [ ['Nikhil', 'COE', '2', '9.0'],

['Sanchit', 'COE', '2', '9.1'],

['Aditya', 'IT', '2', '9.3'],

['Sagar', 'SE', '1', '9.5'],

['Prateek', 'MCE', '3', '7.8'],

['Sahil', 'EP', '2', '9.1']]

# name of csv file

filename = "university_records.csv"

# writing to csv file

with open(filename, 'w') as csvfile:

# creating a csv writer object

csvwriter = csv.writer(csvfile)
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

# writing the fields

csvwriter.writerow(fields)

# writing the data rows

csvwriter.writerows(rows)

OUTPUT:-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 05
AIM:

Write a program to learn Multilevel Inheritance.

THEORY:

In multilevel inheritance, features of the base class and the derived class is
inherited into the new derived class.

In the multiple inheritance scenario, any specified attribute is searched first in the
current class. If not found, the search continues into parent classes in depth-first,
left-right fashion without searching the same class twice.

CODE:
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

class employee1:

def
__init__(self, name, age, salary):

self.name
= name

self.age =
age

self.salary = salary

def
printname(self):

print(self.name, self.age, self.salary, self.id)

class childemployee(employee1):

def
__init__(self,name,age,salary,id):

employee1.__init__(self, name, age,salary)


DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

self.id =
id

def
welcome(self):

print("Welcome", self.name, "to the id of", self.id)

x = childemployee('harshit',22,1000,101)

x.printname()

x.welcome()

OUTPUT:
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 06:
AIM:- To learn single inheritance

THEORY:-

In python single inheritance, a derived class is derived only from a single parent
class and allows the class to derive behaviour and properties from a single base
class. This enables code reusability of a parent class, and adding new features to a
class makes code more readable, elegant and less redundant. And thus, single
inheritance is much more safer than multiple inheritances if it’s done in the right
way and enables derived class to call parent class method and also to override
parent classe’s existing methods.

Syntax:

class Parent_class_Name:

#Parent_class code block

class Child_class_Name(Parent_class_name):

#Child_class code block


DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

The above syntax consists of two classes declared. One is the base class, or by
other means, the parent class and the other one is for the child class, which acts as
the derived class.

How Single Inheritance Works in Python?

Each of these classes has its own code block. So as per single inheritance, every
element present in the parent class’s code block can be wisely used in the child
class. To attain a single inheritance syntax ally, the name of the parent class is
mentioned within the child class’s arguments.

PROGRAM:-

class Person:

def __init__(self, fname, lname):

self.firstname = fname
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

self.lastname = lname

def printname(self):

print(self.firstname, self.lastname)

p=Person("ana","xyz")

p.printname()

class Student(Person):

pass

x = Student("pqr", "aaa")

x.printname()
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

OUTPUT:-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 07:
AIM:

Write a program to create a class using Python.


.

THEORY:

A class is a user-defined blueprint or prototype from which objects are created.


Classes provide a means of bundling data and functionality together.

Creating a new class creates a new type of object, allowing new instances of that
type to be made.

Each class instance can have attributes attached to it for maintaining its state. Class
instances can also have methods (defined by their class) for modifying their state.

● Classes are created by keyword class.


● Attributes are the variables that belong to a class.
● Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

Class Definition Syntax:

class ClassName:
# Statement-1
.
.
.
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

# Statement-N

CODE:

class Person:

def
__init__(self, name, age):

self.name = name

self.age
= age

def
myfunc(self):

print("Hello my name is " + self.name)

p1 = Person("John", 36)

p1.myfunc()

OUTPUT:
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 08

AIM:- To create menu using Tkinter

THEORY: -

Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of


the most commonly used package for GUI applications which comes with the
Python itself.

Menus are the important part of any GUI. A common use of menus is to provide
convenient access to various operations such as saving or opening a file, quitting a
program, or manipulating data. Top level menus are displayed just under the title
bar of the root or any other top level windows.

PROGRAM :-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

from tkinter import Toplevel, Button, Tk, Menu

top = Tk()

menubar = Menu(top)

file = Menu(menubar, tearoff=0)

file.add_command(label="New")

file.add_command(label="Open")

file.add_command(label="Save")

file.add_command(label="Save as...")

file.add_command(label="Close")

file.add_separator()

file.add_command(label="Exit", command=top.quit)

menubar.add_cascade(label="File", menu=file)

edit = Menu(menubar, tearoff=0)

edit.add_command(label="Undo")

edit.add_separator()

edit.add_command(label="Cut")
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

edit.add_command(label="Copy")

edit.add_command(label="Paste")

edit.add_command(label="Delete")

edit.add_command(label="Select All")

menubar.add_cascade(label="Edit", menu=edit)

help = Menu(menubar, tearoff=0)

help.add_command(label="About")

menubar.add_cascade(label="Help", menu=help)

top.config(menu=menubar)

top.mainloop()

OUTPUT :-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

Expt 09:
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

AIM: To implement a Python program for creation of Application using tkinter


THEORY:
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a
powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the follow
1. Import the Tkinter module.
2. Create the GUI application main window.
3. Add one or more of the above-mentioned widgets to the GUI application.
4. Enter the main event loop to take action against each event triggered by the
user

Tkinter provides various controls, such as buttons, labels and text boxes used in a
GUI application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter.

PROGRAM:

import tkinter
# Let's create the Tkinter window.
window = tkinter.Tk()
window.title("GUI")
# You will first create a division with the help of Frame class and align them on
TOP and BOTTOM with pack() method.
top_frame = tkinter.Frame(window).pack()
bottom_frame = tkinter.Frame(window).pack(side = "bottom")
# Once the frames are created then you are all set to add widgets in both the
frames.
btn1= tkinter.Button(top_frame, text = "Button1", fg = "red").pack() #'fg or
foreground' is for coloring the contents (buttons)
btn2 = tkinter.Button(top_frame, text = "Button2", fg = "green").pack()
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

btn3 = tkinter.Button(bottom_frame, text = "Button3", fg = "purple").pack(side =


"left")
#'side' is used to left or right align the widgets
btn4 = tkinter.Button(bottom_frame, text = "Button4", fg = "orange").pack(side =
"left")
window.mainloop()

OUTPUT:

EXPERIMENT 10:
AIM :- To run module in python.

THEORY :-

What is a Module?
Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.

Create a Module
To create a module just save the code you want in a file with the file extension .py:

Variables in Module
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

The module can contain functions, as already described, but also variables of all
types (arrays, dictionaries, objects etc):

Example
Save this code in the file mymodule.py

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import the module named mymodule, and access the person1 dictionary:

import mymodule

a = mymodule.person1["age"]
print(a)

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as keyword:

Example
Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
Built-in Modules
There are several built-in modules in Python, which you can import whenever you
like.
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

Example
Import and use the platform module:

import platform

x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a
module. The dir() function:

Example
List all the defined names belonging to the platform module:

import platform

x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create
yourself.

Import From Module


You can choose to import only parts from a module, by using the from keyword.

Example
The module named mymodule has one function and one dictionary:

def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

Example
Import only the person1 dictionary from the module:

from mymodule import person1

print (person1["age"])

PROGRAM :-

def add(a, b):


"""This program adds two
numbers and return the result"""

result = a + b
return result

#main.py
import add1, file
name = input("Enter the values?")
file.displayMsg(name)

print(add1.add(4,5.5))

OUTPUT :-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

EXPERIMENT 11:
AIM :- To show Data visualization using Bar chart

THEORY :-

A bar plot or bar chart is a graph that represents the category of data with
rectangular bars with lengths and heights that is proportional to the values which
they represent. The bar plots can be plotted horizontally or vertically. A bar chart
describes the comparisons between the discrete categories. One of the axis of the
plot represents the specific categories being compared, while the other axis
represents the measured values corresponding to those categories.

Creating a bar plot


The matplotlib API in Python provides the bar() function which can be used in
MATLAB style use or as an object-oriented API. The syntax of the bar() function
to be used with the axes is as follows:-

plt.bar(x, height, width, bottom, align)


DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

The function creates a bar plot bounded with a rectangle depending on the given
parameters.

PROGRAM :-

import matplotlib.pyplot as plt

import numpy as np

y = np.array([35, 25, 25, 15])

mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

plt.pie(y, labels = mylabels, startangle = 90)

plt.show()

OUTPUT :-
DATTA ME DATTA MEGHE COLLEGE OF ENGINEERING
Department of Information Technology
LAB MANUAL

______________________________________________________________________________

You might also like