0% found this document useful (0 votes)
78 views50 pages

Internship Sample Report

Uploaded by

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

Internship Sample Report

Uploaded by

kavyaraga101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

VISVESVARAYA TECHNOLOGICAL UNIVERSITY,

BELAGAVI

AN INTERNSHIP REPORT
ON
“ PROGRAMMING WITH PYTHON”

Submitted in partial fulfillment of requirements of 8th semester


of B.E course during the year 2023-2024

Submitted by
SNEHA (3GN17EC060)

Under the Guidance of


Dr.SHWETA PATIL

DEPARTMENT OF
ELECTRONICS AND COMMUNICATION ENGINEERING
GURU NANAK DEV ENGINEERING COLLEGE, BIDAR
ACADEMIC YEAR 2023-2024
GURU NANAK DEV ENGINEERING COLLEGE, BIDAR

DEPARTMENT OF
ELECTRONICS AND COMMUNICATION ENGINEERING

CERTIFICATE
This is certified that the internship work entitled “Programming with Python” is a
bonafide work carried out by SNEHA (3GN17EC060) in partial fulfillment of the
requirements for the award of Degree Bachelor of Engineering in ELECTRONICS
AND COMMUNICATION ENGINEERING by VISVESVARAYA
TECHNOLOGICAL UNIVERSITY, BELAGAVI during the year 2023-2024. The
internship report has been approved as it satisfies the academic requirements in
respect of internship work prescribed for the Bachelor of Engineering Degree.

DR.SHEWTA PATIL DR.SHEWTA PATIL DR.KISHAN SINGH


GUIDE CO-ORDINATOR HOD

SNEHA
(3GN17EC060)

External Viva
Name of Examiners Signature with Date
1).............................. 1)...............................
2).............................. 2)...............................

1
ACKNOWLEDGEMENT

I would like to express my deep sense of gratitude to our principal Dr.Suresh Reddy
Guru Nanak Dev Engineering College, Bidar for his inspiration and academic support by
providing good facilities to complete the internship.

My sincere thanks to Dr.Kishan Singh, Head of the Department, Electronics and


Communication Engineering for his whole hearted support in completion of this internship.

I am highly indebted to my internship coordinator Dr.Shweta Patil for guiding and


giving me timely advice and suggestions in the successful completion of the internship.

I am highly indebted to my internship guide Dr.Shweta Patil for guiding and giving
me timely advice and suggestions in the successful completion of the internship.

I thank all the staff members for supporting the completion of my internship. Also I
am thankful to my parents and all my dear friends who have directly or indirectly helped me.

Finally, I express gratefulness to all those who knowingly or unknowingly helped me


in successful completion of this internship.

SNEHA
( 3GN17EC060)

2
CERTIFICATE

3
TABLE OF CONTENTS

SI.NO TITLE PAGE.No

CHAPTER 1 COMPANY PROFILE 5

CHAPTER 2 ABOUT THE COMPANY 6

CHAPTER 3 TASK PERFORMED 7-48

3.1. Introduction to Python 8-9


3.2. Using Variables in Python 10-22
3.3 Basics of Programming In Python 23-27
3.4. Principles Of Object Oriented Programming(OOP) 28-30
3.5. Connecting to SQlite Database 31-37
3.6. Developing a GUI with PyQT 38-44
3.7. Application of Python in Various Disciplines 45-48

CHAPTER 4 CONCLUSION 49

4
CHAPTER 1

COMPANY PROFILE

Name of the company : Internshala

Head quarters :Gurgaon

Founded in :2010

Founder: Sarvesh Agrawal

Company type :Private, Employment website

Industry: Education ,Employment.

Services :Internship matching,Online training.

Website: internshala.com

5
CHAPTER 2

ABOUT INTERNSHALA
Internshala is an internship and online training platform, based out of Gurgaon, India. It was
founded by Sarvesh Aggarwal, an IIT Madras alumnus, in 2010, the website helps students
find internships with organizations in India.

