Internship Sample Report
Internship Sample Report
BELAGAVI
AN INTERNSHIP REPORT
ON
“ PROGRAMMING WITH PYTHON”
Submitted by
SNEHA (3GN17EC060)
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.
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.
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.
SNEHA
( 3GN17EC060)
2
CERTIFICATE
3
TABLE OF CONTENTS
CHAPTER 4 CONCLUSION 49
4
CHAPTER 1
COMPANY PROFILE
Founded in :2010
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.
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 Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
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.
● 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.
● 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.
● It provides very high-level dynamic data types and supports dynamic type checking.
9
● It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
10
Examples: 4+6j, -2.3+6.4j
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.
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.
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
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.
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.
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.
\\ Prints backslash.
+ Repetition
[*] Concatenates multiple copies of the same string.
[] Slice
[] Gives the character at given index.
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.
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'
>>>
capitalize()
capitalize(): This method converts the first character of a string to uppercase letter.
>>>var='internshala'
>>>var.capitalize()
'Internshala'
>>>
lower()
>>>var='INTERNSHALA'
>>>var.lower()
'internshala'
>>>
upper()
>>>var='internshala'
>>>var.upper()
'INTERNSHALA'
>>>
title()
16
title(): This method results in a string with the first character of each word converted
to uppercase.
find()
find(): This method finds the first occurrence of a substring in another string. If not
found, the 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.
count()
count(): This method returns the number of occurrences of a substring in given string.
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
>>>
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.
+ 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.
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++']
>>>
The Following utility functions help in converting one sequence data type to other.
list()
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')
>>>
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.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.
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
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
3 pass statement
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 code block within every function starts with a colon (:) and is indented.
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
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")
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
This means that local variables can be accessed only inside the function in which they are declared, whereas
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
__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
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.
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.
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_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
29
print'Calling parent method'
classChild(Parent):# define child class
defmyMethod(self):
print'Calling child method'
SQL
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
To build a website that shows data from a database, you will need:
30
● To use HTML / CSS to style the page
RDBMS
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.
Syntax:
CREATE DATABASE databasename;
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.).
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.
...> f2 text,
...> f3 real
...> );
sqlite>
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
32
INTEGER Whole numbers, either positive or negative.
REAL Real numbers with decimal values that use 8-byte floats.
BLOB Binary Large Object that can be used to store any kind of data. The
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.
cursor()
commit()
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.
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()
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
curschool.execute("INSERT INTO student (StudentID, name, house, marks)
VALUES (5,'Sherlock',32,50);")
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()
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
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.
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.
● 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.
The SELECT query forms a result set containing all records returned as a response to a
query. The execute() method uses a string representing the SELECT query statement. There
are two prominent methods as per DB-API standard. The below two methods are used:
fetchone()
This method fetches the next available record from the result set. It is a tuple consisting of
values of each column of the fetched record. The Following code snippet retrieves and prints
one record at a time till the result set is exhausted.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
curschool=MySchool.cursor()
curschool.execute(sql)while True:
record=curschool.fetchone()
if record==None:
break
print (record)
fetchall()
This method fetches all the remaining records in the form of a list of tuples. Each tuple
corresponds to one record and contains values of each column in the table. The following
code snippet fetches all records and prints them one at a time by using the 'for' statement.
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
sql="SELECT * from student;"
curschool=MySchool.cursor()
curschool.execute(sql)
result=curschool.fetchall()for record in result:
print (record)
36
import sqlite3
MySchool=sqlite3.connect('schooltest.db')
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:
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:
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
40
Step 4
41
Step 5
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
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.
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:
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.
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.
47
integrated with Maya, PaintShop pro, etc.
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