Summer Training Report On Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

University Institute of Engineering and

Technology
Kurukshetra University ,Kurukshetra
Haryana (136119)

Kurukshetra University ,Kurukshetra


Industrial Training Report – Programming with python

Submitted To: Submitted By:


Rahul Gupta Umakshi
B.Tech ECE-B
252001150

➢ Mode of training: Online


➢ Platform: Internshala Online Training
➢ Start Date: 23 August 2021
➢ End Date: 11 October 2021
➢ Duration: 6 weeks
➢ Number of Hours: 180 hours
➢ Marks Obtained: 100%
➢ Project : Build a fantasy Cricket Game
PREFACE

This training report reflects the 6 week summer training at Internshala.


The report has details of the practical experience and the academic knowledge that I have
gained from Internshala during this 6 week as a student and also it is also included details of
many projects that I have conduct and involved.
I have made this report on python. I have tried my best elucidate all the relevant details to be
included in the report. While in the beginning I have tried to give a general view about this
language.

Certificate of Training
Motivation
Being modular, dynamic, object oriented, portable, and extensible in C and C++, Python is
much in demand. Python is an open source language. It is this particular feature, apart from
code readability, that has led to its widespread acceptance in academia and industry. Also,
Python is the future of machine learning and artificial intelligence. It has extensive coding
tools like scientific python and numeric python which foster data analytics and statistics.
Acknowledgement

It is our proud privilege and duty to acknowledge the kind of help and guidance received
from several people in preparation of this report. It would not have been possible to prepare
this report in this form without their valuable help, cooperation and guidance.

I would like to express my gratitude towards my university as well as internshala for providing me the
golden opportunity to do this wonderful summer training which also helped me in doing a lot of
homework and learning. As a result, I came to know about so many new things, so, I am really
thankful to them. Moreover I would like to thank my friends who helped me a lot whenever I got
stuck in some problem related to my course. I am really thankful to have such good support of them
as they always have my back whenever I need.

Student Declaration

I Umakshi (252001150) hereby declare that work done by me on “Programming with


Python” duration of six weeks is a record of original work for the partial fulfillment of the
requirements for the award of degree, electronic and communication engineering.
About the industry

Internshala is an internship and online training platform, based in Gurgaon, India.[1][2] Founded by
Sarvesh Agarwal, an IIT Madras alumnus, in 2011, the website helps students find internships with
organizations in India. Internshala started as a blog with a mission to bring a culture of meaningful
internships in India. This is the world where you can discover your passion and turn it into your
career. A world where you graduate fully assured, confident, and prepared to stake a claim on your
place in the world. In 2011, the website became a part of NASSCOM 10K Startups.[9] In 2015,
Internshala was a finalist in People Matters TechHR 2015 Spotlight Awards under 'Futurism in
Recruitment' category. The website of internshala is www.internshala.org
Internshala Student Partner (ISP) is India’s largest campus ambassador program where college
students get a chance to become the face of Internshala. This program helps students learn, earn &
grow at the same time while developing essential marketing and communication skills. ISPs
participate in various exciting contests while experiencing professional growth by solving real-world
problems and brainstorming out-of-the-box ideas to promote Internshala within their campus.

About the 'Programming with Python' Training


The online training, Programming with Python, is a 6-week training program covering essential
concepts on the building blocks of Python, object-oriented programming, the use of SQLite database
and development of GUIs for Python applications. This training program has been created by
Internshala to make the process of learning enjoyable yet effective. You will learn through videos,
visual organizers and practice exercises. For a great hands-on learning experience, this training
program is packed with assignments, assessment tests, code challenges, quizzes, and exercises. At
the end of this training program, you will build a Fantasy Cricket application that will integrate all the
concepts you learn in the training. For doubt clearing, you can post your queries on the forum and
get answers within 24 hours. Displayed below is a detailed table of contents.
Table of Contents
1. Introduction to Python
Learn how to install Python, distinguish between important data types and use basic features of the
Python interpreter, IDLE.
1. Installation of Python
2. Using the Python Interpreter IDLE
3. Salient Features of Python
4. Basic Syntax of Python