HISTORY

The platform which was founded in 2010, started as a WordPress blog that aggregated
internships across India and articles on education, technology and skill gap. Internshala
launched its online training in 2014. As of 2018, the platform had 3.5 million students and
80,000 companies.

PARTNERSHIPS

In august 2016, Telangana’s not-for-profit organization, Telangana Academy for skill and
knowledge (TASK) partnered with Internshala to help students with Internship resources and
career services.

In September 2016, Team Indus, Google XPRIZE shortlisted entity, partnered with
Internshala for college outreach for its initiative, Lab2Moon.

AWARDS AND RECOGNITION

In 2011, the website became a part of NASSCOM 10k startups. In 2015, Internshala was a
finalist in People Matters TechHR 2015 Spotlight Awards under ‘Futurism in Recruitment
category.

6
About
In this training program we have learnt about Python (Basics of programming, OOP’s
concept in Python, GUI toolkit), Database connectivity etc.

This training introduces object-oriented concepts and the Python programming language. It is
divided into different modules. The module begins with a brief explanation of basic
programming with Python and Object-Oriented concepts. This training covered essential
concepts on the building blocks of Python, object-oriented programming, the use of SQLite
database and development of GUIs for Python applications.

7
CHAPTER 3
1. INTRODUCTION TO PYTHON

1.1 PYTHON

Python is a high-level, interpreted, interactive and object-oriented scriptinglanguage.


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.

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

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

Python has a big list of good features:

● It supports functional and structured programming methods as well as OOP.

● It can be used as a scripting language or can be compiled to byte-code for building


large applications.

● It provides very high-level dynamic data types and supports dynamic type checking.

● IT supports automatic garbage collection.

9
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

2. USING VARIABLES IN PYTHON

2.1 Data Types in Python

The built-in data types in Python are displayed below

Numeric Any representation of data which has numeric value. Python


identifies three types of numbers – integer, float and complex
number.

Integer Positive and negative whole numbers.

Examples: 1234, -234, 0x46 (hexadecimal number), 0O123 (Octalnumber)

Note: In C and related programming languages such as


Python, a hexadecimal number is prefixed with 0x and an
octal number is prefixed with 0O.

Float Real numbers with a floating point representation in which the


fractional component is denoted by a decimal or scientific
notation.

Examples: -55.550, 0.005, 1.32E10 (scientific notation))

Complex A number with a real and imaginary component is represented


number as a + bjinPython where a and b are floats and
j = -1

10
Examples: 4+6j, -2.3+6.4j

Note: The common mathematical representation of a complex


number uses a +bi with i being the imaginary part. But in
electronics j is used because i already represent current and
The next letter after i is j.

Boolean Any representation of data which has two values denoted by


True and False.

Sequence An ordered collection of similar or different data types. The


built-in Sequence data types in Python are – String, List and
Tuple.

String A collection of one or more characters put in single, double or


triple quotes.

Examples: ‘Hello’, "Hello", "'Hello'", """Hello"""

List An ordered collection of one or more data items, not


necessarily of the same type, put in square brackets.

Examples: [1,"Ravi",75.50, True]

Tuple An ordered collection of one or more data items, not


necessarily of the same type put in parentheses. The contents of a
tuple cannot be modified – it is immutable - after the tuple is
created.

Examples: (1,"Ravi", 75.50, True)


Note: Refer to the Helper Text to learn more about mutability.

Dictionary An unordered collection of data in key:value pair form.


Collection of such pairs is enclosed in curly brackets.

Example: {1:"Superman", 2:"Wonder Woman", 3:"Thor", 4:


"Hulk", 5:"Black Widow"}

2.2 VARIABLES

11
Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals or characters in these variables.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.

counter =100# An integer assignment

miles =1000.0# A floating point

name ="John"# A string

There are three numeric data types -integer,float and complex.

2.3 ARITHMETIC OPERATORS

