Sie sind auf Seite 1von 45

A

INDUSTRIAL TRAINING REPORT

On

“PROGRAMMING WITH PYTHON”

Submitted in partial fulfillment for the award of degree of

Bachelor of Technology

By

CHHAYA AGARWAL
18EJCEC043

Department Of Electronics & Communication Engineering


Jaipur Engineering College & Research Centre
Jaipur, Rajasthan
2019-20

SUBMITTED TO: SUBMITTED BY: CHHAYA AGARWAL

(IT Coordinator,ECE) REGISTRATION NO.


CANDIDATE’S DECLARATION

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.

Signature of the Supervisor:

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:

1.Engineering knowledge:Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.

2.Problem analysis:Identify, formulate, research literature, and analyze complex


engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.

1. Design/development of solutions:Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

2. Conduct investigations of complex problems: Use research-based


knowledge and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide valid conclusions.

3. Modern tool usage: Create, select, and apply appropriate techniques,


resources, and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.

4. The engineer and society:Apply reasoning informed by the contextual


knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.

5. Environment and sustainability:Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
1. Ethics:Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.

2. Individual and team work: Function effectively as an individual, and as a


member or leader in diverse teams, and in multidisciplinary settings.

3. Communication: Communicate effectively on complex engineering activities


with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.

4. Project management and finance: Demonstrate knowledge and


understanding of the engineering and management principles and apply these to one’s
own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.

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

Cover Page ----------------------------------------------------------------- i

Title Page ------------------------------------------------------------------ ii

Candidates Declaration ------------------------------------------------- iii

Bonafide Certificate ------------------------------------------------------ iv

Acknowledgement ------------------------------------------------------ v

Program Outcome ------------------------------------------------------- vi

Course Outcome -------------------------------------------------------- vii

Abstract ----------------------------------------------------------------- viii

Table Of Contents ------------------------------------------------------ ix


INTRODUCTION TO PYTHON

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
softwareFoundation. It was mainly developed for emphasis on code redability, 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.

Salient Features of Python


Let us take a closer look at some of the salient features of Python.

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)

System.out.println("divisible by 2 and 3");


else

System.out.println("divisible by 2 not divisible by 3");


}

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:

print ("Divisible by 3 and 2")


else:

print ("Divisible by 2 not divisible by 3")


else:

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.

5. Standard DB2 API


A standard data connectivity API facilitates using data sources such as Oracle, MySQL and
SQLite as a backend to a Python program for storage, retrieval and processing of data.
Comparing Python 2.x and Python 3.x

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.

Python 2.x Python 3.x

It is not mandatory to use parenthesis with Parentheses are mandatory with the print
the in-built print function. function.

Valid statements Valid statement

print "Hello World" print ("Hello World")


print ("Hello World")

If the parentheses are missing, the


interpreter displays the following error:
SyntaxError: Missing parentheses in call to
'print'
Input

Python 2.x Python


Python3.x
3.x

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

Python 2.x Python 3.x

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

Output = 1 Output = 1.5

Unicode strings

Python 2.x Python 3.x

Strings are stored as ASCII by default. Stores strings as Unicode by default

To store strings as Unicode, they have

to be marked

with a ‘u’.
Example: u’hello’

them. To allocate more memory to an

integer object, a trailing L is attached.

Example: u’hello’
Data Types in Python

Mutable and Immutable Objects

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

>>> a=[5, 10, 15] Assigning values to the list a.

>>> 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.

[5, 20, 15] Verified that the value of a has changed.

>>> id(a) Using the function id() to get the memory location of a.

1906292064 The ID of the memory location where a is stored.

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)

Replacing the second item in


the list, 10 with a new item, 20.
>>> b[1]=20

Error explaining that a tuple


Traceback (most recent call last):
does not support a modification
in the items – i.e, it is
immutable.

>>> b=(5, 10, 15) Assigning values to the tuple b.

Replacing the second item in


the list, 10 with a new item, 20.

>>> b[1]=20

Traceback (most recent call last): Error explaining that a tuple


does not support a modification
in the items – i.e, it is
immutable.
TypeError: 'tuple' object does not
support item assignment

TypeError: 'tuple' object does not


support item assignment

ARITHMETIC OPERATORS

Addition

Operator for Addition, +

Adds the operands on either side of the operator.

Example 1

>>> a=21
>>> b=10
>>> c=a+b
>>> c 31

SUBTRACTION

Operator for 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, *

Multiplies values on either side of the operator.

Example 1
>>> a=-21
>>> b=10
>>> c=a*b
>>> c
-210

DIVISION
Operator for Division, /

Divides left hand operand by right hand operand.

Example 1

>>> a=21
>>> b=10
>>> c=a/b
>>> c
2.1

