PROGRAMMING WITH PYTHON
SUBMITTED IN PARTIAL FULFILLMENT FOR AWARD OF
DEGREE
IN
BACHELOR OF TECHNOLOGY
(2019-2023)
BY
SATVIK CHANDEL
1906031044
UNDER THE GUIDANCE OF
MRS. SUSHEELA PATHANIA
School of Computer Science and Engineering
Govt. P.G. College Dharamshala
HIMACHAL PRADESH TECHNICAL UNIVERSITY,
HAMIRPUR-H.P.
CERTIFICATE OF ORIGINALITY
I hereby declare that the Project entitled “Programming with Python” submitted to the
School of Computer Science and Engineering, Govt. P.G. College Dharamshala in partial
fulfilment for the award of the Degree of BACHELOR OF TECHNOLOGY in session
(2019-2023) in an authentic record of my own work carried out under the guidance of “Mrs.
Susheela Pathania” and the Project has not previously formed on the basis for the award of
and any other deree.
Place: Satvik Chandel
Date: 1906031044
This is to certify that that the above statement made by the candidate is correct to the best of
my knowledge.
Name Name
Designation Designation
[2]
INDUSTRY/COMPANY CERTIFICATE
Satvik Chandel
from Government P.G. College Dharamshala has successfully completed a 6-week online training on ProgrammingwithPython.Thetraining
consisted ofIntroductiontoPython,UsingVariablesinPython,Basicsof ProgramminginPython, Principles of Object-oriented Programming (OOP),
Connectingto SQLiteDatabase, Developing a GUI with PyQT, Application of Python in Various Disciplines, and The Final Project modules.
Satvik scored 98% marks in the final assessment and is a top performer in the training.
We wish Satvik all the best for future endeavours.
Date of certification: 2021-10-06 Certificate no. : 24C6CCCE-DA39-6854-
06C4-86FA82A9C717 For certificate authentication, please visit https://trainings.internshala.com/verify_certificate
TABLE OF CONTENTS
1. INTRODUCTION 5
2. SYSTEM STUDY 6
1) Problem Specifications 6
2) Existing System 6
3. DEVELOPMENT ENVIRONMENT 6
1) Hardware Requirement 6
2) Software Requirement 6
3) Programming Environment 6
a) Front End 6
b) Back End 6
4. SYSTEM DESIGN 7-16
1) Python Source Code 7-10
2) Source code Explanation 11-16
5. TESTING AND IMPLEMENTATION 17-19
6. CONCLUSION AND FURTHER ENHANCEMENTS 19
1) Conclusion 19
2) Further Enhancements 19
7. BIBLIOGRAPHY AND REFRENCES 20
[4]
INTRODUCTION
Python Language Introduction Python is a widely used general-purpose, high level programming
language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software
Foundation. It was mainly developed for emphasis on code readability, and its syntax allows
programmers to express concepts in fewer lines of code. Python is a programming language that lets
you work quickly and integrate systems more efficiently. Python is a high-level, interpreted,
interactive and object-oriented scripting language. Python is designed to be highly readable. It uses
English keywords frequently where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.
• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple text
processing to WWW browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from
many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and
other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under
the GNU General Public License (GPL). Python is now maintained by a core development team at the
institute, although Guido van Rossum still holds a vital role in directing its progress.
Python Features
Python's features include –
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface
on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh, and
the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than shell
scripting.
[5]
SYSTEM STUDY
1) Problem Specification
Create a simple pc application of a text editor in Python using PyQt. The functions of this
application are as follows:
It should have notepad like GUI
It should consist of a toolbar and a menu bar.
It should have functionalities such as cut, copy and paste.
It should have feature to open files and save files in “*.txt” format.
2) Existing system
Notepad is prime example of existing system of a text editor which performs simple cut
copy and paste. It also creates files in “.txt” format. Basically above problem is to create
a notepad like application in python using pyqt.
DEVELOPMENT ENVIRONMENT
1) Software requirements
(i) Python 3.5 or greater
(ii) PyQt5 or greater
(iii)VS Code (if necessary)
2) Hardware requirements
(i)Any windows, linux or mac pc or system that can run pyqt5 or greater
3) Programming Environment
i) Front End
PyQt5 is one of the most used modules in building GUI apps in Python, and that's
due to its simplicity as you will see. Another great feature that encourages
developers to use PyQt5 is the PyQt5 designer, which makes it so easy to develop
complex GUI apps in a short time. You just drag your widgets to build your form.
PyQt5 comprises a number of different components. First of all there are a number
of Python extension modules. These are all installed in the PyQt5 Python package
and are described in the list of modules.
ii) Back End
Python has several powerful libraries with a huge amount of pre-written code.
Hence developers don't need to write the code from scratch, thereby speeding up
the development time. This makes it an ideal choice to use Python for backend
development. Python is full-stack, so it can be used both for back-end and front-
end development. Similar to Node. js, Python is cross-platform, so a Python
program written on Mac will run on Linux. Both Mac and Linux have Python pre-
installed, but on Windows you need to install the Python interpreter yourself.
[6]
SYSTEM DESIGN (PYTHON SOURCE CODE)
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import *
import os
import sys
class MainWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.setGeometry(200, 200, 500, 400)
layout = QVBoxLayout()
self.editor = QPlainTextEdit() # Could also use a QTextEdit and set
self.editor.setAcceptRichText(False)
# Setup the QTextEdit editor configuration
fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
fixedfont.setPointSize(12)
self.editor.setFont(fixedfont)
# self.path holds the path of the currently open file.
# If none, we haven't got a file open yet (or creating new).
self.path = None
layout.addWidget(self.editor)
container = QWidget()
container.setLayout(layout)
self.setCentralWidget(container)
self.status = QStatusBar()
self.setStatusBar(self.status)
file_toolbar = QToolBar("File")
self.addToolBar(file_toolbar)
file_menu = self.menuBar().addMenu("&File")
open_file_action = QAction("Open", self)
open_file_action.setStatusTip("Open file")
open_file_action.triggered.connect(self.file_open)
file_menu.addAction(open_file_action)
file_toolbar.addAction(open_file_action)
save_file_action = QAction("Save", self)
save_file_action.setStatusTip("Save current page")
save_file_action.triggered.connect(self.file_save)
file_menu.addAction(save_file_action)
[7]
file_toolbar.addAction(save_file_action)
saveas_file_action = QAction("Save As", self)
saveas_file_action.setStatusTip("Save current page to specified file")
saveas_file_action.triggered.connect(self.file_saveas)
file_menu.addAction(saveas_file_action)
file_toolbar.addAction(saveas_file_action)
print_action = QAction("Print", self)
print_action.setStatusTip("Print current page")
print_action.triggered.connect(self.file_print)
file_menu.addAction(print_action)
file_toolbar.addAction(print_action)
edit_toolbar = QToolBar("Edit")
self.addToolBar(edit_toolbar)
edit_menu = self.menuBar().addMenu("&Edit")
undo_action = QAction( "Undo", self)
undo_action.setStatusTip("Undo last change")
undo_action.triggered.connect(self.editor.undo)
edit_menu.addAction(undo_action)
edit_toolbar.addAction(undo_action)
redo_action = QAction( "Redo", self)
redo_action.setStatusTip("Redo last change")
redo_action.triggered.connect(self.editor.redo)
edit_toolbar.addAction(redo_action)
edit_menu.addAction(redo_action)
edit_menu.addSeparator()
cut_action = QAction( "Cut", self)
cut_action.setStatusTip("Cut selected text")
cut_action.triggered.connect(self.editor.cut)
edit_toolbar.addAction(cut_action)
edit_menu.addAction(cut_action)
copy_action = QAction( "Copy", self)
copy_action.setStatusTip("Copy selected text")
copy_action.triggered.connect(self.editor.copy)
edit_toolbar.addAction(copy_action)
edit_menu.addAction(copy_action)
paste_action = QAction( "Paste", self)
paste_action.setStatusTip("Paste from clipboard")
paste_action.triggered.connect(self.editor.paste)
edit_toolbar.addAction(paste_action)
edit_menu.addAction(paste_action)
select_action = QAction( "Select all", self)
select_action.setStatusTip("Select all text")
select_action.triggered.connect(self.editor.selectAll)
[8]
edit_menu.addAction(select_action)
edit_menu.addSeparator()
wrap_action = QAction( "Wrap text to window", self)
wrap_action.setStatusTip("Toggle wrap text to window")
wrap_action.setCheckable(True)
wrap_action.setChecked(True)
wrap_action.triggered.connect(self.edit_toggle_wrap)
edit_menu.addAction(wrap_action)
self.update_title()
self.show()
def dialog_critical(self, s):
dlg = QMessageBox(self)
dlg.setText(s)
dlg.setIcon(QMessageBox.Critical)
dlg.show()
def file_open(self):
path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text documents
(*.txt);All files (*.*)")
if path:
try:
with open(path, 'rU') as f:
text = f.read()
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
self.editor.setPlainText(text)
self.update_title()
def file_save(self):
if self.path is None:
# If we do not have a path, we need to use Save As.
return self.file_saveas()
self._save_to_path(self.path)
def file_saveas(self):
path, _ = QFileDialog.getSaveFileName(self, "Save file", "", "Text documents
(*.txt);All files (*.*)")
if not path:
# If dialog is cancelled, will return ''
return
self._save_to_path(path)
[9]
def _save_to_path(self, path):
text = self.editor.toPlainText()
try:
with open(path, 'w') as f:
f.write(text)
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
self.update_title()
def file_print(self):
dlg = QPrintDialog()
if dlg.exec_():
self.editor.print_(dlg.printer())
def update_title(self):
self.setWindowTitle("%s - Satvik's Writing Pad" % (os.path.basename(self.path) if
self.path else "Untitled"))
def edit_toggle_wrap(self):
self.editor.setLineWrapMode( 1 if self.editor.lineWrapMode() == 0 else 0 )
if __name__ == '__main__':
app = QApplication(sys.argv)
app.setApplicationName("Satvik's Writing Pad")
window = MainWindow()
app.exec_()
[10]
Source Code Explanation
Importing required libraries
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtPrintSupport import *
Creating main window class
class MainWindow(QMainWindow):
Creating constructor and creating QVBoxLayout and setting font for the QTextEdit object
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
# setting window geometry
self.setGeometry(200, 200, 500, 400)
layout = QVBoxLayout()
self.editor = QPlainTextEdit() # Could also use a QTextEdit and set
self.editor.setAcceptRichText(False)
# Setup the QTextEdit editor configuration
fixedfont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
fixedfont.setPointSize(12)
self.editor.setFont(fixedfont)
# self.path holds the path of the currently open file.
# If none, we haven't got a file open yet (or creating new).
self.path = None
Creating menu bar, file menu and file toolbar
# adding editor to the layout
layout.addWidget(self.editor)
# creating a QWidget layout
container = QWidget()
# setting layout to the container
container.setLayout(layout)
# making container as central widget
self.setCentralWidget(container)
# creating a status bar object
self.status = QStatusBar()
# setting status bar to the window
self.setStatusBar(self.status)
# creating a file tool bar
file_toolbar = QToolBar("File")
# adding file tool bar to the window
self.addToolBar(file_toolbar)
# creating a file menu
file_menu = self.menuBar().addMenu("&File")
[11]
Creating actions to add in file menu
# creating a open file action
open_file_action = QAction("Open file", self)
# setting status tip
open_file_action.setStatusTip("Open file")
# adding action to the open file
open_file_action.triggered.connect(self.file_open)
# adding this to file menu
file_menu.addAction(open_file_action)
# adding this to tool bar
file_toolbar.addAction(open_file_action)
# similarly creating a save action
save_file_action = QAction("Save", self)
save_file_action.setStatusTip("Save current page")
save_file_action.triggered.connect(self.file_save)
file_menu.addAction(save_file_action)
file_toolbar.addAction(save_file_action)
# similarly creating save action
saveas_file_action = QAction("Save As", self)
saveas_file_action.setStatusTip("Save current page to specified file")
saveas_file_action.triggered.connect(self.file_saveas)
file_menu.addAction(saveas_file_action)
file_toolbar.addAction(saveas_file_action)
# for print action
print_action = QAction("Print", self)
print_action.setStatusTip("Print current page")
print_action.triggered.connect(self.file_print)
file_menu.addAction(print_action)
file_toolbar.addAction(print_action)
Creating edit menu and edit toolbar
# creating edit tool bar for editing text
edit_toolbar = QToolBar("Edit")
# adding this tool bar to the main window
self.addToolBar(edit_toolbar)
# creating a edit menu bar
edit_menu = self.menuBar().addMenu("&Edit")
Adding actions to the tool bar and menu bar
# undo action
undo_action = QAction("Undo", self)
# adding status tip
undo_action.setStatusTip("Undo last change")
# when triggered undo the editor
undo_action.triggered.connect(self.editor.undo)
# adding this to tool and menu bar
edit_toolbar.addAction(undo_action)
edit_menu.addAction(undo_action)
[12]
# redo action
redo_action = QAction("Redo", self)
redo_action.setStatusTip("Redo last change")
# when triggered redo the editor
redo_action.triggered.connect(self.editor.redo)
# adding this to menu and tool bar
edit_toolbar.addAction(redo_action)
edit_menu.addAction(redo_action)
# cut action
cut_action = QAction("Cut", self)
cut_action.setStatusTip("Cut selected text")
# when triggered cut the editor text
cut_action.triggered.connect(self.editor.cut)
# adding this to menu and tool bar
edit_toolbar.addAction(cut_action)
edit_menu.addAction(cut_action)
# copy action
copy_action = QAction("Copy", self)
copy_action.setStatusTip("Copy selected text")
# when triggered copy the editor text
copy_action.triggered.connect(self.editor.copy)
# adding this to menu and tool bar
edit_toolbar.addAction(copy_action)
edit_menu.addAction(copy_action)
# paste action
paste_action = QAction("Paste", self)
paste_action.setStatusTip("Paste from clipboard")
# when triggered paste the copied text
paste_action.triggered.connect(self.editor.paste)
# adding this to menu and tool bar
edit_toolbar.addAction(paste_action)
edit_menu.addAction(paste_action)
# select all action
select_action = QAction("Select all", self)
select_action.setStatusTip("Select all text")
# when this triggered select the whole text
select_action.triggered.connect(self.editor.selectAll)
# adding this to menu and tool bar
edit_toolbar.addAction(select_action)
edit_menu.addAction(select_action)
[13]
# wrap action
wrap_action = QAction("Wrap text to window", self)
wrap_action.setStatusTip("Check to wrap text to window")
# making it checkable
wrap_action.setCheckable(True)
# making it checked
wrap_action.setChecked(True)
# adding action
wrap_action.triggered.connect(self.edit_toggle_wrap)
# adding it to edit menu not to the tool bar
edit_menu.addAction(wrap_action)
# calling update title method
self.update_title()
# showing all the components
self.show()
Creating dialog critical method to show errors
def dialog_critical(self, s):
# creating a QMessageBox object
dlg = QMessageBox(self)
# setting text to the dlg
dlg.setText(s)
# setting icon to it
dlg.setIcon(QMessageBox.Critical)
# showing it
dlg.show()
Actions called by open, save, save as and print buttons
# action called by file open action
def file_open(self):
# getting path and bool value
path, _ = QFileDialog.getOpenFileName(self, "Open file", "",
"Text documents (*.txt);All files (*.*)")
# if path is true
if path:
# try opening path
try:
with open(path, 'rU') as f:
# read the file
text = f.read()
# if some error occured
except Exception as e:
[14]
# show error using critical method
self.dialog_critical(str(e))
# else
else:
# update path value
self.path = path
# update the text
self.editor.setPlainText(text)
# update the title
self.update_title()
# action called by file save action
def file_save(self):
# if there is no save path
if self.path is None:
# call save as method
return self.file_saveas()
# else call save to path method
self._save_to_path(self.path)
# action called by save as action
def file_saveas(self):
# opening path
path, _ = QFileDialog.getSaveFileName(self, "Save file", "",
"Text documents (*.txt);All files (*.*)")
# if dialog is cancelled i.e no path is selected
if not path:
# return this method
# i.e no action performed
return
# else call save to path method
self._save_to_path(path)
# save to path method
def _save_to_path(self, path):
# get the text
text = self.editor.toPlainText()
# try catch block
try:
# opening file to write
with open(path, 'w') as f:
[15]
# write text in the file
f.write(text)
# if error occurs
except Exception as e:
# show error using critical
self.dialog_critical(str(e))
# else do this
else:
# change path
self.path = path
# update the title
self.update_title()
# action called by print
def file_print(self):
# creating a QPrintDialog
dlg = QPrintDialog()
# if executed
if dlg.exec_():
# print the text
self.editor.print_(dlg.printer())
# update title method
def update_title(self):
# setting window title with prefix as file name
# suffix aas PyQt5 Notepad
self.setWindowTitle("%s - PyQt5 Notepad" %(os.path.basename(self.path)
if self.path else
"Untitled"))
# action called by edit toggle
def edit_toggle_wrap(self):
# chaining line wrap mode
self.editor.setLineWrapMode(1 if self.editor.lineWrapMode()==0 else 0)
Drivers’ code
if __name__ == '__main__':
# creating PyQt5 application
app = QApplication(sys.argv)
# setting application name
app.setApplicationName("PyQt5-Note")
# creating a main window object
window = MainWindow()
# loop
app.exec_()
[16]
TESTING AND IMPLEMENTATION
Opening screen of the application. You can see the basic notepad interface with title bar,
menu bar and toolbar. We can write in the text area highlighted by blue border.
This is the file dropdown menu. It consist of open, save, save as, and print buttons.
Edit menu consist of undo, redo, cut, copy, paste, select all, and text wrap. Notice redo and
cut are divided by splitter and whenever you place your pointer on a button it shows what the
button does on the bottom of the window.
The print button opens the print dialog box of whatever the operating system you are using
whether it is mac , windows or linux.
The save and save as buttons will open the save dialog box and the files are stored in “.txt”
format.
CONCLUSION AND FURTHER ENHANCEMENTS
Conclusion
So it is concluded by the project that small GUI applications are easier to make in Python and
PyQt . The following are some features of python
Easy To Learn and Readable Language.
Interpreted Language.
Dynamically Typed Language.
Open Source And Free.
Large Standard Library.
High-Level Language.
Object Oriented Programming Language.
Large Community Support.
Further Enhancements
Further enhancements can be done to this project are:
Adding icons toolbar buttons instead of text.
Adding format button and formatting text option in edit menu such as changing font,
font size, bold, italic, underline etc.
Adding find and replace buttons and adding numbered lists and bullets.
BIBLIOGRAPHY AND REFRENCES
https://trainings.internshala.com/python-training
https://www.geeksforgeeks.org/python-programming-language/
https://www.w3schools.com/python/
https://www.python.org/
https://www.tutorialspoint.com/python/index.htm
https://www.tutorialspoint.com/pyqt/index.htm
[20]