2. Using Variables in Python Learn about numeric, string, sequence and dictionary data types and
relevant operations while practicing Python syntax.

1. Data Types and Variables


2. Numeric Data Types
3. String Data Type
4. Sequence Data Type
5. Dictionary Data Type

3. Basics of Programming in Python


Learn how to write programs using conditionals, loops, iterators and generators, functions and
modules and packages.
1. Understanding Programs and Programming
2. Using Conditionals
3. Using Loops
4. Using Functions
5. Using Functions from Built-in Modules
6. Constructing Modules and Packages

4. Principles of Object-oriented Programming (OOP)


Learn about the important features of Object-oriented Programming while using Classes and
Objects, two main aspects of the OOP paradigm.
1. Overview of OOP
2. Declaring Class and Creating Object
3. Understanding Inheritance
4. Using Magic Methods

5. Connecting to SQLite Database


Learn about relational databases while learning how to store and retrieve data from an SQLite
database through Python.

1. Introduction to SQL
2. Creating an SQLite database
3. Accessing SQLite Database through Python

6. Developing a GUI with PyQT


Learn how to install PyQt5 toolkit, Qt Designer and create a graphical user interface using common
widgets and menu systems.
1. GUI and Event driven programming
2. Qt Designer
3. Using Common Widgets
4. Geometry Management
5. Designing Menu Systems
Python
Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language. Its design philosophy emphasizes code readability, and its syntax allows
programmers to express concepts in fewer lines of code than would be possible in
languages such as C++ or Java. The language provides constructs intended to enable clear
programs on both a small and large scale.
Python supports multiple programming paradigms, including object-oriented, imperative
and functional programming or procedural styles. It features a dynamic type system and
automatic memory management and has a large and comprehensive standard library.
Python interpreters are available for installation on many operating systems, allowing
Python code execution on a wide variety of systems.

Scripting Language
A scripting or script language is a programming language that supports scripts, programs
written for a special run-time environment that automate the execution of tasks that could
alternatively be executed one-by-one by a human operator.

Scripting languages are often interpreted (rather than compiled). Primitives are usually the
elementary tasks or API calls, and the language allows them to be combined into more
complex programs. Environments that can be automated through scripting include
software applications, web pages within a web browser, the shells of operating systems
(OS), embedded systems, as well as numerous games.

A scripting language can be viewed as a domain-specific language for a particular


environment; in the case of scripting an application, this is also known as an
extension language. Scripting languages are also sometimes referred to as very high-
level programming languages, as they operate at a high level of abstraction, or as
control language.

History
Python was conceived in the late 1980s, and its implementation was started in December
1989 by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language
(itself inspired by SETL) capable of exception handling and interfacing with the Amoeba
operating system. Van Rossum is Python's principal author, and his continuing central role in
deciding the direction of Python is reflected in the title given to him by the Python
community, benevolent dictator for life (BDFL).
Installation of Python
You can install Python for any platform such as MS-DOS, OS2, Linux or Solaris from the python
website, https://www.python.org/download/other/

Now that you are on the download page, select which of the software builds you would
like to download. For the purposes of this article we will use the most up to date version
available (Python 3.4.1).

Once you have clicked on that, you will be taken to a page with a description of all the new
updates and features of 3.4.1, however, you can always read that while the download is in
process. Scroll to the bottom of the page till you find the “Download” section and click on
the link that says “download page.”

Now you will scroll all the way to the bottom of the page and find the “Windows x86
MSI installer.” If you want to download the 86-64 bit MSI, feel free to do so. We believe
that even if you have a 64-bit operating system installed on your computer, the 86-bit
MSI is preferable. We say this because it will still run well and sometimes, with the 64- bit
architectures, some of the compiled binaries and Python libraries don’t work well.
Installing Python
Once you have downloaded the Python MSI, simply navigate to the download location on your
computer, double clicking the file and pressing Run when the dialog box pops up.