Addition
Operator for Addition, +
Adds the operands on either side of the operator.
Example 1 Example 2
>>> a=21 >>> a=-21
>>> b=10 >>> b=10
>>> c=a+b>>> c=a+b
>>> c >>> c
31 -11

Subtraction
Operator for Subtraction, -
Subtracts the operand on the right from the operand on the left.
Example 1 Example 2
>>> a=21 >>> a=-21
>>> b=10 >>> b=10
>>> c=a-b >>> c=a-b
>>> c >>> c
11 -31

12
Multiplication
Operator for Multiplication, *
Multiplies values on either side of the operator.
Example 1 Example 2
>>> a=21 >>> a= -21
>>> b=10 >>> b=10
>>> c=a*b >>> c=a*b
>>> c >>> c
210 -210

Division
Operator for Division, /
Divides left hand operand by right hand operand.
Example 1 Example 2
>>> a=21 >>> a= -21
>>> b=10 >>> b=10
>>> c=a/b >>> c=a/b
>>> c >>> c
2.1 -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 Example 2
>>> a=21 >>> a= -21
>>> b=10 >>> b=10
>>> c=a%b>>> c=a%b
>>> c >>> c
1 9

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 Example 2
>>> a=4 >>> a=-4
>>> b=3 >>> b=3
>>> c=a**b >>> c=a**b
>>> c >>> c
64 -64

13
Floor division
Operator for Floor Division, //
Returns the quotient in which the digits after the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity).
Example 1 Example 2
>>> a=9 >>> a=-9
>>> b=5 >>> b=5
>>> c=a//b >>> c=a//b
>>> c >>> c
1 -2
Explanation: 9/5 = 1.8. So the floor division Explanation: -9/5 = -1.8. However, the floor
result removes the 8 and division rounds this away from 0
returns 1 and makes it -2

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

Multiplication
The multiplication of two complex numbers is very similar to multiplication of two
binomials.

Division
The division of two complex numbers involves multiplying both sides by
the conjugate of the denominator, which is a number with the same real part and the
opposite imaginary part.

2.5 Formatting Strings using Escape Sequences

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

14
Displayed here are a few common escape sequences available in python

Escape Description
\n Breaks the string into a new line.

\t Adds horizontal tab.

\\ Prints backslash.

\' Prints a single quote.

\" Prints a double quote.

\a Makes a sound like a bell.

2.6 String Operators

You can use certain operators for string processing.


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

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

[] Slice
[] Gives the character at given index.

[:] 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.

in Membership
[in] Returns true if a character exists in the given string.

not in Membership
[not in] Returns true if a character does not exist in the given string.

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

15
The string itself contains placeholders {} in which values of variables are
successively inserted

>>> name="Malhar"
>>> age=23>>>
percentage=55.5
>>> "my name is {} and my age is {} years".format(name, age)
'my name is Malhar and my age is 23 years'
>>>

Methods for String Processing

capitalize()

capitalize(): This method converts the first character of a string to uppercase letter.

>>>var='internshala'
>>>var.capitalize()
'Internshala'
>>>

lower()

lower(): This method results in a string with uppercase characters replaced by


corresponding lowercase characters.

>>>var='INTERNSHALA'
>>>var.lower()
'internshala'
>>>

upper()

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


corresponding uppercase characters.

>>>var='internshala'
>>>var.upper()
'INTERNSHALA'
>>>

title()

16
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 method returns -1.

>>>var='python training from internshala'


>>>var.find('in')10
>>>var.find('on')4
>>>var.find('run')-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()

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

isdigit()

isdigit(): This method returns true if all characters in a string are digits( 0-9), if not
returns false.

>>>var='2000'
>>>var.isdigit()
True
>>>var='2,000'
>>>var.isdigit()
False
>>>

islower()

islower(): This method returns true if all characters in a string are lowercase
characters else returns false.

>>>var='internshala'
>>>var.islower()
True
>>>var='Internshala'
>>>var.islower()
False
>>>var='intern shala'
>>>var.islower()
True
>>>