Modulus

Operator for 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

Note: In Python, the modulus is calculated towards


negative infinity. Thus, 21%10 is 1 because the closest
multiple of 10 towards negative infinity is 20. But -
21%10 is 9 because the closest multiple of 10 towards
negative infinity is -30 and -30+9 is -21.

Exponent

Operator for 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

Arithmetic operations on complex numbers


A complex number – also known as imaginary number – is defined as square root of (-1) ( and
is denoted by J or j. A complex number is represented as x+yj. Both x and y are real numbers.
Y multiplied by the imaginary number forms the imaginary part of a complex number.

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.

Addition and Subtraction

The addition or subtraction of complex numbers involves the addition or subtraction

of their corresponding real and imaginary parts.

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

Formatting Strings using Escape Sequences

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

line time\nAll I know') All I know

Adds a >>> print('Time is a


\t
Time is a valuable thing
horizontal tab \tvaluable thing')

Prints a >>> print('Watch it fly by\\ Watch it fly by\ as the


\\
backslash as the pendulum swings') pendulum swings

Prints a single >>> print('It doesn\'t even It doesn't even matter how
\'
quote matter how hard you try') hard you try

Prints a double >>> print('It is so


\"
It is so "unreal"
String Operators

You can use certain operators for string processing.

+ Concatenation
[+] Appends the second string to the first.
Example

>>> a='"Hello, ' #String a

>>> b='Nick",' #String b

>>> print(a+b+ ' said Harry to Nearly Headless Nick.') #The + here appends the strings a and
b to the string in quotes.

"Hello, Nick", said Harry to Nearly Headless Nick.

>>>

+ Repetition
[*] Concatenates multiple copies of the same
string. Example

>>> a='I must not tell lies…' # String a

>>> 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'

>>>

[:] Range Slice


[ : ] Fetches characters in the range specified by two index operands separated
by a colon.

If the first operand is omitted, the range starts at zero index.

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

>>> a='The Burrow' #String a

>>> a[2:7] #Starting index = 2 = e, Ending index = 7-1 = r'e Bur'

>>> a[:6] #Starting index = 0 = T, Ending index = 6-1 = u'The Bu

'>>> a[5:] #Starting index = 5 = u, Ending index = end of string = w'urrow'

>>>

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

>>> a=''' “For HIM?” shouted Snape. “Expecto Patronum!"


From the tip of his wand burst the silver doe: She landed on the office floor, bounded once
across the office, and soared out of the window. Dumbledore watched her fly away, and as
her silvery glow faded he turned back to Snape, and his eyes were full of tears.

“After all this time?”


“Always,” said Snape.''' #Multi-line string, a

>>> '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'

>>>

Precision formatting of numbers can be accordingly done.

>>> "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()

upper(): This method returns a string with lowercase characters replaced by


corresponding uppercase characters.

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

'Python Training From Internshala'

>>>

find()

find(): This method finds the first occurrence of a substring in another string. If not found, the

>>> var='python training from internshala'


>>> var.find('in')10

>>> 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='python training from internshala'

>>> var.index('in')10

>>> var.index('run')Traceback (most recent call last): File


"<pyshell#19>", line 1, in <module>

var.index('run')
ValueError: substring not found

>>>
count()

count(): This method returns the number of occurrences of a substring in given


string
>>> var='python training from internshala'

>>> 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='Intern shala'

>>> 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='intern shala'

>>> 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={'England': 'Root', 'Australia': 'Smith', 'India': 'Virat', 'Pakistan': 'Sarfraz'}

>>> captains.items()

dict_items([('England', 'Root'), ('Australia', 'Smith'), ('India', 'Virat'), ('Pakistan',


'Sarfraz')])

>>>

keys()
This method returns a list object comprising keys in the dictionary.

>>> captains={'England': 'Root', 'Australia': 'Smith', 'India': 'Virat', 'Pakistan': 'Sarfraz'}

>>> captains.keys()

dict_items(['England', 'Australia', 'India', 'Pakistan'])

>>>

values()
This method returns a list obje

>>> captains={'England': 'Root', 'Australia': 'Smith', 'India': 'Virat', 'Pakistan': 'Sarfraz'}

>>> captains.keys()

dict_items(['England', 'Australia', 'India', 'Pakistan'])

>>>
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.

>>> def myfunction(newlist):

print("List accessed in function: ", "id:", id(newlist))


return

>>> mylist=[10,20,30,40,50]

>>> print("List before passing to function: ", "id:", id(mylist))

List before passing to function: id: 2430484894856>>> myfunction(mylist) List


accessed in function: id: 2430484894856

>>>

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.

>>> def myfunction(list):


list.append(60)

print("modified list inside function:", list)return

>>> mylist=[10,20,30,40,50]

>>> print("list before passing to function:", mylist) list


before passing to function: [10, 20, 30, 40, 50]

>>> myfunction(mylist)

modified list inside function: [10, 20, 30, 40, 50, 60]

>>> print("list after passing to function:", mylist)


list after passing to function: [10, 20, 30, 40, 50, 60]

>>>

Creating a Package Setup File


from setuptools import setup

setup(name='MyFriends', version='1.0', description='A package to calculate expenses when you


hang-out with friends.',

url='#',
author='internshala',
author_email='internshala@internshala.com',

license='MIT',
packages=['MyFriends'],

zip_safe=False)

Command Line Shell for SQLite

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 (

...>f1 varchar(30) primary key, .

...>f2 text,

...>f3 real

SQLite Data Types


Let's talk a little about data types that are used in SQLite databases. SQLite uses what is called,
dynamic type system. That means, the value stored in a column determines its data type and
not the column's data type. Also, you don’t have to define a specific data type for a column
when you create a table. Even if you have a column with the integer data type for example,
you can store any kind of data types such as text and SQLite will not complain about this.

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.

INTEGER Whole numbers, either positive or negative.

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.

Inserting a new Record


In the previous section, you learned how to create a database and a table within it. Now, let's
see how to create a new record in the existing table, student.

Example 1: To add the following record:

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

2. To add a new record to the table, we execute the INSERT query.

import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()

curschool.execute("INSERT INTO student (StudentID, name, house, marks)


VALUES (5,'Sherlock',32,50);")

3. We now commit the changes to confirm them.

import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()

curschool.execute("INSERT INTO student (StudentID, name, house, marks)


VALUES (5,'Sherlock',32,50);")

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.

Retrieving a new Record

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

sql="SELECT * from student;"

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

sql="SELECT * from student;"

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.

Kindly follow these steps to install QT Designer on your computer.

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.

Adding an Event Handler in a Python Script


Let's continue with the myui file from the previous section. (You can download this from the
Helper Text for the video.) Now, let's see how to add a user-defined function to the Python script
and connect it to the clicked signal of the OK button. Assume that we want to print the message
‘Valid Password’ if the password field contains the text 'Internshala' otherwise print the message,
‘Invalid Password’.

 Open the myui.py file in IDLE.


 Now, add the following function inside the class, Ui_MainWindow
def chkPassword(self):

txt=self.lineEdit.text() if
txt=='Internshala':

print ('Valid password')

else:

print ('Invalid password')

In this function, lineEdit refers to the name of the Password line edit field generated in Qt Designer.

Next, add the following statement inside the method, setupUi().

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

 Let's now place the text labels in the left column.

Step 4

 Now, let's place the required elements into the layouts.


1. First, we place a multi-line text box(address) and a LineEdit (City)
widget in the vertical layout.
2. Next, we place two radio buttons (Male, Female) in one horizontal
layout.
3. Finally we place two push buttons(Reset, Submit) in the second
horizontal layout.

Step 5

 Finally, we right-click on QWidget in the Object Inspector Window and select


Layout - lay out in form layout.
You can customize the labels and buttons captions before saving the ui file and generating
the py file.
Application of Python in Various Disciplines

Application of Python in Various Disciplines


Data Science
In recent times, Python has shot up in popularity charts mainly because of its Data science libraries. With
huge amount of data being generated by web applications, mobile applications and other devices,
companies need business insights from this data.

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:

● Automated inspection and surveillance.


● Robot and driverless car navigation and control.
● Medical image analysis.
● Video/image search and retrieval.

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.

Embedded Systems and IoT


Another important area of Python application is in embedded systems. Raspberry Pi is a very popular yet
a low cost single board computer. It is being extensively used in automation products, robotics, IoT, and
kiosk applications. Those of you with Electronics background can certainly explore the possibility of
becoming innovators.
Apart from Raspberry Pi, other microcontrollers can also be programmed with Python. A lightweight
version of Python called micropython has been developed especially for microcontrollers. Popular
microcontrollers like Arduino are used in many IoT products and programmed with Python. A special
micropython compatible controller called Pyboard has also been developed.

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 as a Rapid Development Tool


Although Python is becoming increasingly popular, software development field is still dominated by Java
and Dot net platform. However, Java and C# developers are also taking help of power of Python’s rapid
development capabilities. Jython, the JRE implementation of Python and IronPython, the dot net
implementation interact seamlessly with Java and C# respectively. For example- Jython can use all Java
libraries such as Swing, etc. So the development time can be minimized by using simpler Python syntax
and Java libraries for prototyping of the software product.

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.

Das könnte Ihnen auch gefallen