If you are the only person who uses your computer, simply leave the “Install for all users”
option selected. If you have multiple accounts on your PC and don’t want to install it
across all accounts, select the “Install just for me” option then press “Next.”
If you want to change the install location, feel free to do so; however, it is best to leave it
as is and simply select next, Otherwise Scroll down in the window and find the “Add
Python.exe to Path” and click on the small red “x.” Choose the “Will be installed on local
hard drive” option then press “Next.”
Setup the Path Variable

Begin by opening the start menu and typing in “environment” and select the option called
“Edit the system environment variables.”
When the “System Properties” window appears, click on “Environment Variables…”
Once you have the “Environment Variables” window open, direct your focus to the bottom half. You
will notice that it controls all the “System Variables” rather than just this associated with your user.
Click on “New…” to create a new variable for Python

Simply enter a name for your Path and the code shown below. For the purposes of
this example we have installed Python 2.7.3, so we will call the path: “Python path.”
The string that you will need to enter is: “C:\Python27\;C:\Python27\Scripts;”
• To verify the installation, in the terminal type:$ Python3
• The Python prompt (>>>) will appear.
Using the python Interpreter IDLE

Now that we have successfully completed the installation process and added our

“Environment Variable,” you are ready to create your first basic Python script. Let’s begin by
opening Python’s GUI by pressing “Start” and typing “Python” and selecting the “IDLE
(Python GUI).”

 IDLE stands for Integrated DeveLopment Environment. It is an integrated development


environment for python which has been bundled with the default implementation of language. It
is a development tool & interactive shell. IDLE using Tkinter graphic library. It is used to execute
a single statement.

Once the GUI is open, we will begin by using the simplest directive possible. This is the
“print” directive which simply prints whatever you tell it to, into a new line. Start by typing a
print directive like the one shown in the image below or copy and paste this text then press
“Enter”: print (“Congratulations on executing your first print directive!”)
Python Code Execution
Python’s traditional runtime execution model: source code you type is translated to byte
code, which is then run by the Python Virtual Machine. Your code is automatically compiled,
but then it is interpreted.

Source code extension is .py

Byte code extension is .pyc (compiled python code)

SALIENT FEATURES OF PYTHON

ENHANCED READIABILITY

In Python, uniform indents are used to delimit blocks of statements instead of curly brackets like in C,
C++ and Java. This enhances readability.

DYNAMIC TYPING
In Python, a variable to be used in a program need not have prior declaration of its name and type.
You will earn details about variables in the next module.

INTERPRETED LANGUAGE

Python is an interpreter-based language. An interpreter executes one instruction at a time. 50 if


there is an error on line 7 of the code; it will execute instructions till line 6 and then stop. This is
unlike a compiler which will not execute any of the instructions even if there is a single error. Thus,
an interpreter is useful if you are new to programming because it allows: you to see partial output of
your code and identify the error location more easily.

EXTENSIBLE LANGUAGE

Python extension modules implement new built-in object types and can call C libraries and system
calls which Python doesn't have direct access to database.

Standard DB2API

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

GUI programming

Standard distribution of Python contains Tkinter GUl kit, which is an implementation of the popular
GUI library called Td/Tk. An attractive GUI can be constructed using Tkinter. Many other GUI libraries
like Qt, GTK, Wix Widgets etc. are also ported to Python.

EMBEDABBLE

Python can be integrated with other popular programming technologies such as C, C++, Java, ActiveX
and CORBRA.

Data Type
Data types determine whether an object can do something, or whether it just would not
make sense. Other programming languages often determine whether an operation makes
sense for an object by making sure the object can never be stored somewhere where the
operation will be performed on the object (this type system is called static typing). Python
does not do that. Instead it stores the type of an object with the object, and checks when
the operation is performed whether that operation makes sense for that object.
Python has many native data types. Here are the important ones:

Numeric Data Types


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), 00123 (octal number))
Note: In C and related programming languages such as Python, a hexadecimal number is
prefixed with 0x and an octal number is prefixed with 0 or 0 .
• 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 number:- A number with a real and imaginary component is represented as a+b j in
Python where a and b are floats and j= − 1
Examples:4+6j,-2.3+6.4j