isupper()

isupper(): This method returns true if all characters in a string are uppercase
characters else returns false.

18
>>>var='INTERN_SHALA'
>>>var.isupper()
True
>>>var='INTERNshala'
>>>var.isupper()
False
>>>var='INTERN+SHALA'
>>>var.isupper()
True
>>>var='1234'
>>>var.isupper()
False
>>>

2.5 Set Data type

Set is also a collection data type in Python. However, it is not an ordered collection of
objects, like list or tuple. Hence, indexing and slicing operations cannot be done on a set
object. A set also doesn’t allow duplicate objects to be stored, where as in list and tuple, the
same object can appear more than once. Even if an object is put more than once in a set, only
one copy is held. Set is a Python implementation of a set as defined in Mathematics. The set
object has suitable methods to perform mathematical set operations like union, intersection,
difference etc. A set object contains one or more items, not necessarily of the same type
which are separated by comma and enclosed in curly brackets {}.

set() function
Python has an in-built function set() using which set objects can be constructed out of any
sequence like string, list or tuple object.

Order of elements in the set is not necessarily the same that is given at the time of
assignment. Python optimizes the structure for performing operations over set as defined in
mathematics. Only immutable (and hashable) objects can be a part of set object. Numbers
(integer, float as well as complex), strings, and tuple objects are accepted but list and
dictionary objects are not.

add()
adds a new element in set object.

update()
adds multiple items from a list or tuple.

clear()
Removes contents of set object results in an empty set.

copy()
Creates a copy of set object.

discard()

19
Returns set after removing an item from it. No changes are done if the item is not
present.

remove()
Returns set after removing an item from it. Results in error if the item is not present.

Set Operations
As mentioned earlier, set data type in Python implements set as defined in mathematics.
Various Set operations can be performed using Python’s set object. The operators |, &, - and
^ perform union, intersection, difference and symmetric difference operations respectively.
Each of these operators have a corresponding method associated with built-in set class

Union
Union of two sets is a set of all elements in both.

Intersection
Intersection of two sets is a set containing elements common to both.

Difference
Difference of two sets results in a set containing elements only in first but not in second set.

Symmetric Difference
Result of Symmetric difference is a set consisting of elements in both sets excluding common
elements

Set is a specialized data type. One of the major applications of Python is in area of
mathematical computing and data analysis in which set operations are important.

2.7 LISTS AND TUPLES

+ Concatenation
Appends the second list or tuple to the first.

The data types being concatenated should be of the same type. For example, you cannot
concatenate a list and a tuple.

+ Repetition
Concatenates multiple copies of the same list or tuple.

[] Slice
Returns the item at a given index in a list or tuple.
A negative index counts the position from right with the count starting at -1.
Note: Recall that the index starts at 0.

[:] Range Slice


Fetches items in a range specified by the two index operands separated by the colon [:]
symbol.
If the first operand is omitted, the range starts at zero index.If the second operand is omitted,
range goes upto the end of the list or tuple.

20
in Membership
Returns true if an object exists in the given list or tuple.
Note: If the list or tuple comprises string items, then the items are case sensitive

not in Membership
Returns true if an object does not exist in the given list or tuple.

Manipulating Lists

You can modify the items within a list. Modifying a list means to change an item, or add a
new item, or remove an existing item. Here are some methods of the built-in List class that
helps in modifying lists. Read through each function and then try it out in IDLE.

append()
Adds an item at the end of the list.
>>> L2=['Tailor Swift', 'Ed Sheeran', 'Imagine Dragons', 'Pink', 'Maroon 5']
>>> L2.append('Halsey')
>>> L2
['Tailor Swift', 'Ed Sheeran', 'Imagine Dragons', 'Pink', 'Maroon 5', 'Halsey']
>>>

