Beruflich Dokumente
Kultur Dokumente
On
Bachelor of Technology
By
CHHAYA AGARWAL
18EJCEC043
We hereby declare that the work presented in this project entitled “PROGRAMMING
WITH PYTHON” for subject Project-I in the partial fulfillment of the requirements for
the award of the Degree of Bachelor of Technology in Electronics and Communication at
Jaipur Engineering College and Research Centre, Jaipur is an authentic work of our own.
We have not submitted the matter embodied i n this project work anywhere for
the award of any degree or diploma.
Signature of Student :
CHHAYA AGARWAL
18EJCEC043
Date:
Place:Jaipur
BONAFIDE CERTIFICATE
This is to certify that the project entitled "PROGRAMMING WITH PYTHON ” for subject
Project I is the bonafide work carried out by CHHAYA AGARWAL, student of B.Tech in
Electronics and Communication at Jaipur Engineering College and Research Centre,
during the session 2018-2019, in partial fulfillment of the requirements for the award of
the Degree of Bachelor of Technology in Computer Science & Engineering and the
project has not formed the basis for the award previously of any degree, diploma,
fellowship or any other similar title.
Date:
Place:
ACKNOWLEDGEMENT
The satisfaction that accompanies that the successful completion of any task would be
incomplete without the mention of people whose ceaseless cooperation made it possible,
whose constant guidance and encouragement crown all efforts with success.
We are grateful to our subject guide and supervisor for the subject knowledge, developing
perception and constructive suggestions that was helpful for us in the preparation of this
project.
We are also thankful to whole JECRC family for their continuous guidance, inspiration and
kind support that helped us in successful completion of this project.
We also thank our colleagues who have helped in successful completion of the project.
CHHAYA AGARWAL
18EJCEC043
PROGRAM OUTCOME:
5. Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
TABLE OF CONTENTS
Acknowledgement ------------------------------------------------------ v
Python is a programming language that lets you work quickly and integrate systems more
efficiently.
1. Enhanced readability
In Python, uniform indents are used to delimit blocks of statements instead of curly brackets like
in C, C++ and Java. This enhances readability.
In C, C++, Java
if (X%2==0)
{
if (x%3==0)
else
{
if (x%3==0)
System.out.println("divisible by 3 not divisible by 2");
else
System.out.println("not divisible by 3 nor by 2");
}
if num%2 == 0:
if num%3 == 0:
if num%3 == 0:
print ("Divisible by 3 not divisible by 2")
else:
print ("Not divisible by 3 nor by 2")
In Python
2. Dynamic typing
In Python, a variable to be used in a program need not have prior declaration of its name and
type.
3. Interpreted language
Python is an interpreter-based language. An interpreter executes one instruction at a time. So if
there is an error on line 7 of the code, it will execute instructions till line 6 and then stop. This is
unlike a compiler which will not execute any of the instructions even if there is a single error.
Thus, an interpreter is useful if you are new to programming because it allows you to see
partial output of your code and identify the error location more easily.
4. Extensible language
Python extension modules implement new built-in object types and can call C libraries and
system calls which Python doesn’t have direct access to.
Although development of Python started in the late 80’s, Python 1.0 was published in
January 1994. Some important features like cycle-detecting garbage collector and Unicode
support were added in Python 2.0 which was released in October 2000. Python 3.0 was
released in December 2008. It was designed to rectify certain flaws in earlier version. The
guiding principle of Python 3 was: "reduce feature duplication by removing old ways of doing
things". Python 3.0 doesn’t provide backward compatibility. That means a Python program
written using version 2.x syntax doesn’t execute under python 3.x interpreter. Since all the
Python libraries are not fully ported to Python 3, Python Software Foundation continues to
support Python 2. The foundation has recently announced it will discontinue Python 2
support by year 2020.
Some of the obvious differences between the Python 2.x variants and Python 3.x variants are
displayed below.
It is not mandatory to use parenthesis with Parentheses are mandatory with the print
the in-built print function. function.
Two types of input functions are available to The raw_input() function has been
read data from the console. The raw_input() deprecated and input() function more or less
function always treats the input as string, behaves as raw_input() thereby input is
while the input() function evaluates the input always read as string.
and accordingly decides the data type of
variable.
Integer division
Numbers that you type without any digits Evaluates the result of a division as decimals
after the decimal point are treated as even if the input number are not specified
integers during division. with decimals.
3/2 3/2
Unicode strings
to be marked
with a ‘u’.
Example: u’hello’
Example: u’hello’
Data Types in Python
When a program is run, data objects in the program are stored in the computer’s
memory for processing. While some of these objects can be modified at that memory
location, other data objects can’t be modified once they are stored in the memory.
The property of whether or not data objects can be modified in the same memory
location where they are stored is called mutability.
We can check the mutability of an object by checking its memory location before and after it is
modified. If the memory location remains the same when the data object is modified, it means
it is mutable.
To check the memory location of where a data object is stored, we use the function, id().
Consider the following example (you can try this yourself in IDLE):
>>> id(a) Using the function id() to get the memory location of a.
1906292064 The ID of the memory location where a is stored.
>>> a[1]=20 Replacing the second item in the list,10 with a new item, 20.
>>> print(a) Using the print() function to verify the new value of a.
>>> id(a) Using the function id() to get the memory location of a.
Notice that the memory location has not changed as the ID remains (1906292064) remains
the same before and after the variable is modified. This indicates that the list is mutable, i.e.,
it can be modified at the same memory location where it is stored. Now, let us check if a
tuple is mutable in Python.
Assigning values to the tuple b.
>>> b=(5, 10, 15)
>>> b[1]=20
ARITHMETIC OPERATORS
Addition
Example 1
>>> a=21
>>> b=10
>>> c=a+b
>>> c 31
SUBTRACTION
Subtracts the operand on the right from the operand on the left.
Example 1
>>> a=21
>>> b=10
>>> c=a-b
>>> c
11
MULTIPLICATION
Operator for Multiplication, *
Example 1
>>> a=-21
>>> b=10
>>> c=a*b
>>> c
-210
DIVISION
Operator for Division, /
Example 1
>>> a=21
>>> b=10
>>> c=a/b
>>> c
2.1
Modulus
Returns the remainder of division of the operand on the left by the operand on the right of the
operator.
Example 1
>>> a=21
>>> b=10
>>> c=a%b
>>> c
1
Exponent
Calculates the value of the operand on the left raised to operand on the right of the operator.
Example 1
>>> a=-4
>>> b=3
>>> c=a**b
>>> c
-64
You can use arithmetic operators on complex numbers in the same way as you would for
integer or float data types. The output is governed by rules of mathematics for complex
numbers.
>>> a=6+4j
>>> b=3+2j
>>>a+b
(9+6j)
>>> a-b
(3+2j)
Multiplication
The multiplication of two complex numbers is very similar to multiplication of two binomials.
Consider the following example:
a=6+4j
b=3+2j
c=a*b c=(6+4j)*(3+2j)
c=(18+12j+12j+8*-1)
c=10+24j
>>> a=6+4j
>>> b=3+2j
>>> a*b
(10+24j)
Division
The division of two complex numbers involvesmultiplying both sides by the
conjugate of the denominator, which is a number with the same real part and the opposite
imaginary part. Consider the following example:
a=6+4j
b=3+2j
c=a/b
c=(6+4j)*(3-2j)/(3+2j)(3-2j)
c=(18-12j+12j-8*-1)/(9-6j+6j-4*-1)
c=26/13
c=2+0j
>>> a=6+4j
>>> b=3+2j
>>> a/b
(2+0j)
You can use two or more specially designated characters within a string to format a string or
perform a command. These characters are called escape sequences. An escape sequence in
Python starts with a backslash (\). For example, \n is an escape sequence in which the
common meaning of the letter n is literally escaped and given an alternative meaning - a new
line.
Displayed here are a few common escape sequences available in python. You can try these
out in IDLE or the Python prompt from the windows command prompt.
Escape
sequenc Description Example Result
Breaks the >>> print('I designed this I designed this rhyme to string into
\n a new rhyme to explain in due explain in due time
Prints a single >>> print('It doesn\'t even It doesn't even matter how
\'
quote matter how hard you try') hard you try
+ Concatenation
[+] Appends the second string to the first.
Example
>>> print(a+b+ ' said Harry to Nearly Headless Nick.') #The + here appends the strings a and
b to the string in quotes.
>>>
+ Repetition
[*] Concatenates multiple copies of the same
string. Example
>>> print('Again and again Harry wrote the words on the parchment in his own blood
– '+a*5) # Here, the * joins or concatenates the string a repeatedly for 5 times.Again and
again Harry wrote the words on the parchment in his own blood – I must not tell lies…I must
not tell lies…I must not tell lies…I must not tell lies…I must not tell lies…
>>>
[] Slice
[] Gives the character at given index.
Example
T h e B u r r o w
0 1 2 3 4 5 6 7 8 9
>>> a='The Burrow' #String a
>>> a[8] #Here the index number in square brackets [ ] slices out the character at that
index, which is o in this example.'o'
>>>
If the second operand is omitted, the range goes up to the end of the string.
Note: The slice starts at the first index. The slice ends one index before the second index,
that is at the value of the index - 1.
Example
T h e B u r r o w
0 1 2 3 4 5 6 7 8 9
>>>
in Membership
[in] Returns true if a character exists in the given string.
Example
>>> a='Harry watched Dumbledore striding up and down in front of him, and thought. He
thought of his mother, his father and Sirius. He thought of Cedric Diggory.' #String a
>>> 'v' in a #Checks if the character 'v' is present in the string, aFalse
>>> 'dig' in a #Checks if the characters 'dig' are present in the string, aFalse
>>> 'Dig' in a #Note that this is case-sensitive. As 'Dig' is present in 'Diggory', this
returns True.True
>>>
not in Membership
[not in] Returns true if a character does not exist in the given string.
Example
>>> 'v' not in a #Checks that the character 'v' is not present in the string, a False
>>> 'Red' not in a #Checks that the characters 'Red' iare not present in the string, a
True
>>> 'red' notin a #This is case sensitive. Since 'red' is present in 'soared', this returns False. False
>>>
The format() Method
With Python 3.0, the format() method has been introduced for handling complex string
formatting more efficiently. This method of the built-in string class provides functionality for
complex variable substitutions and value formatting. This new formatting technique is
regarded as more elegant. The general syntax of format() method is:
string.format(var1, var2,...)
The string itself contains placeholders {} in which values of variables are successively
inserted.
You can also specify formatting symbols. Only change is using colon (:) instead of %. For
example, instead of %s use {:s} and instead of %d use (:d}
>>> "my name is {:s} and my age is {:d} years".format(name, age) 'my
name is Malhar and my age is 23 years'
>>>
>>> "my name is {:s}, age {:d} and I have scored {:6.3f} percent
marks".format(name, age, percentage)
'my name is Malhar, age 23 and I have scored 55.500 percent marks'
>>>
Other Methods for String Processing
capitalize()
capitalize(): This method converts the first character of a string to uppercase letter.
>>> var='internshala'
>>> var.capitalize()
'Internshala'
>>>
upper()
>>> var='internshala'
>>> var.upper()
'INTERNSHALA'
>>>
lower()
lower(): This method results in a string with uppercase characters replaced by corresponding
lowercase characters.
>>> var='INTERNSHALA'
>>> var.lower()
'internshala'
>>>
title()
title(): This method results in a string with the first character of each word converted to
uppercase.
>>> var='python training from internshala'
>>> var.title()
>>>
find()
find(): This method finds the first occurrence of a substring in another string. If not found, the
>>> var.find('on')4
>>> var.find('run')-1
>>>
method returns -1.
The substring 'in' first occurs at the 10th position (count starts from 0), 'on' is found at the 4th
position, but 'run' is not found hence returns -1.
index()
index(): This method is similar to find() but throws a ValueError if the substring is not found.
>>> var.index('in')10
var.index('run')
ValueError: substring not found
>>>
count()
>>> var.count('in') 3
>>>
isalpha()
isalpha(): This method returns true if all the characters in a string are alphabetic (a-z or A-Z),
otherwise returns false.
>>> var='Internshala'
>>> var.isalpha()
True
>>> var.isalpha()
False
>>>
islower()
islower(): This method returns true if all characters in a string are lowercase characters else
>>> var='internshala'
>>> var.islower()
True
>>> var='Internshala'
>>> var.islower()
False
>>> var.islower()
True
>>>
Dictionary Datatype
items()
This method returns a list of tuples, with each tuple containing one key and and the
corresponding value.
>>> captains.items()
>>>
keys()
This method returns a list object comprising keys in the dictionary.
>>> captains.keys()
>>>
values()
This method returns a list obje
>>> captains.keys()
>>>
Passing Arguments by reference
A variable is Python is a reference to the object memory. So, both formal and actual arguments
refer to the same object. The following code snippet will confirm this.
We have used the id() function earlier. It returns a unique integer corresponding to identity of
an object. In the code displayed above, the id() of a list object before and after passing to a
function shows an identical value.
>>> mylist=[10,20,30,40,50]
>>>
If we modify the list object inside the function and display its contents after the function is
completed, changes are reflected outside the function as well.
The following result confirms that arguments are passed by reference to a Python function.
>>> mylist=[10,20,30,40,50]
>>> myfunction(mylist)
modified list inside function: [10, 20, 30, 40, 50, 60]
>>>
url='#',
author='internshala',
author_email='internshala@internshala.com',
license='MIT',
packages=['MyFriends'],
zip_safe=False)
The SQLite project provides a simple command-line utility named sqlite3 (or sqlite3.exe on
Windows) that allows the user to manually enter and execute SQL statements against an
SQLite database.
To start the sqlite3 program, simply type "sqlite3" at the command prompt. The "sqlite3"
command may be optionally followed by the name the file that holds the SQLite database. If
the file does not exist, a new database file with the given name will be created automatically.
If no database file is specified on the command-line, a temporary database is created, then
deleted when the "sqlite3" program exits.
On start-up, the sqlite3 program will show a brief banner message then prompt you to enter
SQL. Type in SQL statements (terminated by a semicolon), press "Enter" and the SQL will be
executed.You can terminate the sqlite3 program by typing your system End-Of-File character
(usually a Control-D). Use the interrupt character (usually a Control-C) to stop a long-running
SQL statement.
sqlite> CREATE TABLE tbl2 (
...>f2 text,
...>f3 real
The ANSI Standard of SQL specifies the data types to be used by relational databases. SQLite
provides the following five data types which are referred to as storage classes:
Storage Meaning
Class
NULL Missing or unknown information.
REAL Real numbers with decimal values that use 8-byte floats.
TEXT Character data. SQLite supports various character encodings.
BLOB Binary Large Object that can be used to store any kind of data. The maximum
size of BLOBs is unlimited.
Name= Sherlock
House = Slytherin
Marks = 65
1. Assuming that the database MySchool is created and contains the table student, we
start by creating a connection:
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
MySchool.commit()
The new record is added to the table. You can verify this from SQLite Studio. You
can refer to the helper text for the relevant screenshot.
The SELECT query forms a result set containing all records returned as a response to a query.
The execute() method uses a string representing the SELECT query statement. There are two
prominent methods as per DB-API standard. The below two methods are used:
fetchone()
This method fetches the next available record from the result set. It is a tuple consisting of
values of each column of the fetched record. The Following code snippet retrieves and prints
one record at a time till the result set is exhausted.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
curschool.execute(sql)while True:
record=curschool.fetchone() if
record==None:
break
print (record)
fetchall()
This method fetches all the remaining records in the form of a list of tuples. Each tuple
corresponds to one record and contains values of each column in the table. The following
code snippet fetches all records and prints them one at a time by using the 'for' statement.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
curschool.execute(sql)
result=curschool.fetchall()for record in result:
print (record)
Designer Tools for PyQt5
NOTE: The method explained in the video is obsolete, as the wheel files are no longer available on
the website.
For Windows:
1. Open command line window.
2. Run the command: pip3 install pyqt5-tools==5.9.0.1.2
3. Go to your Python installation folder (assuming it is C:\python36)
4. You will find a folder called Lib. You will find designer.exe file in it's sub-directories.
5. Go to the folder C:\Python36\Lib\site-packages\pyqt5-tools
6. You can find designer.exe in this folder. Run that file
7.
For Linux:
1. Open terminal.
2. Run the following command: sudo apt-get install qttools5-dev-tools
3. The executable file designer can be found in the following directory:
/usr/lib/i386-linux-gnu/qt5/bin/
NOTE: The directory name i386-linux-gnu may differ on your machine, depending on
your OS variant.
txt=self.lineEdit.text() if
txt=='Internshala':
else:
In this function, lineEdit refers to the name of the Password line edit field generated in Qt Designer.
self.button1.clicked.connect(self.chkPassword)
Save this script and run it. Test the working of the OK button by entering any
password and by entering the password, Internshala.
QForm Layout
QForm Layout is a convenient way to create a form with two columns and multiple rows.
Create a new form.
Roughly place all the required widgets into the form.
Use the Layout option, Form layout which will automatically arrange our
widgets. Let's look at the steps:
Step 1
Start Qt Designer.
Create a new form using the template, Widget.
Use the Layout option, Form layout which will automatically arrange our
widgets. Let's look at the steps.
Step 2
Let's first place widgets for the right column. You can just drag them and drop
them anywhere.
1. Two LineEdit widgets (Name, Qualification)
2. One vertical layout (For holding Address and City)
3. Two horizontal layout objects (one for holding the gender radio
buttons and the other for the Reset and Submit buttons)
Step 3
Step 4
Step 5
Today Python has become language of choice for data scientists. Python libraries like NumPy, Pandas and
Matplotlib are used extensively in the process of data analysis and collection, processing and cleansing of
data sets, applying mathematical algorithms to data and to generate visualizations for the benefit of
users. Commercial Python distributions such as Anaconda and Activestate provide all the essential
libraries required for data science.
Data science today has become a prominent buzzword and it has been termed as ‘sexiest job of 21st
century!’.
Machine Learning
This is another glamorous application area where Python developers are getting attracted. Based upon
the past data, Python libraries such as Scikit-learn, Tensorflow, and NLTK are widely used for prediction
of trends like customer satisfaction, projected values of stocks etc.
Some of the real world applications of machine learning are as under:
Medical Diagnosis: Machine learning techniques are used for the analysis of the importance of clinical
parameters and of their combinations for prognosis, e.g. prediction of disease progression, for the
extraction of medical knowledge for outcomes research, for therapy planning and support, and for overall
patient management.
Statistical Arbitrage: Machine learning methods are applied to automate trading strategies where user
tries to implement a trading algorithm for a set of securities on the basis of quantities such as historical
correlations and general economic variables.
Learning associations: Machine learning helps the process of developing insights into various
associations between products and buying behaviors of customers.
Basket analysis- studying the association between the products people buy and suggesting the
associated product to the customer, is a well known phenomenon we see while doing online shopping.
Machine learning is at work behind this analysis.
Prediction: Current prediction is one of the hottest machine learning algorithms. Businesses are interested
in finding out what will be my sales next month / year / Diwali, etc. so that business can take required
decision (related to procurement, stocks, etc.) on time.
Web Development
Another application area which is becoming increasing popular with Python developers is web
development. Simple to complex web applications can be developed using easy to use web application
frameworks like django, Pyramid, Flask etc. These frameworks are used extensively by various IT
companies. Dropbox for example uses django as a backend to store, synchronize local folders.
Most of the web servers today are compatible with WSGI (Web Server Gateway Interface) – a
specification for universal interface between Python web frameworks and web servers. All leading web
servers such as Apache, IIS, Nginx etc can now host Python web applications. Google’s App Engine hosts
web applications built with almost all Python web frameworks.
Image processing
Face detection and gesture recognition using OpenCV library and Python is another important
application. OpenCV is a C++ library, but has been ported to Python. This library has lot of extremely
powerful image processing functions.
Facebook’s automatic tag suggestion feature, which used face recognition to suggest people you might
want to tag in your photos, is an instance of OpenCV at work. Other instances of OpenCV applications
are:
Game Development
Python is a popular choice of game developers. The Pygame library is extensively used for building
games for desktop as well as mobile platforms. Pygame applications can be installed on Android too.
Android apps
Although Android apps are predominantly developed using Android SDK which is more or less like Java,
Python can also be used to develop Android apps. Python’s Kivy library has all the functionality required
to build a mobile application.
Automated Jobs
Python is extremely useful and widely used for automating CRON jobs. Certain tasks like backups can be
scheduled to be invoked automatically. These tasks are defined in Python scripts and operating system
scheduler executes them at predefined times.
Python is embedded as a scripting language in many popular software products. This is similar to VBA
used for writing macros in Excel, Powerpoint etc. Similarly Python API is integrated with Maya, PaintShop
pro, etc.
Python has found applications in very diverse fields. There is Astropy library is a collection of software
packages written in the Python programming language and designed for use in astronomy. BioPython
package contains functionality useful for computational biology and bio-informatics.
More and more companies, be it start ups or established ones are using Python for one or other purpose
in their development activities. Hence, lot of opportunities are waiting for those with appropriate Python
skills.