SEQUENCE DATA TYPE


In Python, sequence is the ordered collection of similar or different data types. Sequences allow
storing multiple values in an organized and efficient fashion. There are several sequence types in
Python-
• String
• List
• Tuple

STRING
In python, strings are arrays of bytes representing Unicode characters. A string is a collection of one
or more characters put in single-quote, double quote or triple-quote. In python there is no character
data type, a character is a string of length one. It is representing by str class. Strings in Python can be
created using single quotes or double quotes or even triple quotes. E.g. an HTML document.
Lists
An ordered collection of one or more data items, not necessarily of same type, put in square
brackets.
Examples: [1,"Ravi",75.50, True]

Tuples
An ordered collection of one or more data items, not necessarily of 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)Sets are unordered bags of values.

Booleans: - are either True or False.

DICTIONARY

Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds: key- value
pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a
Dictionary is separated by a colon:, whereas each key is separated by a 'comma'.
Creating Dictionary: A dictionary can be created by placing a sequence of elements within curly {}
braces, separated by 'comma'. Value in the dictionary is of any data type and can be duplicated,
whereas keys can't be repeated and must be immutable. Dictionary can be created by built-in
function dict(). An empty dictionary can be created by placing it to curly braces {}.

Variable

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.

Ex: counter = 100 # an integer


Assignment miles = 1000.0 # A floating
Point name = "John" # A string

Operations performed on String

In Python, we create a string by putting quotes around text. For example, we could take our
otherwise useless

• "hello"+"world" "helloworld" # concatenation


• "hello"*3 "hellohellohello" # repetition

• "hello"[0] "h" # indexing

• "hello"[-1] "o" # (from end)


• "hello"[1:4] "ell" # slicing

• len("hello") 5 # size
• "hello" < "jello" 1 # comparison

• "e" in "hello" 1 # search

Python Operator
Arithmetic Operator

Operator
Meaning Example

+
Add two operands or unary plus x + y+2

- Subtract right operand from the left or unary minus x – y -2

* Multiply two operands x*y


/ Divide left operand by the right one (always results into x/y
float)

% Modulus - remainder of the division of left operand by the x % y (remainder of


right x/y)

// Floor division - division that results into whole number x // y


adjusted to the left in the number line

**
Exponent - left operand raised to the power of right x**y (x to the
power y)
Comparison Operator

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

>=
Greater than or equal to - True if left operand is greater than or equal x >= y
to the right

<= Less than or equal to - True if left operand is less than or equal to the +x <=
right y

Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses.

Accessing Values in Tuples:

To access values in tuple, use the square brackets for slicing along with the index or
indices to obtain value available at that index.

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string. In fact, tuples
respond to all of the general sequence operations we used on strings.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration


Built-in Tuple Functions
Python includes the following tuple functions −

SN Function with Description

1 cmp(tuple1, tuple2) Compares elements of both tuples.

2 len(tuple) Gives the total length of the tuple.

3 max(tuple) Returns item from the tuple with max value.

4 min(tuple) Returns item from the tuple with min value.

5 tuple(seq) Converts a list into tuple.

List
The list is a most versatile data type available in Python which can be written as a list of
comma- separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between
square brackets. For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1,
2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"];
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Basic List Operation
Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation


['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership


for x in [1, 2, 3]: print x, 123 Iteration

Built-in List Functions & Methods:

SN Function with Description

1 cmp(list1, list2) Compares elements of both lists.

2 len(list) Gives the total length of the list.


3 max(list) Returns item from the list with max value.

4 min(list) Returns item from the list with min value.

5 list(seq) Converts a tuple into list.

Python includes following list methods

SN Methods with Description

1 list.append(obj) Appends object obj to list

2 list.count(obj) Returns count of how many times obj occurs in list


3 list.extend(seq) Appends the contents of seq to list

4 list.index(obj) Returns the lowest index in list that obj appears

5 list.insert(index, obj) Inserts object obj into list at offset index

6 list.pop(obj=list[-1]) Removes and returns last object or obj from list

7 list.remove(obj) Removes object obj from list

8 list.reverse() Reverses objects of list in place

9 list.sort([func]) Sorts objects of list, use compare func if given

Understanding Programs and Programming


Converting Python scripts into executable programs- Windows py2exe is a Python extension which
converts Python scripts (.py) into Microsoft Windows executables (.exe). These executables can run
on a system without Python installed.

1. For each script file that needs to be converted into an executable, a setup script file needs to be
created. Assuming that test.py is to be converted into an executable, asetup .py file should be
created with the following lines of code.
2. Run this script from command-line,
3. Two directories will be created when you run your setup script, build and dist. The test.exe will be
stored in directory.
Loop definition
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement −

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

Loop Type Description

while loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing the
loop body.
for loop Executes a sequence of statements multiple times and
abbreviates the code that manages the loop variable.

nested loops You can use one or more loop inside any another while, for or
do…While loop.
Conditional Statements:
Decision making is anticipation of conditions occurring while execution of the program and specifying
actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to
execute if outcome is TRUE or FALSE otherwise.

Python programming language provides following types of decision making statements. Click
the following links to check their detail.

Statement Description

if statements An if statement consists of a Boolean expression followed


by one or more statements.

if...else statements An if statement can be followed by an optional else


statement, which executes when the Boolean expression
is FALSE.

nested if statements You can use one if or else if statement inside


another if or else if statement(s).
Syntax of If Statement

Syntax of If else statement

Nested If Else syntax


Function
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.
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.
Syntax:
Def functionname(parameters):
“function_docstring”
Function_suite
Return[expression]

Using Functions From Built- in Modules


OS
This module provides a unified interface to a number of Operating system functions.

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

Random
This module contains a number of functions for processing.

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

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.

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

Constructing Modules and packages

Example:
Create the following and save it as example.py
def operatorname(x, y):
return (x+y)

Now, in another Python file, call the add() function using the following:

import example
print(example.add (1,2))

- Modules have the name variable set to the module name.


- When a Python file is called as a script, the name is set to "_main ". This lets you create modules
that can also be executed as scripts using the following:

Def operatorname{add}(x, y):


Return $x+y
if _name _ = "
print (operatorname{add}(1,2))
Object Oriented Programming Language
Object-oriented programming (OOP) is a programming paradigm based on the concept of
"objects", which may contain data, in the form of fields, often known as attributes; and
code, in the form of procedures, often known as methods. A distinguishing feature of
objects is that an object's procedures can access and often modify the data fields of the
object with which they are associated (objects have a notion of "this" or "self").

In OO programming, computer programs are designed by making them out of objects that
interact with one another. There is significant diversity in object-oriented programming, but
most popular languages are class-based, meaning that objects are instances of classes, which
typically also determines their type.

Overview of OOP
➢ In Python, everything is an object - integers, strings, dictionaries, etc.
➢ Class objects are instantiated from user-defined classes; other objects are from language
defined types.
➢ OOP allows representation of real-life objects as software objects (e.g., a dictionary as an
object)

BASICS OF OBJECT ORIENTED PROGRAMING


➢ Object: A single software unit that combines attributes and methods
➢ Attribute: A "characteristic" of an object; like a variable associated with a kind of object
➢ Method: A "behavior" of an object; like a function associated with a kind of object
➢ Class: Classes are used to create user-defined data structures. Classes define functions called
methods, which identify the behaviors and actions that an object created from the class can
perform with its data.

DECLARING CLASS AND CREATING OBJECTS

CLASSES IN PYTHON
➢ Can be defined anywhere in the program
➢ All methods and instance variables are public, by default
➢ The language provides "limited support" for private identifiers (see section $9.6$ in the
documentation).

OBJECTS IN PYTHON

➢ Objects are the basic run-time entities in an object-oriented system.


➢ They may represent a person, a place, a bank account, a table of data or any item that the
program must handle.
➢ When a program is executed the objects interact by sending messages to one another.
➢ Objects have two components:
➢ Data (i.e., attributes)
➢ Behaviors (i.e., methods)

UNDERSTANDING INHERITANCE

➢ Inheritance is a powerful feature in object oriented programming.


➢ It refers to defining a new class with little or no modification to an existing class.
➢ The new class is called derived (or child) class and the one from which it inherits is called the
base (or parent) class.
➢ Derived class inherits features from the base class, adding new features to it.
➢ This results into re-usability of code.

The Syntax of Inherited class is

The Magic methods which are used in OOP

SQLite Studio
SQL is Structured Query Language. It is designed by Donald Chamberlin and R.F.Boyce. We use SQL to
issue commands to the database:
• Create data
• Retrieve data
• Insert data
• Delete data
Let's talk a little about data types that are used in SQLite databases. SQLite uses what is called,
dynamic type system. That means, the value stored in a column determines its data type and not the
column's data type. Also, you don't have to define a specific data type for a column when you create
a table. Even if you have a column with the integer data type for example, you can store any kind of
data types such as text and SQLite will not complain about this.
The ANSI Standard of SQL specifies the data types to be used by relational databases. SQLite
provides the following five data types which are referred to as storage classes:

A storage class is more general than a data type. 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 statement in SQL is classified into five categories:


➢ Data definition language
➢ Data retrieval
➢ Data manipulation language
➢ Transaction control
➢ Data control

Data definition language: - The SQL statements that are used to create modify and delete the data in
a database.
Example: - ALTER… (All statements beginning with ALTER), ANALYZE, CREATE…etc
Data retrieval: - Their purpose is to Querying and retrieving data from tables.
Example: - SELECT WHERE, ORDER, GROUP clauses along with SELECT
Manipulation language: - It is used to Insert, delete and update data in a table.
Example: - INSERT, DELETE, UPDATE
Transaction control: - It managing changes made by DML statements.
Example: - COMMIT, ROLLBACK
Data Control Statements: - It is used for user management.
Example: - GRANT CREATE TABLE TO INTERNSHALA
REVOKE CREATE TABLE FROM INTERNSHALA

Command Line Shell for SQLite

The SQLite project provides a simple command-line utility named sqlite3 (or sqlite3.exe on Windows)
that allows the user to manually enter and execute SQL statements against a SQLite database.
To start the sqlite3 program, simply type "sqlite3" at the command prompt. The
"sqlite3" command may be optionally followed by the name the file that holds the SQLite database. If
the file does not exist, a new database files with the given name will be created automatically. If no
database file is specified on the command-line, a temporary database is created, and then deleted
when the "sqlite3" program exits.
On start-up, the sqlite3 program will show a brief banner message then prompt you to enter SQL.
Type in SQL statements (terminated by a semicolon), press "Enter" and the SQL will be executed.
You can terminate the sqlite3 program by typing your system End-Of-File character (usually a
Control-D). Use the interrupt character (usually a Control-C) to stop a long-running SQL statement.
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. For example:
sqlite> CREATE TABLE tbl2 (
...> f1 varchar(30) primary key, .
...> f2 text,
...> f3 real
...> );
sqlite>

SQL COMMANDS

INSERT
The insert statement inserts a row into a table.

DELETE
Deletes a row in a table based on a selection criteria.

UPDATE
Allows the updating of a field with a where clause

Retrieving record-select
The select statement retrieves a group of records you can either retrieves all the records or a subset
of the records with a WHERE clause
Sorting with ORDER BY
You can add an ORDER BY clause to SELECT statements to get the results sorted in ascending or
descending order.

Creating an SQLite Database


In SQLite, sqlite3 command is sed to crete a new SQlite database. You do not need to have any
special privilege to create a database.
Syntax:

CREATE TABLE IN SQLITE

SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating
a basic table involves naming the table and defining its columns and each column's data type.
Syntax

CREATE TABLE is the keyword telling the database system to create a new table. The unique name or
identifier for the table follows the CREATE TABLE statement. Optionally, you can specify
database_name along with table_name.

SELECT QUERY FROM TABLE


SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in
the form of a result table. These result tables are, also called result sets.
Syntax:

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

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.
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.
Error handling in Python is done through the use of exceptions that are caught in try blocks and
handled in except blocks.

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 statement.
• If an exception occurs which does not match the exception named in 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.

.
GUI Programming
Most modern computer software employs a graphical user interface or GUI.

A GUI displays text as well as small images (called icons) that represent objects such as directories,
files of different types, command buttons, and drop-down menus

In addition to entering text at keyboard, the user of a GUI can select an icon with pointing device,
such as mouse, and move that icon around on the display
User-generated events (e.g., mouse clicks) trigger operations in program to respond by pulling in
inputs, processing them, and displaying results
- Event-driven software
- Event-driven programming

Qt Designer

PyQt is a GUI widgets toolkit. It is a Python interface for Qt, one of the most powerful, and popular
cross-platform GUI library.

PyQt API is a set of modules containing a large number of classes and functions. While QtCore
module contains non-GUI functionality for working with file and directory etc., QtGui module
contains all the graphical controls.

Installing the QT designer tool

For Windows:
1. Open command line window.
2. Run the command: pip3 install pyqt5-tools==5.9.0.1.2
3. Go to your Python installation folder (assuming it is C:\python36)
4. You will find a folder called Lib. You will find designer.exe file in it's sub-directories.
5. Go to the folder C:\Python36\Lib\site-packages\pyqt5-tools
6. You can find designer.exe in this folder. Run that file

Adding an Event Handler in a Python Script


Let's continue with the myui file from the previous section. (You can download this from the Helper
Text for the video.) Now, let's see how to add a user-defined function to the Python script and
connect it to the clicked signal of the OK button. Assume that we want to print the message ‘Valid
Password’ if the password field contains the text 'Internshala' otherwise print the message, ‘Invalid
Password’. Open the myui.py files in IDLE.
Now, add the following function inside the class, Ui_MainWindow
def chkPassword(self):
txt=self.lineEdit.text()
if txt=='Internshala':
print ('Valid password')
else:
print ('Invalid password')
In this function, line Edit refers to the name of the Password line edit field generated in Qt Designer.
Next, add the following statement inside the method, setupUi().
self.button1.clicked.connect(self.chkPassword)
Common Widgets