insert()
Inserts an item in list at the specified index.
>>> L2=['Tailor Swift', 'Ed Sheeran', 'Imagine Dragons', 'Pink', 'Maroon 5']
>>> L2.insert(2, 'Halsey')
>>> L2
['Tailor Swift', 'Ed Sheeran', 'Halsey', Imagine Dragons', 'Pink', 'Maroon 5']
>>>

remove()
Removes the specified item from the list.
>>> L2=['Python', 'Perl', 'Java', 'C++'
>>> L2.remove('Java')
>>> L2
['Python', 'Perl', 'C++']
>>>

pop()
Removes and returns the last object in the list.
>>> L2=['Python', 'Perl', 'Java', 'C++'
>>> L2.pop()'C++'
>>> L2
['Python', 'Perl', 'Java']
>>>

reverse()
Reverses the order of items in a list.
>>> L2=['Python', 'Perl', 'Java', 'C++'

21
>>> L2.reverse()
>>> L2
['C++', 'Java', 'Perl', 'Python']
>>>

sort()
Rearranges items in the list according to alphabetical order. Default is ascending
order. For descending order put reverse=True as argument in function bracket.
>>> L2=['Python', 'C++', 'Java', 'Ruby'>>> L2.sort()
>>> L2
['C++', 'Java', 'Python', 'Ruby']
>>>
>>> L2.sort(reverse=True)
>>> L2
['Ruby', 'Python', 'Java', 'C++']
>>>

Converting One Sequence Type to Another

The Following utility functions help in converting one sequence data type to other.

list()

Converts a tuple or string to a list.>>> t2=('python', 'java', 'c++')


>>> list(t2)
['python', 'java', 'c++']
>>> s1="Internshala"
>>> list(s1)
['I', 'n', 't', 'e', 'r', 'n', 's', 'h', 'a', 'l', 'a']
>>>

tuple()
Converts a list or string to a tuple.
>>> L2=['C++', 'Java', 'Python', 'Ruby']
>>> tuple(L2)
('C++', 'Java', 'Python', 'Ruby')
>>> s1="Internshala"
>>> tuple(s1)
('I', 'n', 't', 'e', 'r', 'n', 's', 'h', 'a', 'l', 'a')
>>>

Other Methods Of Dictionary Objects

items()
This method returns a list of tuples, with each tuple containing one key and and the
corresponding value.

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

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

3. BASICS OF PROGRAMMING IN PYTHON

3.1 LOOPS

A loop statement allows us to execute a statement or group of statements multiple times. The following diagr

Python programming language provides the following types of loops to handle looping
requirements.

Sr.No Loop Type & Description

1 while loopRepeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

2 for loop

23
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 nested loops

You can use one or more loop inside any another while, for or do..while loop

3.2 Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

Sr.No. Control Statement & Description

1 break statement

Terminates the loop statement and transfers execution to the statement


immediately following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.

3 pass statement

The pass statement in Python is used when a statement is required syntactically


but you do not want any command or code to execute

24
3.3 FUNCTION

A function is a block of organized, reusable code that is used to perform a single, related
action. Functions provide better modularity for your application and a high degree of code
reusing. Python gives you many built-in functions like print(), etc. but you can also create
your own functions. These functions are called user-defined functions.

Defining a Function
Simple rules to define a function in Python.

● Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

● Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.

● The first statement of a function can be an optional statement - the documentation


string of the function or docstring.

● The code block within every function starts with a colon (:) and is indented.

● The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as return
None.

deffunctionname( parameters ):
"function_docstring"
function_suite
return[expression]

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and

# Function definition is here


defprintme(str):

25
"This prints a passed string into this function"
printstr
return;
# Now you can call printme function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result

I'm first call to user defined function!


Again second call to the same function

Function Arguments
You can call a function by using the following types of formal arguments:

● Required arguments

● Keyword arguments

● Default arguments

● Variable-length arguments

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. T

Global variables Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas

total =0;# This is global variable.

26
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2;# Here total is local variable.
print"Inside the function local total : ", total
return total;
sum(10,20);
print"Outside the function global total : ", total

Result

Inside the functionlocal total :30


Outside the functionglobal total :0

Prominent built-in methods in Python

__builtin__
This module contains built-in functions which are automatically available in all
Python modules. You usually don’t have to import this module; it is loaded
automatically when the interpreter starts.

exceptions
This module provides the standard exception hierarchy. It is automatically imported
when Python starts.
An exception is an even that occurs during the execution of a program and disrupts
the normal flow of the program's instructions. An exception is a Python object that
represents an error.

os
This module provides a unified interface to a number of operating system functions.
string
This module contains a number of functions for string processing.

re
This module provides a set of powerful regular expression facilities. A Regular
Expression (RegEx) allows powerful string search and matching for a pattern in a
string.

math
This module implements a number of mathematical operations for floating point
numbers. These functions are generally thin wrappers around the platform C library
functions.

cmath

27
This module contains a number of mathematical operations for complex numbers.

sys
This module provides functions and variables used to manipulate different parts of the
Python runtime environment.

time
This module provides functions to deal with dates and the time within a day. It wraps
the C runtime library.

gc
This module provides an interface to the built-in garbage collector

4. PRINCIPLES OF OBJECT ORIENTED PROGRAMMING

Python has been an object-oriented language since it existed. Because of this, creating and
using classes and objects are downright easy. This chapter helps you become an expert in
using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you
may want to consult an introductory course on it or at least a tutorial of some sort so that you
have a grasp of the basic concepts.

4.1 Overview of OOP Terminology

Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.

Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used as
frequently as instance variables are.

Data member: A class variable or instance variable that holds data associated with a class
and its objects.

Function overloading: The assignment of more than one behavior to a particular function.
The operation performed varies by the types of objects or argument

Instance variable: A variable that is defined inside a method and belongs only to the current
instance of a class.

Inheritance: The transfer of the characteristics of a class to other classes that are derived
from it.

Instance: An individual object of a certain class. An object obj that belongs to a class Circle,
for example, is an instance of the class Circle.

Instantiation: The creation of an instance of a class.

Method : A special kind of function that is defined in a class definition.

28
Object: A unique instance of a data structure that's defined by its class. An object comprises
both data members (class variables and instance variables) and methods.

Operator overloading: The assignment of more than one function to a particular operator.

Creating Classes

The class statement creates a new class definition. The name of the class immediately
follows the keyword class

classClassName:
'Optional class documentation string'
class_suite

● The class has a documentation string, which can be accessed


via ClassName.__doc__.

● The class_suite consists of all the component statements defining class members,
data attributes and function.

Class Inheritance

Instead of starting from scratch, you can create a class by deriving it from a preexisting class
by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if
they were defined in the child class. A child class can also override data members and
methods from the parent.

Syntax
Derived classes are declared much like their parent class; however, a list of base classes to inherit from is giv

classSubClassName(ParentClass1[,ParentClass2,...]):
'Optional class documentation string'
class_suite

Overriding Methods
You can always override your parent class methods. One reason for overriding parent's
methods is because you may want special or different functionality in your
subclass.Example

classParent:# define parent class


defmyMethod(self):

29
print'Calling parent method'
classChild(Parent):# define child class
defmyMethod(self):
print'Calling child method'

c =Child()# instance of child


c.myMethod()# child calls overridden method

When the above code is executed, it produces the following result

Calling child method

5. CONNECTING TO SQLITE DATABASES

SQL

SQL is a standard language for accessing and manipulating databases.

● SQL stands for Structured Query Language


● SQL lets you access and manipulate databases
● SQL became a standard of the American National Standards Institute (ANSI) in 1986,
and of the International Organization for Standardization (ISO) in 1987

SQL USES
● SQL can execute queries against a database
● SQL can retrieve data from a database
● SQL can insert records in a database
● SQL can update records in a database
● SQL can delete records from a database
● SQL can create new databases
● SQL can create new tables in a database
● SQL can create stored procedures in a database
● SQL can create views in a database
● SQL can set permissions on tables, procedures, and views

Using SQL in Your Web Site

To build a website that shows data from a database, you will need:

● An RDBMS database program (i.e. MS Access, SQL Server, MySQL)


● To use a server-side scripting language, like PHP or ASP
● To use SQL to get the data you want

30
● To use HTML / CSS to style the page

RDBMS

RDBMS stands for Relational Database Management System.

RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server,
IBM DB2, Oracle, MySQL, and Microsoft Access. The data in RDBMS is stored in database
objects called tables. A table is a collection of related data entries and it consists of columns
and rows.

CREATE SQL DATABASE


The SQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL database.

Syntax:
CREATE DATABASE databasename;

CREATE SQL TABLE

The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a database.

Syntax:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype
....
);

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer,
date, etc.).

COMMAND LINE SHELL FOR SQLite

The SQLite project provides a simple command-line utility named sqlite3 (orsqlite3.exe on
Windows) that allows the user to manually enter and execute SQL statements against an
SQLite database.

31
To start the sqlite3 program, simply type "sqlite3" at the command prompt. The "sqlite3"
command may be optionally followed by the name of 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 along-running SQL
statement.

Make sure you type a semicolon at the end of each SQL command! The sqlite3 program
looks for a semicolon to know when your SQL command is complete. If you omit the
semicolon, sqlite3 will give you a continuation prompt and wait for you to enter more text to
be added to the current SQL command. This feature allows you to enter SQL commands that
span multiple lines.

sqlite> CREATE TABLE tbl2 (

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

...> f2 text,

...> f3 real

...> );

sqlite>

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, we don’t have to define a specific data type for a
column when you create a table. Even if we have a column with the integer data type for
example, we 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.

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

A storage class is more general than a datatype. These storage classes are mapped to standard
SQL data types. For example, INTEGER in SQLite has a type affinity with all integer types
such as int, smallint, bigint, tinyint etc. Similarly REAL in SQLite has a type affinity with
float and double data type. Standard SQL data types such as varchar, char, nchar etc. are
equivalent to TEXT in SQLite.

The following methods are defined in the connection class :

cursor()

Returns a Cursor object which uses this Connection.

commit()

Explicitly commits any pending transactions to the database.

rollback()

Causes a transaction to be rolled back to the starting point. This method is optional since not
all databases provide transaction support.

close()

Closes the connection to the database permanently. Attempts to use the connection after
calling this will raise a DB-API Error.

Inserting a new Record

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:

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

Error handling in Python

In Python, there are (at least) two distinguishable kinds of errors: syntax errors and
exceptions. Syntax errors, also known as parsing errors, are errors in the programming
syntax. In the following example, the quotation mark is missing at the end of the string, hello
world. This is a syntax error.

Example 1

>>> print("Hello World)

SyntaxError: EOL while scanning string literal


>>>

Example 2

34
Even if a statement or expression is syntactically correct, it may cause an error when an
attempt is made to execute it. Errors detected during execution are called exceptions. In the
following example, division by zero is an exception.

>>> 10 * (1/0)Traceback (most recent call last):


File "<pyshell#0>", line 1, in <module>
10 * (1/0)
ZeroDivisionError: division by zero
>>>

Error handling in Python is done through the use of exceptions that are caught in try blocks
and handled in except blocks.The following code not only accepts a user input and adds a
new record but also displays a message if the operation was successful or not.

import sqlite3
MySchool=sqlite3.connect('schooltest.db')
mysid= int(input("Enter ID: "))
myname=input("Enter name: ")
myhouse=int(input("Enter house: "))
mymarks=float(input("Enter marks: "))
#try block to catch exceptionstry:
curschool=MySchool.cursor()
curschool.execute("INSERT INTO student (StudentID, name, house, marks)
VALUES (?,?,?,?)", (mysid, myname, myhouse, mymarks))
MySchool.commit()
print ("One record added successfully.")
#except block to handle exceptions except:
print ("Error in operation.")
MySchool.rollback()

MySchool.close()

The connection class defines the commit() and rollback() methods. Changes in database are
finalised only if the execute() method runs successfully by commit() method. Otherwise, any
changes are undone by the rollback() method. You can try this yourself by saving this code as
a .py file and executing it.

Try and Except

The try statement works as follows.

● First, the try clause (the statement(s) between the try and except keywords) is
executed.
● If no exception occurs, the except clause is skipped and execution of the try statement
is finished
● If an exception occurs during execution of the try clause, the rest of the clause is
skipped. Then the except clause is executed, and then execution continues after the try

35
statement.
● If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer try statements; if no handler is found, it is an unhandled
exception and execution stops with a message.

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)

Updating a Record - Example

36
import sqlite3
MySchool=sqlite3.connect('schooltest.db')

nm=input("enter name: ")


sql="SELECT * from student WHERE name='"+nm+"';"
curschool=MySchool.cursor()
curschool.execute(sql)
record=curschool.fetchone()print (record)
m=float(input("enter new marks: "))
sql="UPDATE student SET marks='"+str(m)+"' WHERE name='"+nm+"';"try:
curschool.execute(sql)
MySchool.commit()
print ("record updated successfully")except:
print ("error in update operation")
MySchool.rollback()

6. DEVELOPING A GUI WITH PyQT

A GUI (graphical user interface) is a system of interactive visual components for computer
software. A GUI displays objects that convey information, and represent actions that can be
taken by the user. The objects change color, size, or visibility when the user interacts with
them.

GUI objects include icons, cursors, and buttons. These graphical elements are sometimes
enhanced with sounds, or visual effects like transparency and drop shadows.

QForm Layout

QForm Layout is a convenient way to create a form with two columns and multiple rows.

37
Each row consists of an input field associated with a label. As a convention, the left column
contains the label while the right column contains an input field. The QFormLayout class has
a setWidget() method. Its usage is:

QFormLayout.setWidget(rownum, role, widget)

The role parameter has two possible values, LabelRole and FieldRole. We shall now design a
student information form in the Form Layout. The broad process we will follow is:

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

1. Start Qt Designer.
2. Create a new form using the template, Widget.
3. Use the Layout option, Form layout which will automatically arrange our widgets.
Let's look at the steps.

38
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 Reset and Submit buttons)

39
Step 3

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

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

41
Step 5

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


Layout - lay out in form layout.

42
You can customize the labels and buttons captions before saving the ui file and generating the

43
py file.

Final Output

44
7. 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 a 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 the 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 ‘Demanding
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 the 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.

45
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 decisions (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 a 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.

46
● 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 the 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

47
integrated with Maya, PaintShop pro, etc.

Python as a Rapid Development Tool


Although Python is becoming increasingly popular, the software development field is still
dominated by Java and Dot net platform. However, Java and C# developers are also taking
help from the 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. Astropy library is a collection of
software packages written in the Python programming language and designed for use in
astronomy. The BioPython package contains functionality useful for computational biology
and bioinformatics.

More and more companies, be it start ups or established ones are using Python for one or
other purpose in their development activities.

48
CHAPTER 4

CONCLUSION

I believe the trial has shown conclusively that it is both possible and desirable to use Python
as the principal teaching language:
o It is Free (as in both cost and source code).
o It is trivial to install on a Windows PC allowing students to take their interest further. For
many the hurdle of installing a Pascal or C compiler on a Windows machine is either too
expensive or too complicated;
o It is a flexible tool that allows both the teaching of traditional procedural programming and
modern OOP; It can be used to teach a large number of transferable skills;
o It is a real-world programming language that can be and is used in academia and the
commercial world;
o It appears to be quicker to learn and, in combination with its many libraries, this offers the
possibility of more rapid student development allowing the course to be made more
challenging and varied;

49

You might also like