These are some common widgets that are used in Qt designer.

Major Classes in PyQT


Desigining Menu System

PyQt API is a large collection of classes and methods. These classes are defined in more than 20
modules.
- PyQt API contains more than 400 classes. The QObject class is at the top of class hierarchy. It is the
base class of all Qt objects. Additionally, QPaintDevice class is the base class for all objects that can
be painted.

QApplication class manages the main settings and control flow of a GUI application. It contains main
event loop inside which events generated by window elements and other sources are processed and
dispatched. It also handles system-wide and application-wide settings.
- QWidget class, derived from QObject and QPaintDevice classes is the base class for all user
interface objects. QDialog and QFrame classes are also derived from QWidget class. They have their
own sub-class system.

Application of python

Python supports cross platform operating systems which makes building applications with it all the
more convenient. Some of the globally known applications such as YouTube, Bit Torrent, Drop box,
etc. use python to achieve their functionality.
 1. Web Development
 2. Game Development
 3. Machine learning \& artificial intelligence
 4. Data science & data visualization
 5. Desktop GUI
 6. Web scrapping applications
 7. Business Applications
 8. Audio & video applications
 9. CAD applications
 10. Embedded applications
Project Work
I had built a Fantasy cricket game .In which there is a use the use of SQLite database and
development of GUIs for Python applications. There is the Sneak peak of it.
Result and discussion
I believe the trial has shown conclusively that it is both possible and desirable to use Python as the
principal teaching language:
• It is Free (as in both cost and source code).
• 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;
• 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;
• It is a real-world programming language that can be and is used in academia and the
commercial world;
• 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;
• And most importantly, its clean syntax offers increased understanding and enjoyment for
students.
Bibliography

1. Internshala:- www.internshala.org
2. Wikipedia:- www.wikipedia.com
3. Internshala Study Material.

You might also like