Python Learners Guide
Python Learners Guide
1
Table of Contents
Introduction and course overview............................................................................................................ 1
Introduction to programming and numeric system.............................................................................. 1
Bits and Bytes: Fundamental computer number systems..................................................................... 3
Binary Number Formats........................................................................................................................ 3
Number Base Conversion...................................................................................................................... 4
Setting up Python....................................................................................................................................12
Compilers installations:....................................................................................................................... 12
What is Python.................................................................................................................................... 12
Python 2 vs. Python 3..........................................................................................................................12
Java vs Python Program.......................................................................................................................13
Python History.........................................................................................................................................14
Why learn Python?.............................................................................................................................. 14
Where is Python used?........................................................................................................................14
Python Popular Frameworks and Libraries............................................................................................. 15
Python print() Function....................................................................................................................... 15
Web Fundamentals..................................................................................................................................... 18
HTML....................................................................................................................................................... 18
CSS...........................................................................................................................................................20
JavaScript................................................................................................................................................ 23
Responsive Web Design.......................................................................................................................... 26
Web Servers and HTTP............................................................................................................................ 39
Databases................................................................................................................................................41
Security and APIs.....................................................................................................................................43
Python Operators........................................................................................................................................ 52
Python Conditional Statements.............................................................................................................. 52
Python Loops...........................................................................................................................................52
Python Data Structures........................................................................................................................... 52
Python List...............................................................................................................................................52
Python Tuple........................................................................................................................................... 53
Python String...........................................................................................................................................53
Dictionaries................................................................................................................................................. 54
Python Sets............................................................................................................................................. 55
Python Functional Programming.............................................................................................................55
Python File I/O........................................................................................................................................ 56
Python Modules...................................................................................................................................... 56
Python Exceptions...................................................................................................................................56
1
Python CSV..............................................................................................................................................56
Python Sending Mail............................................................................................................................... 56
Python Oops Concepts............................................................................................................................ 57
Python Database Connections............................................................................................................ 58
Python If-else statements........................................................................................................................... 59
The if-else statement...............................................................................................................................61
The elif statement................................................................................................................................... 63
Python for loop........................................................................................................................................... 66
The range() Function............................................................................................................................... 67
Nested Loops...........................................................................................................................................69
Python Functions.................................................................................................................................... 70
Advantages of Functions in Python.........................................................................................................70
Calling a Function.................................................................................................................................... 71
The Anonymous Functions......................................................................................................................77
Python Arrays.............................................................................................................................................. 81
Array operations......................................................................................................................................81
Finding the length of an array............................................................................................................. 83
Array Concatenation............................................................................................................................83
Python String...........................................................................................................................................85
Creating String in Python.....................................................................................................................85
Strings indexing and splitting.............................................................................................................. 86
Reassigning Strings.............................................................................................................................. 90
Deleting the String...............................................................................................................................90
String Operators.................................................................................................................................. 91
Escape Sequence................................................................................................................................. 92
Python String Formatting Using % Operator....................................................................................... 96
Python String functions...........................................................................................................................96
File Handling in Python............................................................................................................................. 101
Working of open() function...................................................................................................................101
Working of read() mode........................................................................................................................102
Creating a file using write() mode......................................................................................................... 102
Working of append() mode................................................................................................................... 102
Using write along with the with() function........................................................................................... 103
split() using file handling....................................................................................................................... 103
Reading file attributes in Python...........................................................................................................104
Creating new Python directories...........................................................................................................104
Reading Python directory contents.......................................................................................................105
2
Removing files or directories in Python................................................................................................ 106
Performing file searches in Python....................................................................................................... 108
Processing binary files in Python...........................................................................................................109
Creating and extracting from Python archives...................................................................................... 110
Copying and moving files...................................................................................................................... 111
Python file handling best practices....................................................................................................... 111
Python GUI – tkinter..................................................................................................................................114
Tkinter Programming............................................................................................................................ 114
import Tkinter....................................................................................................................................... 114
Geometry Management.................................................................................................................... 117
To create a tkinter app:......................................................................................................................... 118
import tkinter........................................................................................................................................118
File Handling Using Python GUI............................................................................................................ 135
What is File Handling in Python?.......................................................................................................135
Code for the project:............................................................................................................................. 135
Define code working:-....................................................................................................................... 136
Python Regex.............................................................................................................................................140
Matching Characters............................................................................................................................. 140
Repeating Things............................................................................................................................... 140
Matching Versus Searching............................................................................................................... 142
Python List.................................................................................................................................................144
List indexing and splitting......................................................................................................................146
Updating List values.......................................................................................................................... 148
Adding elements to the list............................................................................................................... 150
Removing elements from the list...................................................................................................... 151
Python List Built-in functions................................................................................................................ 152
Python Set.............................................................................................................................................155
Creating a set.....................................................................................................................................155
Adding items to the set..................................................................................................................... 157
Python Set Operations.......................................................................................................................... 163
Union of two Sets.............................................................................................................................. 163
Python Built-in set methods..................................................................................................................172
Python Tuples............................................................................................................................................174
Creating a Tuple.................................................................................................................................... 174
Indexing............................................................................................................................................. 176
Negative Indexing..............................................................................................................................178
Tuple Methods.................................................................................................................................. 180
3
Python Dictionary......................................................................................................................................185
Adding dictionary values....................................................................................................................... 187
Deleting elements using del keyword................................................................................................... 189
Iterating Dictionary............................................................................................................................... 190
Built-in Dictionary functions..............................................................................................................193
Python NumPy Project.............................................................................................................................. 195
NumPy Project...................................................................................................................................195
What is NumPy..................................................................................................................................195
The need of NumPy...........................................................................................................................195
NumPy performs array-oriented computing..................................................................................... 196
Python with Databases............................................................................................................................. 197
SQLite databases................................................................................................................................... 197
import sqlite3.................................................................................................................................... 197
Module functions.............................................................................................................................. 200
Open a connection to an SQLite database........................................................................................ 200
Connection............................................................................................................................................ 201
interrupt()..........................................................................................................................................211
PrepareProtocol objects.................................................................................................................... 223
SQLite and Python types....................................................................................................................... 224
Default adapters and converters....................................................................................................... 225
How to write adaptable objects........................................................................................................ 228
How to create and use row factories.................................................................................................235
What is Django?.................................................................................................................................... 238
Django’s key features are:..................................................................................................................... 238
What is Flask?....................................................................................................................................... 239
Comparing the Differences Between Flask and Django?...................................................................240
Working with Flask................................................................................................................................ 241
Installation.........................................................................................................................................241
Virtual environments.........................................................................................................................242
Define and Access the Database....................................................................................................... 242
Connect to the Database...................................................................................................................243
Create the Tables...................................................................................................................................244
Register with the Application............................................................................................................ 245
Initialize the Database File.................................................................................................................246
Application Discovery Behavior.........................................................................................................247
Externally Visible Server.................................................................................................................... 247
Python | Introduction to Web development using Flask.......................................................................... 247
4
What is Flask?....................................................................................................................................... 247
Getting Started With Flask:............................................................................................................... 248
Routing:............................................................................................................................................. 248
Using Variables in Flask:........................................................................................................................ 249
Handling Static Files :............................................................................................................................ 252
Sessions in Flask:............................................................................................................................... 255
File-Uploading in Flask:..................................................................................................................... 256
Sending Form Data to the HTML File of Server:.................................................................................... 257
Python with Django...................................................................................................................................261
What is Django?................................................................................................................................ 261
Why Django? Key Advantages of Django...........................................................................................261
History of Django...............................................................................................................................262
Features of Django............................................................................................................................ 263
Characteristics of Django...................................................................................................................263
Django Architecture: MVC and MVT................................................................................................. 263
MVC Pattern:..................................................................................................................................... 264
Django MVC-MVT pattern................................................................................................................. 264
Components of Django......................................................................................................................265
Famous Companies Using Django..................................................................................................... 266
Disadvantages of using Django..........................................................................................................266
XML Processing in Python......................................................................................................................... 267
Python XML Parsing Modules............................................................................................................267
xml.etree.ElementTree Module:....................................................................................................... 267
Using parse() function:...................................................................................................................... 267
Using fromstring() function:.............................................................................................................. 268
Modifying XML files:..........................................................................................................................271
Adding to XML:.................................................................................................................................. 271
Deleting from XML:........................................................................................................................... 273
Using the parse() function:................................................................................................................274
Using parseString() Method:............................................................................................................. 275
Finding Elements of Interest:............................................................................................................ 275
AI based Real-time Projects.................................................................................................................. 277
Project 1 Tic-Tac-Toe Game Engine................................................................................................... 277
Project 2 A Chatbot........................................................................................................................... 277
Project 3 Physical Projects With Python on the Raspberry Pi........................................................... 277
Project 4 Deploy a Python (Django or Flask) web app with PostgreSQL in Azure............................. 277
5
6
Introduction and course overview
Introduction to programming and numeric system
Number System:
Firstly, let us know why we need to understand the Number System while we are learning a programming
language. The Number System, which we Humans follow, is the Decimal number system but the
computer understands in Binary number system. So again, there is a difference between how I saw the
number and how the computer sees it.
Example:
As a human, if I give 10 for me it is Ten but for the computer, it is two. So, it’s actually necessary to
understand the different types of number systems.
Basically, we use the decimal system and in the decimal number system, the pictures or figures or the
symbols are from 0 to 9 i.e. total of 10 symbols we have. As we already discussed the computer works on
zeros and ones. So, for computers, there are only two symbols and the binary number systems have only
two symbols i.e. 0 and 1.
In the decimal number system, once we have finished with the last symbol i.e. 9, after 9, we use the
combination of symbols (from 0 to 9). For example- 10, 11, 12, and so on. 10 is the combination of two
symbols i.e. 0 and 1 similarly 11 is the combination of 1 and 1.
So, the point that you need to understand is, once we finished with the symbols, then we can take the
combination of symbols and in the binary number system, the same methodology is also followed. To
denote the new number, we use the combinations of two symbols i.e. 1’s and 0’s. For example, to denote
2 in the binary system we will use the combination of 1 and 0 i.e. 10, don’t read it as ten, read it as one
zero. For more details, please have a look at the following which shows the numbers from 0 to 16 in the
Decimal, Binary, Hexadecimal, and Octal number system.
1
2
Bits and Bytes: Fundamental computer number systems
The Binary Number System
Most computer systems operate using binary logic. The computer represents value using two voltage
levels, usually 0V for logic 0 and either +3.3V or +5V for logic 1. These two voltage levels represent
exactly two different values and by convention, the values are zero and one. These two values
coincidentally, correspond to the two digits used by the binary number system. Since there is a
correspondence between the logic levels used by the computer and the two digits used in the binary
numbering system, it should come as no surprise that computers employ the binary system.
In the United States among other countries, every three decimal digits is separated with a comma to
make larger numbers easier to read. For example, 123,456,789 is much easier to read than 123456789.
We adopt a similar convention for binary numbers. In order to make binary numbers more readable, we
add a space every four digits starting from the least significant digit, on the left of the decimal point. For
example, the binary value 1010111110110010 will be written as 1010 1111 1011 0010.
● The rightmost sequence (0010) is in bit position zero, holding value 0. Bit zero is referred to as
the least significant bit, or lsb
● Each bit to the left is given the next successive bit number. bit 1, bit 2 and so on...
● The left-most bit (1010) is typically called the most significant bit, or msb, holding value 1.
We typically write binary numbers as a sequence of bits. There are defined boundaries for the different
sizes of a bit:
Bit 1 1
Nibble 4 0101
Double Word 32 0000 0000 0000 0000 0000 0000 0000 0101
In any number base, we may add as many leading zeroes without ever changing its value, but in the
binary number system, adding leading zeroes adjusts the bit to a desired size. For example, we can
represent the number 5 as a:
Bit 101;
Nibble 0101;
3
Double Word 0000 0000 0000 0000 0000 0000 0000 0101
Notes on Names
The Word
The boundary for a Word can be defined as either 16-bits or the size of the data bus for the processor.
Therefore, a Word and Double Word is not a fixed size but varies from system to system - depending on
the processor.
For the 8085 and 8086 microprocessors, a word is a group of 16 bits. We number the bits in a word
starting from bit zero (b0) through fifteen (b15) as follows:
Remember, b0 is the LSB and b15 is the msb and when referencing the other bits in a word use their bit
position number. Notice that a word contains exactly two bytes. b0-b7 form the low order
byte, b8-b15 form the high order byte. Naturally, a word may be further broken down into four nibbles.
Nibble zero is the low order nibble (b0-b4) and nibble three is the high order nibble (b12-b15) of the
word. The other two nibbles are "nibble one" and "nibble two".
With 16 bits, you can represent 2^16 or 65,536 different values. These could be the unsigned numeric
values in the range of 0 => 65,535, signed numeric values which include both positive and negative
values in the range of -32,768 => +32,767, or any other data type with no more than 65,536 values. The
three major uses for words are
A double word is exactly that, two words, so a double word quantity is 32 bits. Naturally, this double
word can be divided into a high order word and a low order word, four bytes, or eight nibbles.
digit 1 1 0 0 1 0 1 0
bit
b7 b6 b5 b4 b3 b2 b1 b0
number
4
base 2 2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
Now just like the decimal system, we multiply each digit by base 2 and its weighted position value, then
find the sum, like this:
1(2^6) 1(64) 64
0(2^5) 0(32) 0
0(2^4) 0(16) 0
1(2^3) 1(8) 8
0(2^2) 0(4) 0
1(2^1) 1(2) 2
0(2^0) 0(1) 0
=202
Decimal to Binary
There are two methods, division by 2 and subtraction by the weighted position value.
For this, we divide the decimal number by 2, if the remainder is 0 write down a 0. If the remainder is 1,
then write down a 1. This process is continued until the quotient is 0.
The remainders will represent the binary equivalent of the decimal number. The remainder values are
written from the least significant digit to the more significant digit. So each new remainder value is
written to the left of the previous.
2671 / 2 1335 1 1
1335 / 2 667 1 11
166 / 2 83 0 0 1111
83 / 2 41 1 10 1111
5
41 / 2 20 1 110 1111
20 / 2 10 0 0110 1111
10 / 2 5 0 0 0110 1111
Start with a weighted position value greater than the number. If the number is less than the weighted
value, write down a 0 and subtract 0. If the number is greater than the weighted value, write down
a 1 but subtract the weighted value instead. This process is continued until the result is 0.
When performing the subtraction method, the digits will represent the binary equivalent of the decimal
number from the most significant digit to the lesser significant digit. So each new digit is written to
the right of the previous.
6
Although this was once a popular number base, especially in the Digital Equipment Corporation PDP/8
and other old computer systems, it is rarely used today. The Octal system is based on the binary system
with a 3-bit boundary.
The Octal system uses base 8 which includes only the digits 0,1,2,3,4,5,6 and 7 (any other digit would
make the number an invalid octal number).
0 000
1 001
2 010
3 011
4 100
5 101
6 110
7 111
First, break the binary number into 3-bit sections from the LSB to the MSB then convert the 3-bit binary
number to its octal equivalent.
MSB LSB
Octal Digit 1 2 7 6 6 2
Convert the decimal number to its 3-bit binary equivalent, then combine the 3-bit sections.
7
Let's take the above octal number, 127662 and break it down:
Octal
3-bit
Digit
1 001
2 010
7 111
6 110
6 110
2 010
This yields the binary number 001010111110110010 or 0000 1010 1111 1011 0010 in our more readable
format.
To convert from Octal to Decimal, multiply the value in each position by its Octal weight and add each
value.
6(8^1) 6(8) 48
2(8^0) 2(1) 2
=44978
The typical method to convert from decimal to octal is repeated division by 8. For this method, divide the
decimal number by 8, and write the remainder on the side as the least significant digit. This process is
continued by dividing the quotient by 8 and writing the remainder until the quotient is 0. When
performing the division, the remainders which will represent the octal equivalent of the decimal number
are written beginning at the least significant digit (right) and each new digit is written to the next more
significant digit (the left) of the previous digit. Consider the number 44978.
8
44978 / 8 5622 2 2
5622 / 8 702 6 62
702 / 8 87 6 662
87 / 8 10 7 7662
10 / 8 1 2 27662
1/8 0 1 127662
A big problem with the binary system is verbosity. For example, eight binary digits are required to
represent the value 202 while the decimal version requires only three decimal digits. Especially with
large values, binary numbers become too unwieldy. The hexadecimal numbering system solves these
problems.
Hexadecimal numbers are very compact and it is easy to convert from hex to binary and binary to hex.
Since we'll often need to enter hexadecimal numbers into the computer system, we need a different
mechanism for representing hexadecimal numbers since you cannot enter a subscript to denote the radix
of the associated value.
The Hexadecimal system is based on the binary system using a Nibble or 4-bit boundary. In Assembly
Language programming, most assemblers require the first digit of a hexadecimal number to be 0, and we
place an H at the end of the number to denote the number base.
The hexadecimal number system uses base 16, which includes only the digits 0 through 9 and the
letters A, B, C, D, E, and F.
This table provides all the information you'll ever need to convert from one number base into any other
number base for the decimal values from 0 to 16.
9
08 08H 1000 10Q
Hexadecimal to Binary
3. Each binary value is written from the beginning of the MSB (left) to the LSB (right)
For example, to convert 0ABCDH into a binary value, simply convert each hexadecimal digit according to
the table above.
0 0000
A 1010
B 1011
C 1100
D 1101
Binary to Hexadecimal
For example, given the binary number 1011001010, the first step would be to add two zeros in
the MSB position so that it contains 12 bits. Then separate the binary value into groups of four bits, so
the revised binary value reads 0010 1100 1010. Then we look up the binary values in the table above and
substitute the appropriate hexadecimal digit:
0010 2
10
1100 C
1010 A
16^0 1
16^1 16
16^2 256
16^3 4096
To convert from Hex to Decimal, multiply the value in each position by its weighted value then add. Using
the table above and the previous example, 0AFB2H, we expect to obtain the decimal value 44978.
2(16^0) 2(1) 2
=44978
Decimal to Hex
To convert from decimal to hex is slightly more difficult. The typical method is repeated division by 16.
11
Setting up Python
Compilers installations:
Python Project | Python Programming Language
Python project provides basic and advanced concepts of Python. Our Python project is designed for
beginners and professionals.
Python is a simple, general purpose, high level, and object-oriented programming language.
Python is an interpreted scripting language also. Guido Van Rossum is known as the founder of Python
programming.
Our Python project includes all topics of Python Programming such as installation, control
statements, Strings, Lists, Tuples, Dictionary, Modules, Exceptions, Date and Time, File I/O, Programs, etc.
There are also given Python interview questions to help you better understand Python Programming.
What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports
Object Oriented programming approach to develop applications. It is simple and easy to learn and
provides lots of high-level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for
Application Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting
and rapid application development.
Python supports multiple programming pattern, including object-oriented, imperative, and functional or
procedural programming styles.
Python is not intended to work in a particular area, such as web programming. That is why it is known
as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10
to assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in
Python development, and edit-test-debug cycle is very fast.
1. Python 2 uses print as a statement and used as print "something" to print some string on the
console. On the other hand, Python 3 uses print as a function and used as print("something") to
print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string
representing the value, which is typed by the user. To convert it into the integer, we need to use
the int() function in Python. On the other hand, Python 3 uses input() function which
12
automatically interpreted the type of input entered by the user. However, we can cast this value
to any type by using primitive functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string type is
Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant of range()
function which returns a xrange object that works similar to Java iterator. The range() returns a
list for example the function range(0,3) contains 0, 1, 2.
Java Program
4. System.out.println("Hello World");
5. }
6. }
Python Program
print("Hello World")
Both programs will print the same result, but it takes only one statement without using a semicolon or
curly braces in Python.
There is no use of curly braces or semicolon in Python programming language. It is English-like language.
But Python uses the indentation to define a block of code. Indentation is nothing but adding whitespace
before the statement when it is needed. For example -
1. def func():
2. statement 1
3. statement 2
4. …………………
13
5. …………………
6. statement N
In the above example, the statements that are same level to right belong to the function. Generally, we
can use four whitespaces to define indentation.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python
programming language has taken from the ABC programming language or we can say that ABC is a
predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the popular BBC
comedy show of that time, "Monty Python's Flying Circus". So he decided to pick the name Python for
his newly created programming language.
Python has the vast community across the world and releases its version within the short period.
o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Extensible
o Integrated
o Embeddable
o Data Science
o Date Mining
14
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Speech Recognitions
Unlike the other programming languages, Python print() function is most unique and versatile function.
o objects - An object is nothing but a statement that to be printed. The * sign represents that there
can be multiple statements.
o sep - The sep parameter separates the print values. Default values is ' '.
15
o flush - The stream or file is forcibly flushed if it is true. By default, its value is false.
1. print("Welcome to javaTpoint.")
2.
3. a = 10
5. print("a =", a)
6.
7. b = a
Output:
Welcome to javaTpoint.
a = 10
a = 10 = b
As we can see in the above output, the multiple objects can be printed in the single print() statement.
We just need to use comma (,) to separate with each other.
1. a = 10
Output:
a =dddd10
a =010$$$$$
In the first print() statement, we use the sep and end arguments. The given object is printed just after
the sep values. The value of end parameter printed at the last of given object. As we can see that, the
second print() function printed the result after the three black lines.
Python provides the input() function which is used to take input from the user. Let's understand the
following example.
16
Example -
Output:
By default, the input() function takes the string input but what if we want to take other data types as an
input.
If we want to take input as an integer number, we need to typecast the input() function into an integer.
For example -
Example -
3.
4. print(a+b)
Output:
150
17
Web Fundamentals
● The browser and the server “talk” to each other using a relatively
simple protocol called HTTP, which stands for the Hyper Text Transfer Protocol.
● If we break down HTTP into its two components we get a little more detail:
o Hyper Text - The idea of hyper text is that it links you from one page to another (we
used to call the links (hyperlinks) but that has been shortened to just links. However,
the concept of Hyper Text is central to this course in that the specific text that is
transferred follows a standard called the Hyper Text Markup Language (HTML).
o Transfer Protocol - when two programs want to talk to each other both programs
have to “speak the same language.” A protocol is a very specific description of a
series of messages that two programs use to communicate.
● The web server sends the HTML to the browser over the internet and the
browser renders the HTML into the nicely formatted page that you see on your screen.
At the beginning of the World Wide Web there was only HTML, and web pages were a bit drab
compared to what we are used to seeing today. Now modern web pages rely on three technologies,
which will be the main focus of this book.
● HTML – Hyper Text Markup Language – HTML describes the content of the page, giving the
page some sctructure including common things like headings, and sections, and lists of
things.
● CSS – Cascading Style Sheets – CSS desribes the “look” of the page, the colors, the fonts,
the margins, etc.
● Javascript is used to change the behavior of the page. What happens when you click on a
button, or scroll a scrollbar, or hover over something with your mouse.
HTML
As we noted in the previous chapter, HTML is the language of the web for expressing content. But
before we dive into the specifics of HTML, let’s look at what we mean by a markup language in
general. A markup language is a language that annotates text so that the computer can manipulate
it for some purpose. Most markup languages are readable by humans and are designed to be
written with a plain text editor as rather than a fancy word processor like Microsoft Word.
This book is written using a markup language called restructuredText restructuredText is similar to
another very popular markup language called Markdown. Both of these languages are designed to
be easily readable by humans, and yet easily translate into our language of choice for this class,
HTML. Now you know about three markup languages:
● HTML
● Markdown
● restructuredText
The restructutedText markup for the content in this chapter so far looks like this:
As we noted in the previous chapter, HTML is the language of the web for expressing
content. But before we dive into the specifics of HTML, let's look at what we mean by
a markup language in general. A markup language is a language that **annotates**
18
text so that the computer can manipulate it for some purpose. Most markup languages
are readable by humans and are designed to be written with a plain text editor as
rather than a fancy word processor like Microsoft Word.
* HTML
* Markdown
* restructuredText
The restructutedText markup for the content in this chapter so far looks like this:
The annotations in the restructuredText are pretty unobtrusive, and actually add to the readability of
the plain text in most cases. For example the === below the title of this chapter indicate that it is, in
fact a title or heading. regular paragraphs require no extra annotation. To make something bold you
surround it by double asterisks. If you want to make a bullet list, you just start the line with an
asterisk.
Most documents have a reasonably limited set of elements including the following:
● Paragraphs
● Title
● Headings and subheadings and subsubheadings
● bullet lists
● numbered lists
● tables of data
● figures or images
● text that is bold, or italic
● page headers
● page footers
As we learn HTML it’s important to keep in mind that the job of html is to structure the document
and provide content. We’ll worry about making things look pretty until we get to CSS.
HTML uses a set of tags to annotate(mark up) the document. The tags all look like
this: < tagname > and they are balanced so that at the end of the content for that tag there
is </ tagname >. Notice that the closing tag contains a slash at the beginning to differentiate itself
from an opening tag.
An HTML document then just contains a series of these balanced tags. Let’s look at a small
document that looks like this:
My First Heading
19
1
<html>
2
<head>
3
<title>Test Page</title>
4
</head>
5
<body>
6
</body>
10
</html>
11
Activity: ActiveCode (html_1)
If you click the run button you will see the HTML in the example above in a special output
window that mimics your browser. Try changing the text of one of the paragraphs and click run
again. Try changing the h1 tag to h2 Don’t forget to change both the opening and closing tags. I
have indented the HTML for you so you can see the opening and closing tags more clearly. A
web browser does not care about indentation one bit, you can get rid of all of the indentation, or
put everything on one line and the page will still look the same.
Before we move on to talk more about specific HTML tags it’s useful to think about the page that
is produced and the structure of the page. You get a sense of the structure from the indentation I
have provided, but it’s useful to look at this from another perspective.
The html tag has two children, the head and the body. The head has one child, which is the title
tag. The html tag is the parent of the head tag. The body has three children, the h1 tag and two p
tags. You may also find it helpful to think of this as an outline, although you would have to rotate
the picture 90 degrees counter clockwise to get the orientation into outline form. We will see how
this tree structure of an html page is useful later on when we start to use CSS and Javascript.
20
CSS
CSS stands for Cascading Style Sheets. Style sheets define how to display your html code. This
was not always the case. In HTML 3 the designers of the language added tags like font and color.
This was great for companies like Microsoft where you could export your word doc as html, but
created a nightmare for developers of large sites that were not developed using WYSIWYG tools,
and it made the html completely unreadable. So, in HTML 4.0 CSS was introduced to fix the
problem we created for ourselves.
CSS defines how the html should look, and it does this using a set of rules. We are all used to
following certain rules in every day life: If it is raining, then take your umbrella. If the light is
red, then come to a stop at the stoplight. In html terms we might say, if the tag is an h1 then color it
blue and set the font size to 28 points.
CSS Syntax
To tell the computer about these if/then rules, we need a consistent syntax. The syntax for CSS
has two parts, a selector and a declaration.
selector {
declaration;
declaration;
}
The declaration itself consists of two parts: a property and a value. There are many many CSS
properties and we willl look at a lot of them, but for now, just think of the property as something
like color, font-size, font-family, etc.
Selectors can be as simple as a tag name, or a very complex pattern to match. We will start with
some very simple selectors and work our way up to the more complex.
Without further fuss, let’s look at a CSS rule for coloring h1 tags blue, and changing their font to
28 points.
h1 {
color: blue;
font-size: 28pt;
}
21
<html>
2
<head>
3
<style>
4
h1 {
5
color: blue;
6
font-size: 28pt;
7
}
8
</style>
9
</head>
10
<body>
11
<h1>Hello World!!</h1>
12
<h1>Hello Again</h1>
15
</body>
16
</html>
17
Activity: ActiveCode (css_rule_1)
There are several things to notice about the example above. First the h1 selector matches all of
the h1 tags in the document. But it does not match the h2 or the p tags. If you want to change the
style of the paragraph you need to add another rule. Let’s try it: Add a rule to the style tag that
22
colors the paragraph text green. Then make another rule that makes the h2 tag size 16pt and
yellow.
One thing to be careful about is to remember the semi-colons after the values. If you forget a
semi-colon, then your rule will not work.
Using a separate css file is the most preferred way to organize your CSS. This allows you to use
the same style in multiple web pages, and in a group setting makes it easy for one person to work
on the style while another focuses on the content. CSS stylesheets are included in a web page by
using the link tag in the head section of your page as follows:
Cascading
Since you can add style information about a tag in any or all of the three places, how is the style
resolved if different sources provide conflicting information?
Default rules from the browser are combined with rules from an external Style Sheet are
combined with the rules contained in any style tags in the page itself. If there is a conflict then
then internal style tag wins. These rules are then combined with any style information contained
in a style attribute. If the style attribute conflicts with any previous informatin, it wins.
JavaScript
Although we have been calling HTML and CSS programming languages, they do not have nearly
the power of Javascript. Once you learn Javascript you could can write any program that could be
written.
Javascript is a procedural language. With HTML and especially CSS the order of things is not
always important, but with Javascript, the order that you do things in is very important. Javascript is
also called an object oriented language. That means that we will be working with objects in our
imaginary world of the browser. Objects can tell us things we want to know, and objects know how
to do many things. We only need to write a javascript program to ask or tell.
But, let’s not get caught up in a bunch of formal talk about computer science and programming
language theory, let’s start with a simple example of one of the things that Javascript is good at
doing, namely making buttons do interesting things. For our first program let’s make a button that
changes the background color of our window.
Render
1
<html>
2
<body>
3
<h1>Hello World!!</h1>
4
23
<button onclick="changeThisPageFunc();">Click Me!</button>
5
<script type="text/javascript">
6
changeThisPageFunc = function() {
7
document.body.style.backgroundColor = "lightblue";
8
document.body.innerHTML = "<h1>I am a little blue today</h1>";
9
}
10
</script>
11
</body>
12
</html>
13
Now that example may look very complex to you, and in fact it does demonstrate LOTS of
important aspects of programming. But do not worry, we’ll dissect this example carefully so that
you fully understand what is going on.
Here are some questions that we should answer about the example above:
1. Button? We haven’t talked about a button tag before, whats the deal with that?
2. What is the onclick attribute for?
3. script tag? Again this is a new one why a script tag?
4. What in the world does all of that stuff inside the script tag mean?
5. What happened to my button!?!
Those are all very good questions, I’m glad you asked. Let’s take them one at a time right now, and
then we’ll expand upon the ideas in the next few sections.
The button tag is part of HTML that is going to allow us to make interactive websites. In addition to
buttons there are other things like check boxes, and text input, that we will talk about in the next
section. For now we will use the button as a simple example, of something we are all used to using
every day.
The onclick attribute is the way we answer the question, “what should this button do when
someone clicks on it.” The answer in this case is may lead to confusion, but hopefully you at least
get the idea that when the button is clicked we want to “change this page”. The way we are going to
do this is through a function call. You have used functions in math class many times, and these are
not all that different. The important thing to remember is that functions are abstractions of things
that need doing. We all use abstractions all the time in our everyday life.
For example, you may tell your friend, “I’m going to Computer Science now.” this is an abstraction
of the following hypothetical steps:
1. Get out of bed.
2. Get dressed
3. Walk out of your room, down the hall and wait for the elevator.
24
4. Take the elevator to the fourth floor.
5. Walk out of the elevator, out of the door, and across campus to Olin hall.
6. Go in the door, and up the stairs to second floor, enter room 202 and find your favorite place
to sit.
That would be a long boring conversation if you responded with all 6 of those steps every time a
friend asked you what you were doing. But your friend understands those steps are necessary when
you say you are going to class. Further more even step 1 is an abstraction of several smaller steps:
Sit up, remove the covers, slide my legs over the side of the bed, stand up (or climb down the
ladder).
This brings us to the next question, the script tag is one way that we can include Javascript in our
HTML. But like CSS we will see that we can, and should, also include Javascript by putting it in its
own file and including it. More on that later.
The stuff inside the script tag is Javascript code. This code contains a function definition which is
how we create our very own abstractions. Unlike your friend to naturally understands what it means
to go to class, computers are very dumb, and very literal, they only do what you tell them. In this
case there are two steps to our abstraction. One changes the background color of the body, and
the second one changes our message. These lines are also abstractions of a very complicated set
of steps that we as programmers don’t need to know the details of right now. We just need to know
which abstractions the browser understands.
Let’s defer the question of what happened to the button for just a bit. In the meantime experiment
with the Javascript code by trying the following things:
1. Make the background light green
2. Experiment with different style elements we have learned about through CSS. See if you can
add a line that makes the text red.
3. Can you change the fontSize to 48pt?
4. What does that tell you about document.body.style?
5. Change the wording inside the <h1> tag in the Javascript.
6. What happens if you add <button>Click Me</button> after the closing </h1>?
Let’s look at a little different example that accomplishes the same thing, but illustrates how CSS,
Javascript, and HTML all work together. In this example rather than setting the color of the
background directly, we will make the body have the class attribute “myclass” when the button is
clicked.
1
<html>
2
<head>
3
<style>
4
.myclass {
5
background-color: lightblue;
6
}
7
</style>
8
25
</head>
9
<body>
10
<h1>Hello World!!</h1>
11
12
<button onclick="changeThisPageFunc();">Click Me!</button>
13
<script type="text/javascript">
14
changeThisPageFunc = function() {
15
alert("body has class = "+document.body.className);
16
document.body.className = "myclass";
17
alert("body has class = "+document.body.className);
18
document.body.innerHTML = "<h1>I am a little blue today</h1>";
19
}
20
</script>
21
</body>
22
</html>
23
26
Figure used in accordance with w3schools fair use policy
The different parts of the box model are defined as follows:
● Content: The actual text or image content of an html tag
● Padding: The space between the content and the border.
● Border: This can be an actual drawn border or it can be invisible
● Margin: The space outside the border between this box and the boxes next to it in each
direction.
Let’s try a simple example:
<html>
2
<head>
3
<style>
4
section {
5
width: 250px;
6
background-color: green;
7
padding: 25px;
8
border: 10px solid blue;
9
margin: 25px;
10
}
11
</style>
12
27
</head>
13
<body>
14
15
<section>Hello World</section>
16
<section id=b>Hello World</section>
17
18
</body>
19
</html>
20
Activity: ActiveCode (css_boxmodel)
As a bit of review, add a rule to the example above to make the margin for the second Hello
world to be 5px. What does this tell you about how margins work?
The size of content area itself can also be controlled using the following properties:
● height
● max-height
● min-height
● width
● max-width
● min-width
Each of these properties can be specified in terms of pixels (px), points (pt), or as a percentage. In
addition the auto keyword can be used, which is the default and allows the browser to figure out
the proper height and width.
When you use height and width with a container element, such as one of the semantic elements,
it is very useful to know about the overflow property. What if you set your height so small that
the content does not fit? The overflow property tells you how to handle that.
Here is an example activecode for you to experiment with:
<html>
2
<head>
3
<style>
4
section {
5
width: 250px;
6
28
background-color: green;
7
padding: 25px;
8
border: 10px solid blue;
9
margin: 25px;
10
height: 100px;
11
}
12
</style>
13
</head>
14
<body>
15
16
<section>
17
<p>Ea dolore do irure aliquip id qui dolor do in aliquip irure anim id. Adipisicing qui
18
incididunt consectetur veniam cupidatat dolor. Aliquip irure labore elit ipsum officia non
19
culpa consequat et voluptate. Officia nisi nostrud exercitation quis amet ipsum incididunt.
20
Et incididunt eu laborum velit dolore laborum. Esse id mollit fugiat nostrud non ex occaecat
21
culpa. Adipisicing quis excepteur voluptate commodo minim aliqua excepteur occaecat
22
eu ipsum nisi duis amet. Duis proident fugiat velit elit esse cillum minim laborum elit.
23
</p>
24
Activity: ActiveCode (css_overflow)
The possible values for the overflow property are:
● visible
● hidden
● scroll
● auto
Give them a try in the example above and see what happens.
Greeking
29
You may be wondering about the use of latin words in the example paragraph. This is an old
tradition in typesetting, to use a bunch of latin words, many of the sentences start with “Lorum
Ipsum,” so sometimes it is called Lorum Ipusum as well. The idea is to fill the space with words
that obviously have no relationship to the actual webpage. This helps reviewers focus on the
style rather than the content. Why do they call it greeking when the words are latin? It’s Greek
to me. Obviously they skipped Paideia that day.
4.5.2. Display
With CSS you can take control of how each element is layed out on the page. You can hide
elements, you can make block elements inline, and inline elements block. There are two ways to
control the visibility of an element. You can completely hide it, as if it is not there and takes up no
space on the page, or you can have the leave the space on the page, but it will not have
anything in it.
<html>
2
<head>
3
<style>
4
h1.gone {
5
background-color: #bbbbbb;
6
display: none;
7
}
8
</style>
9
</head>
10
<body>
11
12
<h1>Hello World One</h1>
13
<h1 class="gone">Hello World Two</h1>
14
<h1>Hello World Three</h1>
15
<h1 class="gone">Hello World Four</h1>
16
<h1>Hello World Five</h1>
17
</body>
30
18
</html>
19
Activity: ActiveCode (css_disp1)
Now change the rule and instead of display: none change it to visibility: hidden Notice that
visibility hidden reserves space on the page for the element but does not show it. Whereas
the display: none rule removed any trace of the element. Now change the rule
to visibility: show to display all of the elements.
The display property can also be used to change block elements into inline elements. Consider
the following example.
<html>
2
<head>
3
<style>
4
</style>
5
</head>
6
<body>
7
<p>There are 10 kinds of people in the world.
8
<ol>
9
<li>Those that know how to count in binary.</li>
10
<li>Those that do not know how to count in binary</li>
11
</ol>
12
<p>When you have stopped laughing, add a CSS rule that changes the display
13
property for the ``li`` element and sets its value to ``inline``. </p>
14
</body>
15
</html>
16
Activity: ActiveCode (css_disp2)
This technique is often used in the navigation bar to create a “menu” of links. See exercise 5 in
the exercises section for some practice with this.
31
4.5.3. Floating
The CSS float property allows us to push HTML elements to the left or right, so that other
elements will wrap around them. This can be extremely useful for images, but will also be very
useful when we begin to work on more complex layouts for our pages. Let’s begin with a simple
example.
<html>
2
<head>
3
<style>
4
</style>
5
</head>
6
<body>
7
<p>the quick brown fox jumped over the lazy dog. the quick brown fox jumped over the lazy
dog. the quick brown fox jumped over the lazy dog. <img
src="http://interactivepython.org/runestone/static/webfundamentals/_images/norse-logo.png"
/> the quick brown fox jumped over the lazy dog. the quick brown fox jumped over the lazy dog.
the quick brown fox jumped over the lazy dog.
8
</body>
9
</html>
Notice that the logo appears right in the middle of the text in its normal inline flow. Now, add a
CSS rule for an img tag that sets the float property to left. Then change the rule to float the
image to the right.
Next let’s add a second copy of the norse logo to the page by copying and pasting the image
again.
Next, modify the html, and add a CSS rule so that one logo is floated to the left and the other is
floated to the right.
The float property can also be applied to block elements. This will cause the block elements to
behave more like inline elements.
The clear property is used to undo the effects of the float.
4.5.4. Positioning
There are several different ways to affect the positioning of html elements either inside or
outside of the normal flow of the layout.
● static
● fixed
● relative
● absolute
32
Static is the default positioning value for the css position property. The static value simply tells
the browser to position this element in the “normal flow” of the document.
Fixed positioning is measured against the frame of the browser window. Elements with a fixed
position value do not move even when the contents of the browser window are scrolled. The
navigation bar at the top of this page uses the fixed position value so it is always visible. Because
fixed elements are outside the flow of the document they can sometimes cause unexpected
results that you have to deal with carefully.
A relatively positioned element is measured relative to its normal position in the flow. Using a
relative position value lets you create elements that overlap each other.
An absolute element is positioned relative to the first parent element that has a position other
than static. If no such element is found, the containing block is the html tag for the entire
document. Absolutely positioned elements are positioned outside the normal flow of the
document.
4.5.4.1. Fixed
Let’s look at an example of how to use fixed positioning to create an element that stays put on
the screen.
Render
<html>
2
<head>
3
<style>
4
#sticky {
5
position: fixed;
6
top: 0px;
7
left: 5px
8
}
9
</style>
10
</head>
11
<body>
12
<nav id="sticky">
13
<p>There are 10 kinds of people in the world.</p>
14
</nav>
15
33
<ol>
16
<li>Those that know how to count in binary.</li>
17
<li>Those that do not know how to count in binary</li>
18
<li>Those that know how to count in binary.</li>
19
<li>Those that do not know how to count in binary</li>
20
<li>Those that know how to count in binary.</li>
21
<li>Those that do not know how to count in binary</li>
22
<li>Those that know how to count in binary.</li>
23
<li>Those that do not know how to count in binary</li>
24
<li>Those that know how to count in binary.</li>
Activity: 4.5.4.1.1 ActiveCode (css_pos1)
When you run the example above you will notice that it’s not quite right! The text is overlapping
and the page generally looks ugly. The elements overlap because the fixed positioning takes the
paragraph block element out of the flow. Because it’s out of the flow the browser renders
the ol as if it should be the first thing at the top of the page.
Your challenge is to fix the example so that the sentence stays nicely anchored to the top, but the
ordered list begins below it.
Relative
Next let’s look at the relative position and how we can use it to make overlapping elements.
Let’s make a stack of cards using the following image:
34
<html>
2
<head>
3
<style>
4
img.card {
5
height: 200px;
6
}
7
</style>
8
</head>
9
<body>
10
<img id="a" class="card"
src="http://interactivepython.org/runestone/static/webfundamentals/_images/ace-of-hearts.gi
f" />
11
35
<img id="b" class="card"
src="http://interactivepython.org/runestone/static/webfundamentals/_images/ace-of-hearts.gi
f" />
12
<img id="c" class="card"
src="http://interactivepython.org/runestone/static/webfundamentals/_images/ace-of-hearts.gi
f" />
13
</body>
14
</html>
15
Activity: 4.5.4.2.1 ActiveCode (css_pos2)
If you run the example you will see the three cards lined up next to each other. As a reminder this
is because:
1. images are inline elements and so do not create a line break.
2. The browser lays out inline images top to bottom and left to right.
Now let’s use our positioning skills to create a stack. Modify the example above to add the
following css rule:
img#b {
position: relative;
top: 20px;
left: -100px;
}
Great, now we have made the second card appear to be on top of the first. Notice that although
we have moved the second image, the position of the third image does not change. This is
because space is still reserved for the second image in its middle position, we are manually
moving it relative to where it would normally be in the flow. So a relative positioning works
within the flow of the document. Add a rule for the third image to add it to the stack.
Show
Coordinates
You have no doubt noticed that we are using top and left values to position our box. This box is
positioned within the window where the coordinate 0,0 is in the top left corner. The X or first
coordinate gets larger as you move to the right across the windo, and the second, or Y
coordinate grows larger is you move down the screen. This takes a little adjustment as it is
different from what you learned in math class.
Now, what about elements that come after relatively positioned elements? If you add a
paragraph after the images do you expect the text to be covered up or flowed beneath all of the
cards?
Another important thing to notice is that card 2 appears to be stacked on top of card 1, and card
three appears to be stacked on top of cards 1 and 2. This is becuase elements that come later in
the document naturally appear on top of elements that come before them.
If we want to change that and make it look like card 1 is on top of card 2 and card 2 is on top of
card 3 we can use the css z-index property to position the elements. elements that have a larger
36
z-index will appear to be on top of items with a lower z-index. By default, all elements have a
z-idex of zero. So to change the order of the stack we will need to modify the rules for images b
and c. Add a z-imaeg property to the img#b and img#c rules giving b a z-index of -1 and c a
z-index of -2.
Advanced Topic: Transformation
CSS Provides the ability for us to really get fancy and transform any element by rotating or
scaling. We can make our stack of cards look much more like a hand of cards by exploring
the transform property. In fact the transform property is still so new that it goes by different
names in different browsers. For Chrome, Safari you will want to use
the -webkit-transform property while in Firefox you can use transform. If you are Explorer you
will need to use -ms-transform. In fact to write your page to work anywhere you would specify
all three!
4.5.5. Absolute
Absolutely positioned elements are absolute, but relative to their container! The official rule is
that absolute items are positioned using the the upper left corner of the first non-static container
as the origin. If there is no non-static container, then the html tag will be used and the origin will
be the upper left corner of the page.
<html>
2
<head>
3
<style>
4
main {
5
position: relative;
6
}
7
img.card {
8
height: 200px;
9
}
10
img#a {
11
position: absolute;
12
top: 10px;
13
left: 50px;
14
}
37
15
img#b {
16
position: absolute;
17
top: 10px;
18
left: 50px;
19
}
20
</style>
21
</head>
22
<body>
23
<main>
24
<img id="a" class="card"
src="http://interactivepython.org/runestone/static/webfundamentals/_images/ace-of-hearts.gi
f" />
Activity: 4.5.5.1 ActiveCode (css_pos3)
OK, what happened to the second card? How can you make a stack that looks like the stack from
our relatively positioned element? What happens if you add an h1 in front of the main tag?
4.5.6. Full Page Layout
Render
<html>
2
<head>
3
<title>Home</title>
4
<style>
5
header {
6
position: fixed;
7
background-color: #bbbbbb;
8
top: 0px;
9
left: 0px;
38
10
width: 100%;
11
height: 20px;
12
}
13
nav {
14
margin-top: 20px;
15
margin-bottom: 0px;
16
background-color: green;
17
}
18
nav li {
19
display: inline;
20
}
21
section {
22
float: left;
23
width: 20%;
24
height: 500px;
Activity: ActiveCode (css_layout1)
This looks pretty good. It almost matches the picture in the aside area. This is a pretty typical
layout for a good quality page, and you can use this as a template for your own homepage.
However it is missing the article area, and there is an ugly black band between the nav and the
tops of the aside and section. See if you can do the following:
1. Remove the black band. Hint: A good way to find out why things look the way they do is
to use the “Inspect Element” feature of your browser. If you right click on an area that
interests you, you will be able to see all of the css rules including the default style rules
that affect a particular element.
2. Add an article area as shown in the picture. Give it a purple background. As you try to to
make this area match the picture think about the effects of the various things you may
try.
39
Web Servers and HTTP
We now return to the question of how a page gets from the server to your browser. Let’s use the
idea of a URI as our starting point for this section. In fact let’s start by addressing a very common
point of confusion What is a URI and what is URL, you probably more commonly think of URL’s.
● URL - Uniform Resource Locator
● URI - Uniform Resource Identifier
All locators are also identifiers, so all URLs are URI’s. Think about it this way, Bradley Miller is an
identifier, it identifies me, but does not tell you how to locate me or how to contact me. 321 Olin
Hall, Luther College, Decorah IA, is a locator and an identifier for a specific place in the world. On
the web URL’s have three main pieces, let’s look at one and identify the parts:
http://interactivepython.org/runestone/static/webfundamentals/index.html
Let’s suppose we continue with the URL above. You, the user, type in the URL to your browser, The
browser knows that the host name is the part that comes after the first two slashes, but before the
next slash. So it is able to extract that part of the URL. Using patterns like this occurs frequently in
Computer Science. The name is then passed on to another server called the Domain Name Service
(DNS) in the diagram above. The DNS is actually a very large and complex network of servers, but
we’ll just take it for granted that it works and gives us back the IP address correctly. With the
address in hand, the browser establishes a connection to the server through a mechanism known
as a socket. This socket allows the browser and the server to reliably communicate over the
internet.
An HTTP Request
40
With the connection established the browser sends the following message:
The format of this message is defined by HTTP. Remember a protocol is a well defined set of
rules for how one program communicates with another. Let us break down this message into its
component parts.
● GET – HTTP defines several commands, but the most common are GET and POST. As
you might imagine, GET is a request to retrieve some resource from the server.
● runestone/static/webfundamentals/index.html This is the URI for the resource that we
want to get. Recall that this will correspond to a file on the disk drive of the server.
● HTTP/1.1 tells the server that the browser is “speaking” the 1.1 version of the HTTP
protocol.
This is all of the information that can be contained on the first line of the message. If there is
anything else on the line it may confuse the server, or the server may just ignore it. This line is
called the request line.
What follows the request line are a series of lines called the headers There may be just one
header or there may be many. However, there can only be one header per line and they all follow
the pattern of name: value. So the first line the name is host and the value
is myname.luther.edu this lets the server know the name of the machine that is contacting it.
The User-Agent header tells the server that the user is running version 6.0 of the Mozilla browser.
Finally the last line is blank. The server knows that there are no more headers when it gets a
blank line.
An HTTP Response
The server extracts the URI from the request line and goes out to its disk to locate the file.
Assuming the file is there it will make the following response through the socket back to the
browser:
HTTP/1.1 200 OK
Date: Tues, 2 Sept 2014 15:39:21
Server: Apache/1.4.1
Content-Type: text/html
<html>
<head>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Just like the request, the format of the response is spelled out by the HTTP. The first line again
has three parts HTTP/1.1 tells the browser that the server is following the HTTP 1.1 protocol.
41
the 200 is the response code that tells the browser that everything is fine and the OK is a
descriptive message: Some other common response lines are:
● HTTP/1.1 404 Not Found – you may have seen a 404 if you’ve ever mistyped a URL
● HTTP/1.1 500 Internal Server Error – The server itself has crashed for some reason
● HTTP/1.1 302 Resource Moved
Following the response line are the headers from the server. Most of these are self-explanatory,
but the Content-Type header is particularly important. This tells the browser that what follows is
going to be some HTML. Another common Content-type is image/jpg this tells the browser that
what comes next is going to be an image. Note that each image in a page will require its own
request / response from the browser to the server.
Databases
o A database is a way of electronically storing collections of data in an organised
manner. A database is controlled by a DBMS which is an acronym for Database
Management System, DBMS's fall into two
camps Relational or Non-Relational, the focus of this room will be on
Relational databases, some common one's you'll come across are MySQL,
Microsoft SQL Server, Access, PostgreSQL and SQLite. We'll explain the
difference between Relational and Non-Relational databases at the end of this
task but first, it's important to learn a few terms.
o Within a DBMS, you can have multiple databases, each containing its own set of
related data. For example, you may have a database called "shop". Within this
database, you want to store information about products available
to purchase, users who have signed up to your online shop, and information
about the orders you've received. You'd store this information separately in the
database using something called tables, the tables are identified with a unique
name for each one. You can see this structure in the diagram below, but you can
also see how a business might have other separate databases to store staff
information or the accounts team.
42
o
Columns:
Each column, better referred to as a field has a unique name per table. When
creating a column, you also set the type of data it will contain, common ones being
integer (numbers), strings (standard text) or dates. Some databases can contain
much more complex data, such as geospatial, which contains location information.
Setting the data type also ensures that incorrect information isn't stored, such as
the string "hello world" being stored in a column meant for dates. If this happens,
the database server will usually produce an error message. A column containing an
integer can also have an auto-increment feature enabled; this gives each row of
data a unique number that grows (increments) with each subsequent row, doing so
creates what is called a key field, a key field has to be unique for every row of data
43
which can be used to find that exact row in SQL queries.
Rows:
Rows or records are what contains the individual lines of data. When you add data
to the table, a new row/record is created, and when you delete data, a row/record
is removed.
Non-relational databases sometimes called NoSQL on the other hand is any sort of
database that doesn't use tables, columns and rows to store the data, a specific
database layout doesn't need to be constructed so each row of data can contain
different information which can give more flexibility over a relational database.
Some popular databases of this type are MongoDB, Cassandra and ElasticSearch.
44
Browser APIs
All browsers have a set of built-in Web APIs to support complex operations, and
to help accessing data.
For example, the Geolocation API can return the coordinates of where the
browser is located.
Example
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
myElement.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
myElement.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
45
Image source: Overloaded plug socket by The Clear Communication People, on Flickr.
In the same way, if you want to say, program some 3D graphics, it is a lot easier to do it using an
API written in a higher-level language such as JavaScript or Python, rather than try to directly
write low-level code (say C or C++) that directly controls the computer's GPU or other graphics
functions.
Note: See also the API glossary entry for further description.
Client-side JavaScript, in particular, has many APIs available to it — these are not part of the
JavaScript language itself, rather they are built on top of the core JavaScript language, providing
you with extra superpowers to use in your JavaScript code. They generally fall into two
categories:
● Browser APIs are built into your web browser and are able to expose data from the browser and
surrounding computer environment and do useful complex things with it. For example, the Web
Audio API provides JavaScript constructs for manipulating audio in the browser — taking an
audio track, altering its volume, applying effects to it, etc. In the background, the browser is
actually using some complex lower-level code (e.g. C++ or Rust) to do the actual audio
processing. But again, this complexity is abstracted away from you by the API.
● Third-party APIs are not built into the browser by default, and you generally have to retrieve
their code and information from somewhere on the Web. For example, the Twitter API allows
46
you to do things like displaying your latest tweets on your website. It provides a special set of
constructs you can use to query the Twitter service and return specific information.
So above, we talked about what client-side JavaScript APIs are, and how they relate to the
JavaScript language. Let's recap this to make it clearer, and also mention where other JavaScript
tools fit in:
● JavaScript — A high-level scripting language built into browsers that allows you to implement
functionality on web pages/apps. Note that JavaScript is also available in other programming
environments, such as Node.
● Browser APIs — constructs built into the browser that sits on top of the JavaScript language and
allows you to implement functionality more easily.
● Third-party APIs — constructs built into third-party platforms (e.g. Twitter, Facebook) that allow
you to use some of those platform's functionality in your own web pages (for example, display
your latest Tweets on your web page).
● JavaScript libraries — Usually one or more JavaScript files containing custom functions that you
can attach to your web page to speed up or enable writing common functionality. Examples
include jQuery, Mootools and React.
● JavaScript frameworks — The next step up from libraries, JavaScript frameworks (e.g. Angular
and Ember) tend to be packages of HTML, CSS, JavaScript, and other technologies that you install
and then use to write an entire web application from scratch. The key difference between a
library and a framework is "Inversion of Control". When calling a method from a library, the
developer is in control. With a framework, the control is inverted: the framework calls the
developer's code.
47
What can APIs do?
There are a huge number of APIs available in modern browsers that allow you to do a wide
variety of things in your code. You can see this by taking a look at the MDN APIs index page.
Common browser APIs
In particular, the most common categories of browser APIs you'll use (and which we'll cover in
this module in greater detail) are:
● APIs for manipulating documents loaded into the browser. The most obvious example is
the DOM (Document Object Model) API, which allows you to manipulate HTML and CSS —
creating, removing and changing HTML, dynamically applying new styles to your page, etc. Every
time you see a popup window appear on a page or some new content displayed, for example,
that's the DOM in action. Find out more about these types of API in Manipulating documents.
● APIs that fetch data from the server to update small sections of a webpage on their own are
very commonly used. This seemingly small detail has had a huge impact on the performance and
behavior of sites — if you just need to update a stock listing or list of available new stories, doing
it instantly without having to reload the whole entire page from the server can make the site or
app feel much more responsive and "snappy". The main API used for this is the Fetch API,
although older code might still use the XMLHttpRequest API. You may also come across the
term Ajax, which describes this technique. Find out more about such APIs in Fetching data from
the server.
● APIs for drawing and manipulating graphics are widely supported in browsers — the most
popular ones are Canvas and WebGL, which allow you to programmatically update the pixel data
contained in an HTML <canvas> element to create 2D and 3D scenes. For example, you might
draw shapes such as rectangles or circles, import an image onto the canvas, and apply a filter to
it such as sepia or grayscale using the Canvas API, or create a complex 3D scene with lighting and
textures using WebGL. Such APIs are often combined with APIs for creating animation loops
(such as window.requestAnimationFrame()) and others to make constantly updating scenes like
cartoons and games.
● Audio and Video APIs like HTMLMediaElement, the Web Audio API, and WebRTC allow you to do
really interesting things with multimedia such as creating custom UI controls for playing audio
and video, displaying text tracks like captions and subtitles along with your videos, grabbing
video from your web camera to be manipulated via a canvas (see above) or displayed on
someone else's computer in a web conference, or adding effects to audio tracks (such as gain,
distortion, panning, etc.).
● Device APIs enable you to interact with device hardware: for example, accessing the device GPS
to find the user's position using the Geolocation API.
● Client-side storage APIs enable you to store data on the client-side, so you can create an app
that will save its state between page loads, and perhaps even work when the device is offline.
There are several options available, e.g. simple name/value storage with the Web Storage API,
and more complex database storage with the IndexedDB API.
Third-party APIs come in a large variety; some of the more popular ones that you are likely to
make use of sooner or later are:
● The Twitter API, which allows you to do things like displaying your latest tweets on your website.
48
● Map APIs, like Mapquest and the Google Maps API, which allow you to do all sorts of things with
maps on your web pages.
● The Facebook suite of APIs, which enables you to use various parts of the Facebook ecosystem to
benefit your app, such as by providing app login using Facebook login, accepting in-app
payments, rolling out targeted ad campaigns, etc.
● The Telegram APIs, which allows you to embed content from Telegram channels on your website,
in addition to providing support for bots.
● The YouTube API, which allows you to embed YouTube videos on your site, search YouTube, build
playlists, and more.
● The Pinterest API, which provides tools to manage Pinterest boards and pins to include them in
your website.
● The Twilio API, which provides a framework for building voice and video call functionality into
your app, sending SMS/MMS from your apps, and more.
● The Mastodon API, which enables you to manipulate features of the Mastodon social network
programmatically.
Note: You can find information on a lot more 3rd party APIs in the Programmable Web API
directory.
Different JavaScript APIs work in slightly different ways, but generally, they have common
features and similar themes to how they work.
They are based on objects
Your code interacts with APIs using one or more JavaScript objects, which serve as containers
for the data the API uses (contained in object properties), and the functionality the API makes
available (contained in object methods).
Note: If you are not already familiar with how objects work, you should go back and work
through our JavaScript objects module before continuing.
Let's return to the example of the Web Audio API — this is a fairly complex API, which consists
of a number of objects. The most obvious ones are:
● AudioContext, which represents an audio graph that can be used to manipulate audio playing
inside the browser, and has a number of methods and properties available to manipulate that
audio.
● MediaElementAudioSourceNode, which represents an <audio> element containing sound you
want to play and manipulate inside the audio context.
● AudioDestinationNode, which represents the destination of the audio, i.e. the device on your
computer that will actually output it — usually your speakers or headphones.
So how do these objects interact? If you look at our simple web audio example (see it live also),
you'll first see the following HTML:
HTMLCopy to Clipboard
<audio src="outfoxing.mp3"></audio>
49
<button class="paused">Play</button>
<br />
<input type="range" min="0" max="1" step="0.01" value="1" class="volume" />
We, first of all, include an <audio> element with which we embed an MP3 into the page. We don't
include any default browser controls. Next, we include a <button> that we'll use to play and stop
the music, and an <input> element of type range, which we'll use to adjust the volume of the track
while it's playing.
Next, let's look at the JavaScript for this example.
We start by creating an AudioContext instance inside which to manipulate our track:
JSCopy to Clipboard
const AudioContext = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContext();
Next, we create constants that store references to our <audio>, <button>, and <input> elements, and
use the AudioContext.createMediaElementSource() method to create
a MediaElementAudioSourceNode representing the source of our audio — the <audio> element will
be played from:
JSCopy to Clipboard
const audioElement = document.querySelector("audio");
const playBtn = document.querySelector("button");
const volumeSlider = document.querySelector(".volume");
// if track ends
audioElement.addEventListener("ended", () => {
playBtn.setAttribute("class", "paused");
50
playBtn.textContent = "Play";
});
Note: Some of you may notice that the play() and pause() methods being used to play and pause
the track are not part of the Web Audio API; they are part of the HTMLMediaElement API, which
is different but closely-related.
Next, we create a GainNode object using the AudioContext.createGain() method, which can be used
to adjust the volume of audio fed through it, and create another event handler that changes the
value of the audio graph's gain (volume) whenever the slider value is changed:
JSCopy to Clipboard
// volume
const gainNode = audioCtx.createGain();
volumeSlider.addEventListener("input", () => {
gainNode.gain.value = volumeSlider.value;
});
The final thing to do to get this to work is to connect the different nodes in the audio graph up,
which is done using the AudioNode.connect() method available on every node type:
JSCopy to Clipboard
audioSource.connect(gainNode).connect(audioCtx.destination);
The audio starts in the source, which is then connected to the gain node so the audio's volume
can be adjusted. The gain node is then connected to the destination node so the sound can be
played on your computer (the AudioContext.destination property represents whatever is the
default AudioDestinationNode available on your computer's hardware, e.g. your speakers).
They have recognizable entry points
When using an API, you should make sure you know where the entry point is for the API. In The
Web Audio API, this is pretty simple — it is the AudioContext object, which needs to be used to
do any audio manipulation whatsoever.
The Document Object Model (DOM) API also has a simple entry point — its features tend to be
found hanging off the Document object, or an instance of an HTML element that you want to
affect in some way, for example:
JSCopy to Clipboard
const em = document.createElement("em"); // create a new em element
const para = document.querySelector("p"); // reference an existing p element
em.textContent = "Hello there!"; // give em some text content
para.appendChild(em); // embed em inside para
The Canvas API also relies on getting a context object to use to manipulate things, although in
this case, it's a graphical context rather than an audio context. Its context object is created by
getting a reference to the <canvas> element you want to draw on, and then calling
its HTMLCanvasElement.getContext() method:
JSCopy to Clipboard
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
Anything that we want to do to the canvas is then achieved by calling properties and methods of
the context object (which is an instance of CanvasRenderingContext2D), for example:
51
JSCopy to Clipboard
Ball.prototype.draw = function () {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
};
52
Python Operators
Operators are the symbols which perform various operations on Python objects. Python operators are
the most essential to work with the Python data types. In addition, Python also provides identify
membership and bitwise operators. We will learn all these operators with the suitable example in
following project.
o Python Operators
Python Loops
Sometimes we may need to alter the flow of the program. The execution of a specific code may need to
be repeated several numbers of times. For this purpose, the programming languages provide various
types of loops capable of repeating some specific code several times. Consider the following project to
understand the statements in detail.
o Python Loops
Python List
Python list holds the ordered collection of items. We can store a sequence of items in a list. Python list is
mutable which means it can be modified after its creation. The items of lists are enclosed within the
square bracket [] and separated by the comma. Let's see the example of list.
2. L2 = [1, 2, 3, 4, 5, 6]
If we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
1. print(type(L1))
2. print(type(L2))
Output:
<class 'list'>
53
<class 'list'>
o Python List
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since
the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of
the items stored in the tuple cannot be changed.
Example -
2. print(type(tup))
3. print(tup)
Output:
<class 'tuple'>
Example -
2.
3. tup[2] = "Papaya"
4. print(tup)
Output:
tup[2] = "Papaya"
The above program throws an error because tuples are immutable type.
54
Python String
Python string is a sequence of characters. It is a collection of the characters surrounded by single quotes,
double quotes, or triple quotes. It can also define as collection of the Unicode characters. We can create
a string as follows.
Example -
3. print(str1)
6. print(str1)
9. print(str1)
Output:
Hi Python
Hi Python
Hi Python
Python doesn't support the character data-type. A single character written as 'p' is treated as a string of
length 1.
Stings are also immutable. We can't change after it is declared. To learn more about the string, visit the
following project.
o Python Strings
Dictionaries
Python Dictionary is a most efficient data structure and used to store the large amount of data. It stores
the data in the key-value pair format. Each value is stored corresponding to its key.
Keys must be a unique and value can be any type such as integer, list, tuple, etc.
It is a mutable type; we can reassign after its creation. Below is the example of creating dictionary in
Python.
Example -
4. print(employee)
Output:
<class 'dict'>
The empty curly braces {} are used to create empty dictionary. To learn more, visit the complete project
of the dictionary.
o Python Dictionary
Python Sets
A Python set is a collection of unordered elements. Each element in set must be unique and immutable.
Sets are mutable which means we can modify anytime throughout the program. Let's understand the
example of creating set in Python.
Example -
1. # Creating Set
3. print(Month)
4. print(type(Month))
Output:
<class 'set'>
To get the more information about sets, visit the following resources.
o Python Sets
56
o Python Function
Python Modules
Python modules are the program files that contain a Python code or functions. There are two types of
module in the Python - User-define modules and built-in modules. A module that the user defines, or we
can say that our Python code saved with .py extension, is treated as a user-define module.
Built-in modules are predefined modules of Python. To use the functionality of the modules, we need to
import them into our current working program.
o Python Modules
Python Exceptions
An exception can be defined as an unusual condition in a program resulting in the interruption in the
flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not
executed. Therefore, an exception is the run-time errors that are unable to handle to Python script. An
exception is a Python object that represents an error.
o Python Exceptions
Python CSV
A csv stands for "comma separated values", which is defined as a simple file format that uses specific
structuring to arrange tabular data. It stores tabular data such as spreadsheet or database in plain text
and has a common format for data interchange. A csv file opens into the excel sheet, and the rows and
columns data define the standard format. Visit the following project to learn the CSV module in detail.
57
Python Sending Mail
We can send or read a mail using the Python script. Python's standard library modules are useful for
handling various protocols such as PoP3 and IMAP. We will learn how to send a mail with the popular
email service SMTP from a Python script.
Python magic method is defined as the special method which adds "magic" to a class. It starts and ends
with double underscores, for example, _init_ or _str_.
The built-in classes define many magic methods. The dir() function can be used to see the number of
magic methods inherited by a class. It has two prefixes and suffix underscores in the method name.
o Classes and Objects - Python classes are the blueprint of the object. An object is a collection of
data and method that act on the data.
o Inheritance - An inheritance is a technique where one class inherits the properties of other
classes.
o Constructor - Python provides a special method __init__() which is known as a constructor. This
method is automatically called when an object is instantiated.
o Data Member - A variable that holds data associated with a class and its objects.
o Python Constructor
o Python Inheritance
o Python Polymorphism
Python includes many advance and useful concepts that help the programmer to solve the complex
tasks. These concepts are given below.
Python Iterator
An iterator is simply an object that can be iterated upon. It returns one object at a time. It can be
implemented using the two special methods, __iter__() and __next__().
58
To learn more about the iterators visit our Python Iterators project.
Python Generators
The Generators are an easiest way of creating Iterators. To learn more about, visit our Python
Generators project.
Python Decorators
These are used to modify the behavior of the function. Decorators provide the flexibility to wrap another
function to expand the working of wrapped function, without permanently modifying it.
Python MySQL
Environment Setup
Database Connection
Creating Tables
Insert Operation
Read Operation
Update Operation
Join Operation
Performing Transactions
Python MongoDB
Python MongoDB
Python SQLite
Python SQLite
Python CGI
Python CGI stands for "Common Gateway Interface", which is used to define how to exchange
information between the webserver and a custom Python scripts. The Common Gateway Interface is a
standard for external gateway programs to interface with the server, such as HTTP Servers. To learn more
about Python CGI, visit the following project.
59
60
Python If-else statements
Decision making is the most important aspect of almost all the programming languages. As the name
implies, decision making allows us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition checking is the backbone of
decision making.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a block of
code (if-block) will be executed.
If - else The if-else statement is similar to if statement except the fact that, it also provides the
Statement block of the code for the false case of the condition to be checked. If the condition
provided in the if statement is false, then the else statement will be executed.
Nested if Nested if statements enable us to use if ? else statement inside an outer if statement.
Statement
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual
indentation takes place in decision making and other stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it executes a block of
code known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false.
61
The syntax of the if-statement is given below.
1. if expression:
2. statement
Example 1
2. if num%2 == 0:
3. print("Number is even")
Output:
Number is even
62
1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
5. print("a is largest");
7. print("b is largest");
9. print("c is largest");
Output:
Enter a? 100
Enter b? 120
Enter c? 130
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
63
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
2. if age>=18:
64
3. print("You are eligible to vote !!");
4. else:
Output:
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")
Output:
Number is even
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
65
9.
10. else:
Example 1
66
1. number = int(input("Enter the number?"))
2. if number==10:
4. elif number==50:
6. elif number==100:
8. else:
Output:
Example 2
10. lse:
67
Python for loop
Python is a powerful, general-purpose scripting language intended to be simple to understand and
implement. It is free to access because it is open-source. This project will teach us how to use Python for
loops, one of the most basic looping instructions in Python programming.
In Python, the for loop is often used to iterate over iterable objects such as lists, tuples, or strings.
Traversal is the process of iterating across a series. If we have a section of code that we would like to
repeat a certain number of times, we employ for loops. The for-loop is usually used on an iterable object
such as a list or the in-built range function. The for statement in Python traverses through the elements
of a series, running the block of code each time. The for statement is in opposition to the "while" loop,
which is employed whenever a condition requires to be verified each repetition or when a piece of code
is to be repeated indefinitely.
2. {loop body}
On each iteration, the value is the parameter that gets the element's value within the iterable sequence.
If an expression statement is present in a sequence, it is processed first. The iterating variable
iterating_variable is then allocated to the first element in the sequence. After that, the intended block is
run. The statement block is performed until the whole sequence is completed, and each element in the
sequence is allocated to iterating_variable. The for loop's material is distinguished from the rest of the
program using indentation.
Code
1. # Code to find the sum of squares of each element of the list using for loop
2.
5.
7. sum_ = 0
8.
11.
68
12. sum_ = sum_ + num ** 2
13.
Output:
Code
1. my_list = [3, 5, 6, 8, 4]
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )
Output:
[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]
Another method of iterating through every item is to use an index offset within the sequence. Here's a
simple illustration:
Code
1. # Code to find the sum of squares of each element of the list using for loop
2.
5.
7. sum_ = 0
8.
11.
13.
Output:
The len() built-in method that returns the total number of items in the list or tuple and the built-in
function range(), which returns the exact sequence to iterate over, came in handy here.
When the else clause is combined with a for loop, it is performed after the circuit has finished iterating
over the list.
The following instance shows how to use an otherwise statement in conjunction with a for expression to
find students' marks from the record.
Code
2. student_name_1 = 'Itika'
3. student_name_2 = 'Parker'
4.
5.
9. for a_student in record: # for loop will iterate over the keys of the dictionary
12. break
13. else:
70
15.
Output:
Nested Loops
If we have a piece of script that we want to run a number of times and then another piece of script inside
that script that we want to run B number of times, we employ a "nested loop." When working with an
iterable in the lists, these are widely utilized in Python.
Code
1. import random
2. numbers = [ ]
4. numbers.append( random.randint( 0, 11 ) )
6. for i in numbers:
7. if num == i:
71
Python Functions
This project will learn about the basics of Python functions, including what they are, their syntax, their
main components, return keywords, and major types. We will also see examples of how to define a
Python function.
The functions are broad of two types, user-defined and built-in functions. It aids in keeping the software
succinct, non-repetitive, and well-organized.
o By including functions, we can prevent repeating the same code block repeatedly in a program.
o Python functions, once defined, can be called many times and from anywhere in a program.
o If our Python program is large, it can be separated into numerous functions which is simple to
track.
o The key accomplishment of Python functions is we can return as many outputs as we want with
different arguments.
Code
2. """This is a docstring"""
3. # code block
o name_of_function is the function's name that we can use to separate it from others. We will use
this name to call the function later in the program. The same criteria apply to naming functions
as to naming variables in Python.
o We pass arguments to the defined function using parameters. They are optional, though.
72
o We can use a documentation string called docstring in the short form to explain the purpose of
the function.
o The body of the function is made up of several valid Python statements. The indentation depth
of the whole code block must be the same (usually 4 spaces).
We will define a function that when called will return the square of the number passed to it as an
argument.
Code
2. """
4. """
5. return num**2
6. object_ = square(9)
Output:
Calling a Function
A function is defined by using the def keyword and giving it a name, specifying the arguments that must
be passed to the function, and structuring the code block.
After a function's fundamental framework is complete, we can call it from anywhere in the program. The
following is an example of how to use the a_function function.
Code
1. # Defining a function
4. return len(string)
5.
73
8. print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
In the Python programming language, all arguments are supplied by reference. It implies that if we
modify the value of an argument within a function, the change is also reflected in the calling function.
For instance,
Code
4. squares = []
5. for l in my_list:
6. squares.append( l**2 )
7. return squares
8.
Output:
Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments
Default Arguments
74
A default argument is a kind of parameter that takes as input a default value if no value is supplied for
the argument when the function is called. Default arguments are demonstrated in the following instance.
Code
2. # defining a function
6.
7.
10. function(10)
11.
14. function(10,30)
Output:
num1 is: 10
num2 is: 40
num1 is: 10
num2 is: 30
Keyword Arguments
The arguments in a function called are connected to keyword arguments. If we provide keyword
arguments while calling a function, the user uses the parameter label to identify which parameters value
it is.
Since the Python interpreter will connect the keywords given to link the values with its parameters, we
can omit some arguments or arrange them out of order. The function() method can also be called with
keywords in the following manner:
75
Code
2.
3. # Defining a function
7.
11.
Output:
num1 is: 50
num2 is: 30
num1 is: 30
num2 is: 50
Required Arguments
The arguments given to a function while calling in a pre-defined positional sequence are required
arguments. The count of required arguments in the method call must be equal to the count of arguments
provided while defining the function.
We must send two arguments to the function function() in the correct order, or it will return a syntax
error, as seen below.
Code
76
2.
3. # Defining a function
7.
8. # Calling function and passing two arguments out of order, we need num1 to be 20 and num2 to
be 30
11.
14. try:
15. function( 30 )
16. except:
Output:
num1 is: 30
num2 is: 20
Variable-Length Arguments
We can use special characters in Python functions to pass as many arguments as we want in a function.
There are two types of characters that we can use for this purpose:
Code
77
1. # Python code to demonstrate the use of variable-length arguments
2.
3. # Defining a function
5. ans = []
6. for l in args_list:
7. ans.append( l.upper() )
8. return ans
12.
15. ans = []
21. print(object)
Output:
return Statement
We write a return statement in a function to leave a function and give the calculated value when a
defined function is called.
Syntax:
78
An argument, a statement, or a value can be used in the return statement, which is given as output when
a specific task or function is completed. If we do not write a return statement, then None object is
returned by a defined function.
Code
2.
5. return num**2
6.
9. print( square( 39 ) )
10.
13. num**2
14.
Output:
1521
None
79
Lambda expressions can accept an unlimited number of arguments; however, they only return one value
as the result of the function. They can't have numerous expressions or instructions in them. Since
lambda needs an expression, an anonymous function cannot be directly called to print.
Lambda functions contain their unique local domain, meaning they can only reference variables in their
argument list and the global domain name.
Although lambda expressions seem to be a one-line representation of a function, they are not like inline
expressions in C and C++, which pass function stack allocations at execution for efficiency concerns.
Syntax
Code
1. # Defining a function
3.
Output:
The scope of a variable refers to the domain of a program wherever it is declared. A function's arguments
and variables are not accessible outside the defined function. As a result, they only have a local domain.
The period of a variable's existence in RAM is referred to as its lifetime. Variables within a function have
the same lifespan as the function itself.
When we get out of the function, they are removed. As a result, a function does not retain a variable's
value from earlier executions.
Code
2. def number( ):
80
3. num = 30
5.
6. num = 20
7. number()
Output:
Here, we can observe that the initial value of num is 20. Even if the function number() modified the value
of num to 30, the value of num outside the function remained unchanged.
This is because the variable num within the function is distinct from the variable outside the function
(local to the function). Despite their identical variable name, they are 2 distinct variables having distinct
scopes.
Variables beyond the function, on the contrary, are accessible within the function. These variables have a
global reach.
We can retrieve their values inside the function but cannot alter (change) them. If we declare a variable
global using the keyword global, we can also change the variable's value outside the function.
Functions are considered first-class objects in Python. In a programming language, first-class objects are
treated the same wherever they are used. They can be used in conditional expressions, as arguments,
and saved in built-in data structures. If a programming language handles functions as first-class entities, it
is said to implement first-class functions. Python supports the notion of First Class functions.
Inner or nested function refers to a function defined within another defined function. Inner functions can
access the parameters of the outer scope. Inner functions are constructed to cover them from the
changes that happen outside the function. Many developers regard this process as encapsulation.
Code
3. def function1():
5.
6. def function2():
81
7. print( string )
8.
9. function2()
10. function1()
82
Python Arrays
An array is defined as a collection of items that are stored at contiguous memory locations. It is a
container which can hold a fixed number of items, and these items should be of the same type. An array
is popular in most programming languages like C/C++, JavaScript, etc.
Array is an idea of storing multiple items of the same type together and it makes easier to calculate the
position of each element by simply adding an offset to the base value. A combination of the arrays could
save a lot of time by reducing the overall size of the code. It is used to store multiple values in single
variable. If you have a list of items that are stored in their corresponding variables like this:
car1 = "Lamborghini"
car2 = "Bugatti"
car3 = "Koenigsegg"
If you want to loop through cars and find a specific one, you can use the array.
The array can be handled in Python by a module named array. It is useful when we have to manipulate
only specific data values. Following are the terms to understand the concept of an array:
Index - The location of an element in an array has a numerical index, which is used to identify the
position of the element.
Array Representation
An array can be declared in various ways and different languages. The important points that should be
considered are as follows:
o The length of the array defines the capacity to store the elements.
Array operations
Some of the basic operations supported by an array are as follows:
The Array can be created in Python by importing the array module to the python program.
83
2. arrayName = array(typecode, [initializers])
We can access the array elements using the respective indices of those elements.
Output:
First element: 2
Second element: 4
Explanation: In the above example, we have imported an array, defined a variable named as "a" that
holds the elements of an array and print the elements by accessing elements through indices of an array.
Arrays are mutable, and their elements can be changed in a similar way like lists.
3.
5. numbers[0] = 0
7.
Output:
84
Explanation: In the above example, we have imported an array and defined a variable named as
"numbers" which holds the value of an array. If we want to change or add the elements in an array, we
can do it by defining the particular index of an array where you want to change or add the elements.
A combination of arrays saves a lot of time. The array can reduce the overall size of the code.
The elements can be deleted from an array using Python's del statement. If we want to delete any value
from the array, we can do that by using the indices of a particular element.
Output:
Explanation: In the above example, we have imported an array and defined a variable named as
"number" which stores the values of an array. Here, by using del statement, we are removing the third
element [3] of the given array.
Syntax
1. len(array_name)
Array Concatenation
We can easily concatenate any two arrays using the + symbol.
Example
2. b=arr.array('d',[3.7,8.6])
3. c=arr.array('d')
4. c=a+b
5. print("Array c = ",c)
Output:
85
Explanation
In the above example, we have defined variables named as "a, b, c" that hold the values of an array.
Example
Output:
First element: 4
Second element: 7
Explanation: In the above example, first, we have imported an array and defined a variable named as "x"
which holds the value of an array and then, we have printed the elements using the indices of an array.
86
Python String
Till now, we have discussed numbers as the standard data-types in Python. In this section of the project,
we will discuss the most popular data type in Python, i.e., string.
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple
quotes. The computer does not understand the characters; internally, it stores manipulated character as
the combination of the 0's and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also
called the collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes.
Python allows us to use single quotes, double quotes, or triple quotes to create the string.
Syntax:
Here, if we check the type of the variable str using a Python script
In Python, strings are treated as the sequence of characters, which means that Python doesn't support
the character data-type; instead, a single character written as 'p' is treated as the string of length 1.
3. print(str1)
6. print(str2)
7.
11. docstring'''
12. print(str3)
87
Output:
Hello Python
Hello Python
docstring
1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
Output:
As shown in Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given string.
Consider the following example.
Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str =
'HELLO' is given, then str[1:3] will always include str[1] = 'E', str[2] = 'L' and nothing else.
89
Consider the following example:
1. # Given String
2. str = "JAVATPOINT"
4. print(str[0:])
6. print(str[1:5])
8. print(str[2:4])
10. print(str[:3])
12. print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
We can do the negative slicing in the string; it starts from the rightmost character, which is indicated as
-1. The second rightmost index indicates -2, and so on. Consider the following image.
90
Consider the following example
1. str = 'JAVATPOINT'
2. print(str[-1])
3. print(str[-3])
4. print(str[-2:])
5. print(str[-4:-1])
6. print(str[-7:-2])
8. print(str[::-1])
9. print(str[-12])
Output:
NT
OIN
ATPOI
TNIOPTAVAJ
Example 1
1. str = "HELLO"
2. str[0] = "h"
3. print(str)
Output:
str[0] = "h";
However, in example 1, the string str can be assigned completely to a new content as specified in the
following example.
Example 2
1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
Output:
HELLO
hello
1. str = "JAVATPOINT"
2. del str[1]
Output:
92
Now we are deleting entire string.
1. str1 = "JAVATPOINT"
2. del str1
3. print(str1)
Output:
String Operators
Operator Description
+ It is known as concatenation operator used to join the strings given either side of the
operator.
* It is known as repetition operator. It concatenates the multiple copies of the same string.
[:] It is known as range slice operator. It is used to access the characters from the specified
range.
not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.
r/R It is used to specify the raw string. Raw strings are used in the cases where we need to
print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.
% It is used to perform string formatting. It makes use of the format specifiers used in C
programming like %d or %f to map their values in python. We will discuss how
formatting is done in python.
Example
Consider the following example to understand the real use of Python operators.
1. str = "Hello"
93
2. str1 = " world"
5. print(str[4]) # prints o
6. print(str[2:4]); # prints ll
10. print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
ll
False
False
C://python37
Escape Sequence
Let's suppose we need to write the text as - They said, "Hello what's going on?"- the given statement can
be written in single quotes or double quotes but it will raise the SyntaxError as it contains both single
and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
2. print(str)
Output:
We can use the triple quotes to accomplish this problem but Python provides the escape sequence.
94
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We can
apply the same as in the double quotes.
Example -
3.
6.
Output:
Python2 \
Python3")
Output:
2. \\ Backslash print("\\")
Output:
95
Output:
'
Output:
"
Output:
Hello World
Hello World!
Output:
Hello
World!
Output:
World!
Output:
Hello World!
Output:
Hello
96
World!
Output:
Hello
Output:
Hello
1. print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")
Output:
C:\Users\DEVANSH SHARMA\Python32\Lib
This is the
multiline quotes
We can ignore the escape sequence from the given string by using the raw string. We can do this by
writing r or R in front of the string. Consider the following example.
1. print(r"C:\\Users\\DEVANSH SHARMA\\Python32")
Output:
C:\\Users\\DEVANSH SHARMA\\Python32
The format() method is the most flexible and useful method in formatting strings. The curly braces {} are
used as the placeholder in the string and replaced by the format() method argument. Let's have a look at
the given an example:
3.
4. #Positional Argument
97
5. print("{1} and {0} best players ".format("Virat","Rohit"))
6.
7. #Keyword Argument
Output:
James,Peter,Ricky
1. Integer = 10;
2. Float = 1.290
3. String = "Devansh"
4. print("Hi I am Integer ... My value is %d\nHi I am float ... My value is %f\nHi I am string ... My val
ue is %s"%(Integer,Float,String))
Output:
Method Description
98
casefold() It returns a version of s suitable for case-less comparisons.
center(width ,fillchar) It returns a space padded string with the original string centred
with equal number of left and right spaces.
decode(encoding = 'UTF8', errors Decodes the string using codec registered for encoding.
= 'strict')
find(substring ,beginIndex, It returns the index value of the string where substring is found
endIndex) between begin index and end index.
isalnum() It returns true if the characters in the string are alphanumeric i.e.,
alphabets or numbers and there is at least 1 character.
Otherwise, it returns false.
isalpha() It returns true if all the characters are alphabets and there is at
least one character, otherwise False.
isdecimal() It returns true if all the characters of the string are decimals.
99
isdigit() It returns true if all the characters are digits and there is at least
one character, otherwise False.
istitle() It returns true if the string is titled properly and false otherwise. A
title string is the one in which the first character is upper-case
whereas the other characters are lower-case.
isupper() It returns true if all the characters of the string(if exists) is true
otherwise it returns false.
ljust(width[,fillchar]) It returns the space padded strings with the original string left
justified to the given width.
100
partition() It searches for the separator sep in S, and returns the part before
it, the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
rjust(width,[,fillchar]) Returns a space padded string having original string right justified
to the number of characters specified.
rstrip() It removes all trailing whitespace of a string and can also be used
to remove particular character from trailing.
rsplit(sep=None, maxsplit = -1) It is same as split() but it processes the string from the backward
direction. It returns the list of words in the string. If Separator is
not specified then the string splits according to the white-space.
split(str,num=string.count(str)) Splits the string according to the delimiter str. The string splits
according to the space if the delimiter is not provided. It returns
the list of substring concatenated with the delimiter.
splitlines(num=string.count('\n')) It returns the list of strings at each line with newline removed.
startswith(str,beg=0,end=len(str)) It returns a Boolean value if the string starts with given str
between begin and end.
101
title() It is used to convert the string into the title-case i.e., The
string meEruT will be converted to Meerut.
translate(table,deletechars = '') It translates the string according to the translation table passed in
the function .
rpartition()
102
File Handling in Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files. The concept of file handling has stretched over
various other languages, but the implementation is either complicated or lengthy, but like other concepts
of Python, this concept here is also easy and short. Python treats files differently as text or binary and
this is important. Each line of code includes a sequence of characters and they form a text file. Each line
of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or
newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with
the reading and writing files.
f = open(filename, mode)
2. w: open an existing file for a write operation. If the file already contains some data then it will be
overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
6. a+: To append and read data from the file. It won’t override existing data.
● Python3
print (each)
The open command will open the file in the read mode and the for loop will print each line present in the
file.
103
Working of read() mode
There is more than one way to read a file in Python. If you need to extract a string that contains all
characters in the file then we can use file.read(). The full code would work like this:
● Python3
print (file.read())
Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first five characters of stored data and return it as a string:
● Python3
print (file.read(5))
● Python3
file = open('geek.txt','w')
file.close()
The close() command terminates all the resources in use and frees the system of this particular program.
● Python3
104
file = open('geek.txt', 'a')
file.close()
There are also various other commands in file handling that is used to handle various tasks like:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are working with code.
That explains why it’s good practice to use them with a statement where applicable. This is helpful
because using this method any files opened will be closed automatically after one is done, so
auto-cleanup.
Example:
● Python3
data = file.read()
● Python3
f.write("Hello World!!!")
● Python3
105
with open("file.text", "r") as file:
data = file.readlines()
word = line.split()
print (word)
Look at the file code below, which displays file size, the last accessed time, and the last modified time.
stat = os.stat("myFile.txt")
The os.stat function returns a stat results object with many file attribute details. Here we used st_size to
get the file size, at_atime to get the last file accessed timestamp, and st_mtime to get the last modified
timestamp. The stat results object can be different according to your operating system. For example, on
the Windows operating system, you can retrieve Windows-specific file attributes via
the st_file_attributes key.
If you need to get only file size, you can use the os.path.getsize method without retrieving all metadata,
as shown in the following code.
size = os.path.getsize("myFile.txt")
import os
106
os.mkdir("myFolder")
If you try to make multiple directories recursively with the above code, it will fail. For example, you can’t
create myFolder/abc at once because it requires the creation of multiple directories. In those scenarios,
the os.makedirs function will help us, as shown below.
import os
import os
cur_dir = os.getcwd()
entries = os.listdir(cur_dir)
print('-' * 10)
print(entry)
Once you execute the above script, it will show your current directory’s entries, as shown below.
Try executing the script from a different directory. Then it will display entries of that specific directory
because we use the os.getcwd function to get the current working directory.
107
Sometimes we need to list directory content recursively. The os.walk function helps us with the recursive
directory listing. The following code lists all entries of the current working directory recursively.
import os
cur_dir = os.getcwd()
rel_root = os.path.relpath(root)
print("-" * 10)
print(entry)
The os.walk function has a recursive implementation internally. It returns three values for each entry:
● Root
● Subdirectories
● File entries
Here we used root, sub_dirs, and files variables respectively, with a for-loop to capture all entries.
file_to_remove = "myFile.txt"
if os.path.exists(file_to_remove):
os.remove(file_to_remove)
else:
The Python standard library also offers the os.rmdir function to remove a single directory. It behaves
similar to os.mkdir and won’t remove a directory if the particular directory has some entries. First, try to
remove a single directory with the following code.
import os
dir_to_remove = "myFolder"
if os.path.exists(dir_to_remove):
os.rmdir(dir_to_remove)
else:
The above code will throw an error if myFolder contains subfolders or files. Use the following code
snippet to remove a directory recursively.
dir_to_remove = "myFolder"
if os.path.exists(dir_to_remove):
else:
109
Performing file searches in Python
When we work with automation scripts, sometimes we need to perform file searches on the disk. For
example, programmers often need to find log files, image files, and various text files via their Python
scripts. There are a few different approaches to performing file searches in Python:
● Finding all entries with the os.listdir function and checking each entry with an if condition inside
a for loop
● Finding all entries recursively with the os.walktree function and validating each entry with
an if condition inside a for loop.
● Querying all entries with the glob.glob function and obtaining only entries you need
Overall, the third approach is best for most scenarios because it has inbuilt filtering support, very good
performance, and requires minimal code from the developer’s end (more Pythonic). Let’s implement a
file search with the Python glob module.
import glob, os
query = "**/*.py"
no_of_entries = len(entries)
if no_of_entries == 0:
else:
print("-" * 10)
print(entry)
The above code lists all Python source files in the current directory recursively. The first two asterisks (**)
in the query variable instruct Python to search every sub-directory, while the last asterisk refers to any
filename.
Run the above script. You will see Python source files, as shown below.
110
Try to search different file types by changing the query variable.
To get started with binary file handling, let’s write a binary file with some bytes. We are going to save the
following bytes into myFile.bin.
For simplicity, we can represent the above bytes with the following decimal values respectively.
Now, add the following code to your Python source file and execute it to create the binary file.
myBinaryFile.write(bytes)
myBinaryFile.close()
Here, we passed a byte array instance to the file object’s write method. Also, note that we used binary
mode (b) to create the file object. After executing the above code snippet, open the newly
created myFile.bin with your favorite text editor. You will see the following result.
111
We have received “Python” as the output because the byte array’s bytes represent known ASCII
characters. For example, 80 (01010000) represents letter P in ASCII encoding. Even though we saved
readable text inside a binary file, almost all binary files contain unreadable byte streams. Try opening an
image file via a text editor.
Now we can see the binary file read operation in the following example code.
bytes = myBinaryFile.read()
print(bytes) # bytearray(b'Python')
print("Bytes: ", list(bytes)) # Bytes: [80, 121, 116, 104, 111, 110]
myBinaryFile.close()
Python returns bytes with the read method for the binary mode. Here we converted bytes to
a bytearray instance using the bytearray constructor.
Python standard library offers archive file processing APIs via the shutil module. First, let’s make an
archive with myFolder’s content. Look at the following code. Make sure to create myFolder and add
some files into it before running the code snippet.
import shutil
112
output_file = "myArchive"
input_dir = "myFolder"
You can extract the archive file into myNewFolder with the following code.
import shutil
input_file = "myArchive.zip"
output_dir = "myNewFolder"
shutil.unpack_archive(input_file, output_dir)
import shutil
shutil.copy("main.py", "main_copy.py")
shutil.move("main_copy.py", "main_backup.py")
shutil.copytree("myFolder", "myFolder_copy")
shutil.move("myFolder_copy", "myFolder_backup")
print("Done.")
For example, some programmers use try-finally block and close file handlers manually. Some
programmers let the garbage collector close the file handler by omitting the close method call — which is
not a good practice. Meanwhile, other programmers use the with syntax to work with file handlers.
113
In this section, I will summarize some best practices for file handling in Python. First, look at the following
code that follows file handling best practices.
def print_file_content(filename):
content = myFile.read()
print(content)
file_to_read = "myFile.txt"
try:
print_file_content(file_to_read)
except:
else:
Here, we used the with keyword to implicitly close the file handler. Also, we handle possible exceptions
with a try-except block. While you are working with Python file handling, may sure that your code has
the following points.
● Never ignore exceptions — especially with long-running Python processes. However, it’s okay to
ignore exceptions for simple utility scripts because unhandled exceptions halt utility scripts from
continuing further
● If you are not using the with syntax, make sure to close opened file handlers properly. The
Python garbage collector will clean the unclosed file handlers, but it’s always good to close a file
handler via our code to avoid unwanted resource usages
● Make sure to unify file handling syntaxes in your codebase. For example, if you use with keyword
for handling files, make sure to use the same syntax for all places where you are handling file
● Avoid reopening the same file again when you read or write with multiple handlers. Instead, use
the flush and seek methods, as shown below:
def process_file(filename):
# Write content
myFile.write("Hello Python!")
114
print("Cursor position: ", myFile.tell()) # 13
myFile.flush()
myFile.seek(0)
content = myFile.read()
print(content)
file_to_read = "myFile.txt"
try:
process_file(file_to_read)
except:
else:
The above content saves a string to the file first. After that, it reads the newly added content again by
resetting the internal buffer. The flush method clears the temporarily saved data in memory, so the next
read will return the newly added content. Also, we need to use the seek(0) method call to reset the
cursor to the beginning because the write method sets it to the end.
115
Python GUI – tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods,
tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit
shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applications.
Creating a GUI using tkinter is an easy task.
Python provides various options for developing graphical user interfaces (GUIs). Most important are
listed below.
● Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would
look this option in this chapter.
● JPython − JPython is a Python port for Java which gives Python scripts seamless access to Java
class libraries on the local machine http://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and
easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI
toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps
−
● Enter the main event loop to take action against each event triggered by the user.
Example
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()
top.mainloop()
116
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These
controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description
in the following table −
1 Button
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your
application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user can
select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting values from a user.
5 Frame
117
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also contain
images.
7 Listbox
8 Menubutton
9 Menu
The Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting values from a user.
11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The user can
select only one option at a time.
12 Scale
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14 Text
15 Toplevel
16 Spinbox
118
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to
select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or container
for complex window layouts.
19 tkMessageBox
Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and fonts are specified.
● Dimensions
● Colors
● Fonts
● Anchors
● Relief styles
● Bitmaps
● Cursors
Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have the purpose of
organizing widgets throughout the parent widget area. Tkinter exposes the following geometry manager
classes: pack, grid, and place.
● The pack() Method − This geometry manager organizes widgets in blocks before placing them in
the parent widget.
● The grid() Method − This geometry manager organizes widgets in a table-like structure in the
parent widget.
119
● The place() Method − This geometry manager organizes widgets by placing them in a specific
position in the parent widget.
Importing tkinter is same as importing any other module in the Python code. Note that the name of the
module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.
import tkinter
There are two main methods used which the user needs to remember while creating the Python
application with GUI.
2. mainloop(): There is a method known by the name mainloop() is used when your application is
ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur
and process the event as long as the window is not closed.
m.mainloop()
import tkinter
m = tkinter.Tk()
'''
'''
m.mainloop()
tkinter also offers access to the geometric configuration of the widgets which can organize the widgets in
the parent windows. There are mainly three geometry manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
120
2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the parent
widget.
3. place() method:It organizes the widgets by placing them on specific positions directed by the
programmer.
There are a number of widgets which you can put in your tkinter application. Some of the major widgets
are explained below:
w=Button(master, option=value)
● activebackground: to set the background color when button is under the cursor.
● activeforeground: to set the foreground color when button is under the cursor.
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button.pack()
r.mainloop()
Output:
121
2. Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:
3. w = Canvas(master, option=value)
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
master = Tk()
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Output:
w = CheckButton(master, option=value)
122
There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● activebackground: to set the background color when widget is under the cursor.
● activeforeground: to set the foreground color when widget is under the cursor.
Break
Secret Code:
master = Tk()
var1 = IntVar()
var2 = IntVar()
mainloop()
Output:
5. Entry:It is used to input the single line text entry from the user.. For multi-line text input, Text
widget is used.
The general syntax is:
6. w=Entry(master, option=value)
123
● bd: to set the border width in pixels.
master = Tk()
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
Output:
7. Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the
widgets. The general syntax is:
8. w = Frame(master, option=value)
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● highlightcolor: To set the color of the focus highlight when widget has to be focused.
124
● cursor: to set the cursor used.
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
root.mainloop()
Output:
9. Label: It refers to the display box where you can put any text or image which can be updated any
time as per the code.
The general syntax is:
125
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
Output:
11. Listbox: It offers a list to the user from which the user can accept any number of options.
The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● highlightcolor: To set the color of the focus highlight when widget has to be focused.
126
● height: to set the height of the widget.
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.pack()
top.mainloop()
Output:
13. MenuButton: It is a part of top-down menu which stays on the window all the time. Every
menubutton has its own functionality. The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
127
● cursor: To appear the cursor when the mouse over the menubutton.
● highlightcolor: To set the color of the focus highlight when widget has to be focused.
top = Tk()
mb.grid()
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.pack()
top.mainloop()
Output:
15. Menu: It is used to create all kinds of menus used by the application.
The general syntax is:
There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● activeforeground: to set the foreground color when widget is under the cursor.
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
129
Output:
17. Message: It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
main = Tk()
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
130
Output:
20. RadioButton: It is used to offer multi-choice option to the user. It offers several options to the
user and the user has to choose one option.
The general syntax is:
There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● activebackground: to set the background color when widget is under the cursor.
● activeforeground: to set the foreground color when widget is under the cursor.
root = Tk()
v = IntVar()
mainloop()
Output:
22. Scale: It is used to provide a graphical slider that allows to select any value from that scale. The
general syntax is:
131
23. w = Scale(master, option=value)
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● cursor: To change the cursor pattern when the mouse is over the widget.
● activebackground: To set the background of the widget when mouse is over the widget.
● to: To set the value of the other end of the scale range.
master = Tk()
w.pack()
w.pack()
mainloop()
Output:
25. Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● cursor: To appear the cursor when the mouse over the menubutton.
root = Tk()
scrollbar = Scrollbar(root)
mainloop()
Output:
28. Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
133
There are number of options which are used to change the format of the text. Number of options can be
passed as parameters separated by commas. Some of them are listed below.
● highlightcolor: To set the color of the focus highlight when widget has to be focused.
root = Tk()
T.pack()
mainloop()
Output:
30. TopLevel: This widget is directly controlled by the window manager. It don’t need any parent
window to work on.The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● cursor: To appear the cursor when the mouse over the menubutton.
134
from tkinter import *
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()
Output:
32. SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of
numbers.The general syntax is:
There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas. Some of them are listed below.
● cursor: To appear the cursor when the mouse over the menubutton.
135
● to: To set the value of the other end of the range.
master = Tk()
w.pack()
mainloop()
Output:
34. PannedWindowIt is a container widget which is used to handle number of panes arranged in it.
The general syntax is:
● cursor: To appear the cursor when the mouse over the menubutton.
m1 = PanedWindow()
left = Entry(m1, bd = 5)
m1.add(left)
m1.add(m2)
136
m2.add(top)
mainloop()
Output:
137
File Handling Using Python GUI
In this blog, we will learn how to manage a file using python (Tkinter module).
File handling is nothing but a combination of various operations performed on the files such as opening
the file, reading the file, and writing the files. Python has a built-in function to open a file.
Now let us start a project using Python GUI for File Handling is :
138
https://github.com/Platforuma/medium_blog/blob/178ccb2a29402f2f1840b2e367c57d8504d648c6/tki
nter_filehandling.py
Tkinter is the name of the GUI library in Python. Creating a GUI application using Tkinter is an easy task,
so we used it in our project Tkinter Module.
root = Tk()
root.title(“File Handling”)
root.geometry(“500x300”)
Tk class is used to create a root window. Tkinter provides many methods, one of them is the geometry()
method. This method is used to set the dimensions of the Tkinter window and it is used to set the
position of the main window on the user desktop.
def open_file():
global text1
text1.set(“”)
if entry_window.get():
file = open(entry_window.get(),’r’)
text1.set(each)
Now come to the next line of the code where we are going to work on the function part of the GUI
project, here we define a function, the function name is open_file.In this line of the code, we define the
global variable. The name of the global variable is text1. In our previous Python GUI Project we already
better understand how global variables work. Now in this line of code, we use Set Function. Here Set
Function is used to assign the new value of the variable so here we apply Set Function on the text1
variable with a null value.
def create_file():
global text1
text1.set(“”)
if entry_window.get():
f = open(entry_window.get(), “x”)
Now come to the next line of the code, here we again define the create_file function. Here in this line of
the code, we define the global variable text1. Now again we work on the Set Function, here we define
the set function on the text1 variable with the null value. Here in this line we again define the if condition
139
where we get the data from the entry_window object. Now here we define the f variable for holding the
open new file which does not exist in any directory. Here we again Set the text1 variable value with
“Create File Successfully”.
def append_text():
global text2
text1.set(“”)
if entry_window.get():
file = open(entry_window.get(),’r’)
text1.set(each)
file3=open(entry_window.get(),”a”)
if entry_window3.get():
file3.write(entry_window3.get())
file3.close()
text1.set(“Append Successfully”)
Now in this line of the code, we again define the append_text function. The global variable name is the
text2 variable. Again we work with the Set Function, the value of the text1 variable is null. Now again we
use the if condition in our code, here we define the if condition where we get the value from the
entry_window object. Here we define the file object where the file object holds the open file in the read
mode.
Now in this line of the code, we define the for loop to read all strings in the file object. Here we again use
Set Function and set the text1 variable value from the for loop collected data. Now in this line of the
code, we define the file3 object to hold the open file in append mode.
Now in this line of the code, we define the if condition where we get the data from the entry_window3
object. In this line of the code, we perform the write operation on the file3 object. Now again use the Set
Function on the text1 variable is: “Append Successfully”.
text1 = StringVar()
text2 = StringVar()
entry_window.place(x=120,y=40)
Now in this line of the code, we define the text1 variable with the type of variable is StringVar type. Now
come to the Designing Part of the GUI window. Here we are using some Label, Entry Box and Button in a
project. So let’s start to understand the working of Label, EntryBox and Button in a project according to
the project code line by line. Now in this line of the code, we define the Entry Box.
140
btn_check = Button(root,text=”Open File”, command=open_file)
btn_check.place(x=210,y=80)
entry_window2.place(x=120,y=120, height=50)
label.place(x=120,y=175)
entry_window3.place(x=120,y=200)
Now come to the Button part of the project in this Button Method we are performing an action when we
clicked on the Button. So let’s start with how Button works in the next line of the code of the program.
Here we define a btn_check object of the Button Method on the GUI window and give the find command
on the Button for performing an action when Button clicks. What type of action performs Button it all
depends on the instruction or a condition giving on the Button function.
Now in this line of code, we have created button’s, entry and label.
btn_check1.place(x=80,y=240)
btn_check2.place(x=210,y=240)
141
btn_check3.place(x=350,y=240)
root.mainloop()
Now in this line of code, we have created button’s, entry and label. Now come to the last line of code of
the project is the main loop function that provides an infinite loop. So let’s start to understand how it
works. Here the main loop() method is an infinite loop used to run the application, using this function
window is not closed as long as.
Here we complete a full GUI Project using the Python Tkinter module and File Handling Methods.
142
Python Regex
A regular expression is a set of characters with highly specialized syntax that we can use to find or match
other characters or groups of characters. In short, regular expressions, or Regex, are widely used in the
UNIX world.
The re-module in Python gives full support for regular expressions of Pearl style. The re module raises
the re.error exception whenever an error occurs while implementing or using a regular expression.
We'll go over two crucial functions utilized to deal with regular expressions. But first, a minor point:
many letters have a particular meaning when utilized in a regular expression.
re.match()
Python's re.match() function finds and delivers the very first appearance of a regular expression pattern.
In Python, the RegEx Match function solely searches for a matching string at the beginning of the
provided text to be searched. The matching object is produced if one match is found in the first line. If a
match is found in a subsequent line, the Python RegEx Match function gives output as null.
Examine the implementation for the re.match() method in Python. The expressions ".w*" and ".w*?" will
match words that have the letter "w," and anything that does not has the letter "w" will be ignored. The
for loop is used in this Python re.match() illustration to inspect for matches for every element in the list
of words.
Matching Characters
The majority of symbols and characters will easily match. (A case-insensitive feature can be enabled,
allowing this RE to match Python or PYTHON.) The regular expression check, for instance, will match
exactly the string check.
There are some exceptions to this general rule; certain symbols are special metacharacters that don't
match. Rather, they indicate that they must compare something unusual, or they have an effect on other
parts of the RE by recurring or modifying their meaning.
1. . ^ $ * + ? { } [ ] \ | ( )
Repeating Things
The ability to match different sets of symbols will be the first feature regular expressions can achieve
that's not previously achievable with string techniques. On the other hand, Regexes isn't much of an
improvement if that had been their only extra capacity. We can also define that some sections of the RE
must be reiterated a specified number of times.
The first metacharacter we'll examine for recurring occurrences is *. Instead of matching the actual
character '*,' * signals that the preceding letter can be matched 0 or even more times, rather than
exactly one.
Ba*t, for example, matches 'bt' (zero 'a' characters), 'bat' (one 'a' character), 'baaat' (three 'a' characters),
etc.
143
Greedy repetitions, such as *, cause the matching algorithm to attempt to replicate the RE as many times
as feasible. If later elements of the sequence fail to match, the matching algorithm will retry with lesser
repetitions.
Parameters
string:- This is the string that will be compared to the pattern at the start of the string.
flags:- Bitwise OR (|) can be used to express multiple flags. These are modifications, and the table below
lists them.
Code
1. import re
4.
5. if match_object:
9. else:
Output:
re.search()
The re.search() function will look for the first occurrence of a regular expression sequence and deliver it.
It will verify all rows of the supplied string, unlike Python's re.match(). If the pattern is matched, the
re.search() function produces a match object; otherwise, it returns "null."
To execute the search() function, we must first import the Python re-module and afterward run the
program. The "sequence" and "content" to check from our primary string are passed to the Python
re.search() call.
string:- The string provided is the one that will be searched for the pattern wherever within it.
flags:- Bitwise OR (|) can be used to express multiple flags. These are modifications, and the table below
lists them.
Code
1. import re
2.
4.
6. if search_object:
10. else:
Output:
Code
1. import re
2.
4.
8. else:
10.
12. if searchObj:
14. else:
Output:
re.findall()
The findall() function is often used to look for "all" appearances of a pattern. The search() module, on the
other hand, will only provide the earliest occurrence that matches the description. In a single operation,
findall() will loop over all the rows of the document and provide all non-overlapping regular matches.
We have a line of text, and we want to get all of the occurrences from the content, so we use Python's
re.findall() function. It will search the entire content provided to it.
Using the re-package isn't always a good idea. If we're only searching a fixed string or a specific character
class, and we're not leveraging any re features like the IGNORECASE flag, regular expressions' full
capability would not be needed. Strings offer various ways for doing tasks with fixed strings, and they're
generally considerably faster than the larger, more generalized regular expression solver because the
execution is a simple short C loop that has been optimized for the job.
146
Python List
A list in Python is used to store the sequence of various types of data. Python lists are mutable type its
mean we can modify its element after it created. However, Python consists of six data-types that are
capable to store the sequences, but the most common and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the list are
separated with the comma (,) and enclosed with the square brackets [].
2. L2 = [1, 2, 3, 4, 5, 6]
IIf we try to print the type of L1, L2, and L3 using type() function then it will come out to be a list.
1. print(type(L1))
2. print(type(L2))
Output:
<class 'list'>
<class 'list'>
Characteristics of Lists
Let's check the first statement that lists are the ordered.
1. a = [1,2,"Peter",4.50,"Ricky",5,6]
2. b = [1,2,5,"Peter",4.50,"Ricky",6]
3. a ==b
Output:
False
Both lists have consisted of the same elements, but the second list changed the index position of the 5th
element that violates the order of lists. When compare both lists it returns the false.
Lists maintain the order of the element for the lifetime. That's why it is the ordered collection of objects.
147
1. a = [1, 2,"Peter", 4.50,"Ricky",5, 6]
3. a == b
Output:
True
2. Dep1 = ["CS",10]
3. Dep2 = ["IT",11]
8. print("printing departments...")
13. print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT))
Output:
printing departments...
Department 1:
Department 2:
<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>
In the above example, we have created the lists which consist of the employee and department details
and printed the corresponding details. Observe the above code to understand the concept of the list
better.
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the
second element of the list is stored at the 1st index, and so on.
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
149
1. list = [1,2,3,4,5,6,7]
2. print(list[0])
3. print(list[1])
4. print(list[2])
5. print(list[3])
7. print(list[0:6])
8. # By default the index value is 0 so its starts from the 0th element and go for index -1.
9. print(list[:])
10. print(list[2:5])
11. print(list[1:6:2])
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5]
[2, 4, 6]
Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative
indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent
left element is present at the index -2 and so on until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to access the elements of
the list.
150
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
As we discussed above, we can get an element by using negative indexing. In the above code, the first
print statement returned the rightmost element of the list. The second print statement returned the
sub-list, and so on.
Python also provides append() and insert() methods, which can be used to add values to the list.
Consider the following example to update the values inside the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
4. list[2] = 10
5. print(list)
6. # Adding multiple-element
8. print(list)
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
151
[1, 2, 10, 4, 5, 6]
The list elements can also be deleted by using the del keyword. Python also provides us
the remove() method if we do not know which element is to be deleted from the list.
1. list = [1, 2, 3, 4, 5, 6]
2. print(list)
4. list[2] = 10
5. print(list)
8. print(list)
10. list[-1] = 25
11. print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
The concatenation (+) and repetition (*) operators work in the same way as they were working with the
strings.
152
Repetition The repetition operator enables the list elements to be L1*2 = [1, 2, 3, 4, 1,
repeated multiple times. 2, 3, 4]
Concatenation It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5,
operator. 6, 7, 8]
Membership It returns true if a particular item exists in a particular list print(2 in l1) prints
otherwise false. True.
Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Output
Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as
follows.
2. for i in list:
3. # The i variable will iterate over the elements of the List and contains each element in each iter
ation.
4. print(i)
Output:
John
David
James
Jonathan
153
Adding elements to the list
Python provides append() function which is used to add an element to the list. However, the append()
function can only add value to the end of the list.
Consider the following example in which, we are taking the elements of the list from the user and
printing the list on the console.
2. l =[]
6. for i in range(0,n):
7. # The input is taken from the user and added to the list as the item
11. for i in l:
Output:
25 46 12 75 42
Example -
1. list = [0,1,2,3,4]
154
2. print("printing original list: ");
3. for i in list:
4. print(i,end=" ")
5. list.remove(2)
7. for i in list:
8. print(i,end=" ")
Output:
01234
0134
1 cmp(list1, It compares the elements of This method is not used in the Python 3 and
list2) both the lists. the above versions.
72
12
155
5 list(seq) It converts any sequence to the str = "Johnson"
list.
s = list(str)
print(type(s))
<class list>
Example: 1- Write the program to remove the duplicate element of the list.
1. list1 = [1,2,2,3,55,98,65,65,13,29]
3. list2 = []
4. for i in list1:
5. if i not in list2:
6. list2.append(i)
7. print(list2)
Output:
Example:2- Write a program to find the sum of the element in the list.
1. list1 = [3,4,5,9,10,12,24]
2. sum = 0
3. for i in list1:
4. sum = sum+i
Output:
Example: 3- Write the program to find the lists consist of at least one common element.
1. list1 = [1,2,3,4,5,6]
2. list2 = [7,8,9,2,10]
3. for x in list1:
4. for y in list2:
5. if x == y:
156
6. print("The common element is:",x)
Output:
157
Python Set
A Python set is the collection of the unordered items. Each element in the set must be unique,
immutable, and the sets remove the duplicate elements. Sets are mutable which means we can modify it
after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index. However, we can print them all together, or we can
get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
Output:
<class 'set'>
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
2. print(Days)
3. print(type(Days))
158
4. print("looping through the set elements ... ")
5. for i in Days:
6. print(i)
Output:
<class 'set'>
Friday
Wednesday
Thursday
Saturday
Monday
Tuesday
Sunday
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary,
set) can't be a member of set. Consider the following example.
3. print(type(set1))
5. set2 = {1,2,3,["Javatpoint",4]}
6. print(type(set2))
Output:
<class 'set'>
<ipython-input-5-9605bb6fbc68> in <module>
In the above code, we have created two sets, the set set1 have immutable elements and set2 have one
mutable element as a list. While checking the type of set2, it raised an error, which means set can
contain only immutable elements.
Creating an empty set is a bit different because empty curly {} braces are also used to create a dictionary
as well. So Python provides the set() method used without an argument to create an empty set.
2. set3 = {}
3. print(type(set3))
4.
6. set4 = set()
7. print(type(set4))
Output:
<class 'dict'>
<class 'set'>
Let's see what happened if we provide the duplicate element to the set.
1. set5 = {1,2,4,4,5,8,9,9,10}
Output:
In the above code, we can see that set5 consisted of multiple duplicate elements when we printed it
remove the duplicity from the set.
5. Months.add("July");
6. Months.add ("August");
8. print(Months)
11. print(i)
Output:
February
July
May
April
March
August
June
January
To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.
3. print(Months)
5. Months.update(["July","August","September","October"]);
7. print(Months);
Output:
{'January', 'February', 'April', 'August', 'October', 'May', 'June', 'July', 'September', 'March'}
Python provides the discard() method and remove() method which can be used to remove the items
from the set. The difference between these function, using discard() function if the item does not exist in
the set then the set remain unchanged whereas remove() method will through an error.
3. print(months)
5. months.discard("January");
6. months.discard("May");
8. print(months)
162
10. for i in months:
11. print(i)
Output:
February
March
April
June
Python provides also the remove() method to remove the item from the set. Consider the following
example to remove the items using remove() method.
3. print(months)
5. months.remove("January");
6. months.remove("May");
8. print(months)
Output:
We can also use the pop() method to remove the item. Generally, the pop() method will always remove
the last item but the set is unordered, we can't determine which element will be popped from set.
Consider the following example to remove the item from the set using pop() method.
3. print(Months)
5. Months.pop();
6. Months.pop();
8. print(Months)
Output:
In the above code, the last element of the Month set is March but the pop() method removed the June
and January because the set is unordered and the pop() method could not determine the last element of
the set.
Python provides the clear() method to remove all the items from the set.
164
2. print("\nprinting the original set ... ")
3. print(Months)
5. Months.clear()
7. print(Months)
Output:
set()
Despite the fact that discard() and remove() method both perform the same task, There is one main
difference between discard() and remove().
If the key to be deleted from the set using discard() doesn't exist in the set, the Python will not give the
error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in the set, the
Python will raise an error.
Example-
3. print(Months)
5. Months.discard("Feb"); #will not give an error although the key feb is not available in the set
7. print(Months)
165
8. print("\nRemoving items through remove() method...");
9. Months.remove("Jan") #will give an error as the key jan is not available in the set.
11. print(Months)
Output:
Months.remove("Jan")
KeyError: 'Jan'
166
Consider the following example to calculate the union of two sets.
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
Python also provides the union() method which can also be used to calculate the union of two sets.
Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
The intersection of two sets can be performed by the and & operator or the intersection() function. The
intersection of the two sets is given as the set of the elements that common in both sets.
167
Consider the following example.
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
168
{1,2,5}
The intersection_update() method removes the items from the original set that are not present in both
the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, the intersection() method returns a
new set.
4.
5. a.intersection_update(b, c)
6.
7. print(a)
Output:
{'castle'}
The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the
resulting set will be obtained that element of A, which is not present in the set B.
Output:
{'Thursday', 'Wednesday'}
3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
170
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we
can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is
returned depending upon the items present inside the sets.
4.
6. print (Days1>Days2)
7.
9. print (Days1<Days2)
10.
11. #prints false since Days2 and Days3 are not equivalent
Output:
True
False
171
False
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot be
changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or append the
content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is passed into this
method which is converted into the frozen set as a return type of the method.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
4. for i in Frozenset:
5. print(i);
6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation
Output:
<class 'frozenset'>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation
172
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from
the dictionary and returns a frozenset that contains the key of the dictionary as its elements.
2. print(type(Dictionary))
4. print(type(Frozenset))
5. for i in Frozenset:
6. print(i)
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
Example - 1: Write a program to remove the given number from the set.
1. my_set = {1,2,3,4,5,6,12,24}
3. my_set.discard(n)
4. print("After Removing:",my_set)
Output:
1. set1 = set([1,2,4,"John","CS"])
2. set1.update(["Apple","Mango","Grapes"])
3. print(set1)
Output:
2. set2 = set(["Peter",1,2,"Joseph"])
3. set3 = set1.union(set2)
4. print(set3)
Output:
1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{56, 23}
1. set1 = {23,44,56,67,90,45,"Javatpoint"}
2. set2 = {13,23,56,76,"Sachin"}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
Above code raised an error because frozensets are immutable and can't be changed after creation.
Example - 6: Write the program to find the issuperset, issubset and superset.
1. set1 = set(["Peter","James","Camroon","Ricky","Donald"])
2. set2 = set(["Camroon","Washington","Peter"])
3. set3 = set(["Peter"])
4.
6. print(issubset)
174
7. issuperset = set1 <= set2
8. print(issuperset)
10. print(issubset)
12. print(issuperset)
Output:
False
False
True
True
SN Method Description
4 difference_update(....) It modifies this set by removing all the items that are also
present in the specified sets.
175
7 intersection_update(....) It removes the items from the original set that are not
present in both the sets (all the sets if more than one are
specified).
176
Python Tuples
A collection of ordered and immutable objects is known as a tuple. Tuples and lists are similar as they
both are sequences. Though, tuples and lists are different because we cannot modify tuples, although we
can modify lists after creating them, and also because we use parentheses to create tuples while we use
square brackets to create lists.
Placing different values separated by commas and enclosed in parentheses forms a tuple. For instance,
Example
1. Empty_tuple = ()
We need to add a comma after the element to create a tuple of a single element.
1. Tuple_1 = (50,)
Tuple indices begin at 0, and similar to strings, we can slice them, concatenate them, and perform other
operations.
Creating a Tuple
All the objects (elements) must be enclosed in parenthesis (), each separated by a comma, to form a
tuple. Although using parenthesis is not required, it is recommended to do so.
Whatever the number of objects, even of various data types, can be included in a tuple (dictionary,
string, float, list, etc.).
Code
2.
4. empty_tuple = ()
6.
10.
177
11. # Creating a tuple having objects of different data types
14.
Output:
Empty tuple: ()
Parentheses are not mandated to build tuples. Tuple packing is the term for this.
Code
2.
3. # Creating a tuple
5.
7. print(tuple_)
8.
11.
13. try:
15. except:
178
16. print( TypeError )
Output:
<class 'tuple'>
<class 'TypeError'>
Placing just the element in parentheses is not sufficient. It will require a comma after the element to be
recognized as a tuple.
Code
2.
3. single_tuple = ("Tuple")
4. print( type(single_tuple) )
5.
7. single_tuple = ("Tuple",)
8. print( type(single_tuple) )
9.
Output:
<class 'str'>
<class 'tuple'>
<class 'tuple'>
Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts from
0.
179
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try to access
an index from the tuple that is outside the range of the tuple index. In this case, an index above 4 will be
out of range.
We cannot give an index of a floating data type or other kinds because the index in Python must be an
integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Code
2.
3. # Creating a tuple
5.
6. print(tuple_[0])
7. print(tuple_[1])
9. try:
10. print(tuple_[5])
12. print(e)
13. # trying to access elements through the index of floating data type
14. try:
15. print(tuple_[1.0])
17. print(e)
18.
21.
23. print(nested_tuple[0][3])
180
24. print(nested_tuple[1][1])
Output:
Python
Tuple
Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Code
2.
3. # Creating a tuple
5.
8.
Output:
Slicing
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
2.
3. # Creating a tuple
181
4. tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
5.
8.
11.
12. # Printing the entire tuple by using the default start and end values.
Output:
Deleting a Tuple
The elements of a tuple cannot be changed, as was already said. Therefore, we are unable to eliminate or
remove elements of a tuple.
Code
2.
3. # Creating a tuple
5.
7. try:
8. del tuple_[3]
9. print(tuple_)
11. print(e)
182
12.
13. # Deleting the variable from the global space of the program
15.
17. try:
18. print(tuple_)
20. print(e)
Output:
Code
2.
3. tuple_ = ('Python',"Tuples")
5.
7. tuple_ = tuple_ * 3
Output:
Tuple Methods
Tuple does not provide methods to add or delete elements, and there are only the following two choices.
Code
1. # Python program to show how to tuple methods (.index() and .count()) work
183
2.
3. # Creating a tuple
5.
6. # Counting the occurrence of an element of the tuple using the count() method
7. print(tuple_.count('Ordered'))
8.
10. print(tuple_.index('Ordered')) # This method returns index of the first occurrence of the element
Output:
Using the in keyword, we can determine whether an item is present in the given tuple or not.
Code
2.
3. # Creating a tuple
5.
6. # In operator
7. print('Tuple' in tuple_)
8. print('Items' in tuple_)
9.
Output:
True
184
False
False
True
Code
2.
3. # Creating a tuple
5.
8. print(item)
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
This implies that after a tuple's elements have been specified, we cannot modify them. However, we can
modify the nested elements of an element if the element itself is a mutable data type like a list.
Code
2.
3. # Creating a tuple
5.
185
6. # Trying to change the element at index 2
7. try:
8. tuple_[2] = "Items"
9. print(tuple_)
11. print( e )
12.
14. tuple_[-1][2] = 10
15. print(tuple_)
16.
19. print(tuple_)
Output:
('Python', 'Items')
To merge multiple tuples, we can use the + operator. Concatenation is the term for this.
Using the * operator, we may also repeat a tuple's elements for a specified number of times. This is
already shown above.
Code
2.
3. # Creating a tuple
5.
Tuples and lists are employed in similar contexts because of how similar they are. A tuple
implementation has several benefits over a list, though. The following are a few of the primary benefits:
o We generally employ lists for homogeneous data types and tuples for heterogeneous data types.
o Tuple iteration is quicker than list iteration because tuples are immutable. There is such a modest
performance improvement.
o Tuples with immutable components can function as the key for a Python dictionary object. This
feature is not feasible with lists.
o Collecting data in a tuple will ensure that it stays write-protected if it never changes.
187
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in
Python, which can simulate the real-life data arrangement where some specific value exists for some
particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values.
In other words, we can say that a dictionary is the collection of key-value pairs where the value can be
any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets {}, and
each key is separated from its value by the colon (:).The syntax to define the dictionary is given below.
Syntax:
In the above dictionary Dict, The keys Name and Age are the string that is an immutable object.
2. print(type(Employee))
4. print(Employee)
Output
<class 'dict'>
Python provides the built-in function dict() method which is also used to create dictionary. The empty
curly braces {} is used to create empty dictionary.
2. Dict = {}
4. print(Dict)
5.
6. # Creating a Dictionary
188
7. # with dict() method
10. print(Dict)
11.
16. print(Dict)
Output:
Empty Dictionary:
{}
We have discussed how the data can be accessed in the list and tuple by using the indexing.
However, the values can be accessed in the dictionary by using the keys as keys are unique in the
dictionary.
2. print(type(Employee))
Output:
<class 'dict'>
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Python provides us with an alternative to use the get() method to access the dictionary values. It would
give the same result as given by the indexing.
Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys
added in the dictionary.
Example - 1:
2. Dict = {}
4. print(Dict)
5.
7. Dict[0] = 'Peter'
8. Dict[2] = 'Joseph'
9. Dict[3] = 'Ricky'
11. print(Dict)
12.
190
14. # with a single Key
18. print(Dict)
19.
23. print(Dict)
Output:
Empty Dictionary:
{}
Example - 2:
2. print(type(Employee))
4. print(Employee)
191
7. Employee["Age"] = int(input("Age: "));
9. Employee["Company"] = input("Company:");
11. print(Employee)
Output:
Empty Dictionary:
{}
2. print(type(Employee))
4. print(Employee)
6. del Employee["Name"]
7. del Employee["Company"]
9. print(Employee)
13. print(Employee)
Output:
<class 'dict'>
The last print statement in the above code, it raised an error because we tried to print the Employee
dictionary that already deleted.
The pop() method accepts the key as an argument and remove the associated value. Consider the
following example.
1. # Creating a Dictionary
3. # Deleting a key
5. pop_ele = Dict.pop(3)
6. print(Dict)
Output:
Python also provides a built-in methods popitem() and clear() method for remove elements from the
dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method
removes all elements to the whole dictionary.
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
193
# for loop to print all the keys of a dictionary
2. for x in Employee:
3. print(x)
Output:
Name
Age
salary
Company
Example 2
2. for x in Employee:
3. print(Employee[x])
Output:
John
29
25000
Example - 3
#for loop to print the values of the dictionary by using values() method.
2. for x in Employee.values():
3. print(x)
Output:
John
29
25000
194
Example 4
#for loop to print the items of the dictionary by using items() method.
2. for x in Employee.items():
3. print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value
for a single key, then the value which is last assigned is considered as the value of the key.
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name":"John"}
3. print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE
2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key,
but we cannot use any mutable object like the list as the key in the dictionary.
3. print(x,y)
Output:
195
Traceback (most recent call last):
SN Function Description
1 cmp(dict1, It compares the items of both the dictionary and returns true if the first
dict2) dictionary values are greater than the second dictionary, otherwise it returns
false.
The built-in python dictionary methods along with the description are given below.
SN Method Description
3 dict.fromkeys(iterable, value = Create a new dictionary from the iterable with the values
None, /) equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
196
6 dict.items() It returns all the key-value pairs as a tuple.
8 dict.setdefault(key,default= It is used to set the key to the default value if the key is not
"None") specified in the dictionary
11 len()
12 popItem()
13 pop()
14 count()
15 index()
197
Python NumPy Project
NumPy Project
Our Python NumPy Project provides the basic and advanced concepts of the NumPy. Our NumPy project
is designed for beginners and professionals.
NumPy stands for numeric python which is a python package for the computation and processing of the
multidimensional and single dimensional array elements.
What is NumPy
NumPy stands for numeric python which is a python package for the computation and processing of the
multidimensional and single dimensional array elements.
Travis Oliphant created NumPy package in 2005 by injecting the features of the ancestor module
Numeric into another module Numarray.
It is an extension module of Python which is mostly written in C. It provides various functions which are
capable of performing the numeric computations with a high speed.
NumPy provides various powerful data structures, implementing multi-dimensional arrays and matrices.
These data structures are used for the optimal computations regarding arrays and matrices.
NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also very
convenient with Matrix multiplication and data reshaping. NumPy is fast which makes it reasonable to
work with a large set of data.
There are the following advantages of using NumPy for data analysis.
198
NumPy performs array-oriented computing.
It efficiently implements the multidimensional arrays.
It is capable of performing Fourier Transform and reshaping the data stored in multidimensional arrays.
NumPy provides the in-built functions for linear algebra and random number generation.
Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the replacement to MATLAB as
Python is more complete and easier programming language than MATLAB.
199
Python with Databases
SQLite databases
Source code: Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate
server process and allows accessing the database using a nonstandard variant of the SQL query language.
Some applications can use SQLite for internal data storage. It’s also possible to prototype an application
using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interface compliant with the
DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
See also
https://www.sqlite.org
The SQLite web page; the documentation describes the syntax and the available data types for the
supported SQL dialect.
https://www.w3schools.com/sql/
Here, you will create a database of Monty Python movies using basic sqlite3 functionality. It assumes a
fundamental understanding of database concepts, including cursors and transactions.
First, we need to create a new database and open a database connection to allow sqlite3 to work with it.
Call sqlite3.connect() to to create a connection to the database tutorial.db in the current working
directory, implicitly creating it if it does not exist:
import sqlite3
con = sqlite3.connect("tutorial.db")
The returned Connection object con represents the connection to the on-disk database.
In order to execute SQL statements and fetch results from SQL queries, we will need to use a database
cursor. Call con.cursor() to create the Cursor:
cur = con.cursor()
200
Now that we’ve got a database connection and a cursor, we can create a database table movie with
columns for title, release year, and review score. For simplicity, we can just use column names in the
table declaration – thanks to the flexible typing feature of SQLite, specifying the data types is optional.
Execute the CREATE TABLE statement by calling cur.execute(...):
We can verify that the new table has been created by querying the sqlite_master table built-in to SQLite,
which should now contain an entry for the movie table definition (see The Schema Table for details).
Execute that query by calling cur.execute(...), assign the result to res, and call res.fetchone() to fetch the
resulting row:
>>>
>>> res.fetchone()
('movie',)
We can see that the table has been created, as the query returns a tuple containing the table’s name. If
we query sqlite_master for a non-existent table spam, res.fetchone() will return None:
>>>
True
Now, add two rows of data supplied as SQL literals by executing an INSERT statement, once again by
calling cur.execute(...):
cur.execute("""
""")
The INSERT statement implicitly opens a transaction, which needs to be committed before changes are
saved in the database (see Transaction control for details). Call con.commit() on the connection object to
commit the transaction:
con.commit()
We can verify that the data was inserted correctly by executing a SELECT query. Use the
now-familiar cur.execute(...) to assign the result to res, and call res.fetchall() to return all resulting rows:
>>>
201
>>> res = cur.execute("SELECT score FROM movie")
>>> res.fetchall()
[(8.2,), (7.5,)]
The result is a list of two tuples, one per row, each containing that row’s score value.
data = [
Notice that ? placeholders are used to bind data to the query. Always use placeholders instead of string
formatting to bind Python values to SQL statements, to avoid SQL injection attacks (see How to use
placeholders to bind values in SQL queries for more details).
We can verify that the new rows were inserted by executing a SELECT query, this time iterating over the
results of the query:
>>>
>>> for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
... print(row)
Each row is a two-item tuple of (year, title), matching the columns selected in the query.
Finally, verify that the database has been written to disk by calling con.close() to close the existing
connection, opening a new one, creating a new cursor, then querying the database:
>>>
>>> con.close()
>>> res = new_cur.execute("SELECT title, year FROM movie ORDER BY score DESC")
>>> print(f'The highest scoring Monty Python movie is {title!r}, released in {year}')
The highest scoring Monty Python movie is 'Monty Python and the Holy Grail', released in 1975
You’ve now created an SQLite database using the sqlite3 module, inserted data and retrieved values from
it in multiple ways.
See also
Reference
Module functions
sqlite3.connect(database, timeout=5.0, detect_types=0, isolation_level='DEFERRED', check_same_thread
=True, factory=sqlite3.Connection, cached_statements=128, uri=False)
● database (path-like object) – The path to the database file to be opened. Pass ":memory:" to
open a connection to a database that is in RAM instead of on disk.
● timeout (float) – How many seconds the connection should wait before raising an exception, if
the database is locked by another connection. If another connection opens a transaction to
modify the database, it will be locked until that transaction is committed. Default five seconds.
● detect_types (int) – Control whether and how data types not natively supported by SQLite are
looked up to be converted to Python types, using the converters registered
with register_converter(). Set it to any combination (using |, bitwise or)
of PARSE_DECLTYPES and PARSE_COLNAMES to enable this. Column names takes precedence
over declared types if both flags are set. Types cannot be detected for generated fields (for
example max(data)), even when the detect_types parameter is set; str will be returned instead.
By default (0), type detection is disabled.
203
● isolation_level (str | None) – The isolation_level of the connection, controlling whether and how
transactions are implicitly opened. Can be "DEFERRED" (default), "EXCLUSIVE" or "IMMEDIATE";
or None to disable opening transactions implicitly. See Transaction control for more.
● check_same_thread (bool) – If True (default), only the creating thread may use the connection.
If False, the connection may be shared across multiple threads; if so, write operations should be
serialized by the user to avoid data corruption.
● factory (Connection) – A custom subclass of Connection to create the connection with, if not the
default Connection class.
● cached_statements (int) – The number of statements that sqlite3 should internally cache for this
connection, to avoid parsing overhead. By default, 128 statements.
● uri (bool) – If set to True, database is interpreted as a URI with a file path and an optional query
string. The scheme part must be "file:", and the path can be relative or absolute. The query string
allows passing parameters to SQLite, enabling various How to work with SQLite URIs.
Return type
Connection
Raises an auditing event sqlite3.connect with argument database.
Changed in version 3.7: database can now also be a path-like object, not only a string.
sqlite3.complete_statement(statement)
Return True if the string statement appears to contain one or more complete SQL statements. No
syntactic verification or parsing of any kind is performed, other than checking that there are no unclosed
string literals and the statement is terminated by a semicolon.
For example:
>>>
True
False
This function may be useful during command-line input to determine if the entered text seems to form a
complete SQL statement, or if additional input is needed before calling execute().
sqlite3.enable_callback_tracebacks(flag, /)
204
Enable or disable callback tracebacks. By default you will not get any tracebacks in user-defined
functions, aggregates, converters, authorizer callbacks etc. If you want to debug them, you can call this
function with flag set to True. Afterwards, you will get tracebacks from callbacks on sys.stderr.
Use False to disable the feature again.
>>>
>>> sqlite3.enable_callback_tracebacks(True)
... 5/0
>>> con.set_trace_callback(evil_trace)
sqlite3.register_adapter(type, adapter, /)
Register an adapter callable to adapt the Python type type into an SQLite type. The adapter is called with
a Python object of type type as its sole argument, and must return a value of a type that SQLite natively
understands.
sqlite3.register_converter(typename, converter, /)
Register the converter callable to convert SQLite objects of type typename into a Python object of a
specific type. The converter is invoked for all SQLite values of type typename; it is passed a bytes object
and should return an object of the desired Python type. Consult the
parameter detect_types of connect() for information regarding how type detection works.
Note: typename and the name of the type in your query are matched case-insensitively.
Module constants
sqlite3.PARSE_COLNAMES
205
Pass this flag value to the detect_types parameter of connect() to look up a converter function by using
the type name, parsed from the query column name, as the converter dictionary key. The type name
must be wrapped in square brackets ([]).
This flag may be combined with PARSE_DECLTYPES using the | (bitwise or) operator.
sqlite3.PARSE_DECLTYPES
Pass this flag value to the detect_types parameter of connect() to look up a converter function using the
declared types for each column. The types are declared when the database table is created. sqlite3 will
look up a converter function using the first word of the declared type as the converter dictionary key. For
example:
This flag may be combined with PARSE_COLNAMES using the | (bitwise or) operator.
sqlite3.SQLITE_OK
sqlite3.SQLITE_DENY
sqlite3.SQLITE_IGNORE
sqlite3.apilevel
String constant stating the supported DB-API level. Required by the DB-API. Hard-coded to "2.0".
sqlite3.paramstyle
String constant stating the type of parameter marker formatting expected by the sqlite3 module.
Required by the DB-API. Hard-coded to "qmark".
Note
sqlite3.sqlite_version_info
sqlite3.threadsafety
Integer constant required by the DB-API 2.0, stating the level of thread safety the sqlite3 module
supports. This attribute is set based on the default threading mode the underlying SQLite library is
compiled with. The SQLite threading modes are:
1. Single-thread: In this mode, all mutexes are disabled and SQLite is unsafe to use in more than a
single thread at once.
2. Multi-thread: In this mode, SQLite can be safely used by multiple threads provided that no single
database connection is used simultaneously in two or more threads.
3. Serialized: In serialized mode, SQLite can be safely used by multiple threads with no restriction.
The mappings from SQLite threading modes to DB-API 2.0 threadsafety levels are as follows:
SQLite
threadsafety SQLITE_THREADSAFE DB-API 2.0 meaning
threading mode
sqlite3.version
Version number of this module as a string. This is not the version of the SQLite library.
sqlite3.version_info
Version number of this module as a tuple of integers. This is not the version of the SQLite library.
Connection objects
class sqlite3.Connection
207
See also
cursor(factory=Cursor)
Create and return a Cursor object. The cursor method accepts a single optional parameter factory. If
supplied, this must be a callable returning an instance of Cursor or its subclasses.
Parameters
● table (str) – The name of the table where the blob is located.
● column (str) – The name of the column where the blob is located.
● row (str) – The name of the row where the blob is located.
● readonly (bool) – Set to True if the blob should be opened without write permissions. Defaults
to False.
● name (str) – The name of the database where the blob is located. Defaults to "main".
Raises
Return type
Blob
Note
The blob size cannot be changed using the Blob class. Use the SQL function zeroblob to create a blob
with a fixed size.
commit()
Commit any pending transaction to the database. If there is no open transaction, this method is a no-op.
rollback()
Roll back to the start of any pending transaction. If there is no open transaction, this method is a no-op.
close()
208
Close the database connection. Any pending transaction is not committed implicitly; make sure
to commit() before closing to avoid losing pending changes.
execute(sql, parameters=(), /)
Create a new Cursor object and call execute() on it with the given sql and parameters. Return the new
cursor object.
executemany(sql, parameters, /)
Create a new Cursor object and call executemany() on it with the given sql and parameters. Return the
new cursor object.
executescript(sql_script, /)
Create a new Cursor object and call executescript() on it with the given sql_script. Return the new cursor
object.
Parameters
● narg (int) – The number of arguments the SQL function can accept. If -1, it may take any number
of arguments.
● func (callback | None) – A callable that is called when the SQL function is invoked. The callable
must return a type natively supported by SQLite. Set to None to remove an existing SQL function.
● deterministic (bool) – If True, the created SQL function is marked as deterministic, which allows
SQLite to perform additional optimizations.
Raises
Example:
>>>
('acbd18db4cc2f85cedef654fccc4a4d8',)
Parameters
● n_arg (int) – The number of arguments the SQL aggregate function can accept. If -1, it may take
any number of arguments.
o finalize(): Return the final result of the aggregate as a type natively supported by SQLite.
The number of arguments that the step() method must accept is controlled by n_arg.
Example:
class MySum:
def __init__(self):
self.count = 0
self.count += value
def finalize(self):
return self.count
con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
print(cur.fetchone()[0])
con.close()
Parameters
● name (str) – The name of the SQL aggregate window function to create or remove.
● num_params (int) – The number of arguments the SQL aggregate window function can accept.
If -1, it may take any number of arguments.
o finalize(): Return the final result of the aggregate as a type natively supported by SQLite.
The number of arguments that the step() and value() methods must accept is controlled by num_params.
Raises
NotSupportedError – If used with a version of SQLite older than 3.25.0, which does not support
aggregate window functions.
Example:
class WindowSumInt:
def __init__(self):
self.count = 0
211
self.count += value
def value(self):
return self.count
self.count -= value
def finalize(self):
"""
return self.count
con = sqlite3.connect(":memory:")
values = [
("a", 4),
("b", 5),
("c", 3),
("d", 8),
("e", 1),
con.create_window_function("sumint", 1, WindowSumInt)
212
cur.execute("""
) AS sum_y
""")
print(cur.fetchall())
create_collation(name, callable)
Create a collation named name using the collating function callable. callable is passed
two string arguments, and it should return an integer:
if string1 == string2:
return 0
return 1
else:
return -1
con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)
print(row)
213
con.close()
Changed in version 3.11: The collation name can contain any Unicode character. Earlier, only ASCII
characters were allowed.
interrupt()
Call this method from a different thread to abort any queries that might be executing on the connection.
Aborted queries will raise an exception.
set_authorizer(authorizer_callback)
Register callable authorizer_callback to be invoked for each attempt to access a column of a table in the
database. The callback should return one of SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE to signal how
access to the column should be handled by the underlying SQLite library.
The first argument to the callback signifies what kind of operation is to be authorized. The second and
third argument will be arguments or None depending on the first argument. The 4th argument is the
name of the database (“main”, “temp”, etc.) if applicable. The 5th argument is the name of the
inner-most trigger or view that is responsible for the access attempt or None if this access attempt is
directly from input SQL code.
Please consult the SQLite documentation about the possible values for the first argument and the
meaning of the second and third argument depending on the first one. All necessary constants are
available in the sqlite3 module.
Changed in version 3.11: Added support for disabling the authorizer using None.
set_progress_handler(progress_handler, n)
Register callable progress_handler to be invoked for every n instructions of the SQLite virtual machine.
This is useful if you want to get called from SQLite during long-running operations, for example to update
a GUI.
If you want to clear any previously installed progress handler, call the method
with None for progress_handler.
Returning a non-zero value from the handler function will terminate the currently executing query and
cause it to raise an OperationalError exception.
set_trace_callback(trace_callback)
Register callable trace_callback to be invoked for each SQL statement that is actually executed by the
SQLite backend.
The only argument passed to the callback is the statement (as str) that is being executed. The return
value of the callback is ignored. Note that the backend does not only run statements passed to
the Cursor.execute() methods. Other sources include the transaction management of the sqlite3 module
and the execution of triggers defined in the current database.
214
Passing None as trace_callback will disable the trace callback.
Note
Exceptions raised in the trace callback are not propagated. As a development and debugging aid,
use enable_callback_tracebacks() to enable printing tracebacks from exceptions raised in the trace
callback.
enable_load_extension(enabled, /)
Enable the SQLite engine to load SQLite extensions from shared libraries if enabled is True; else, disallow
loading SQLite extensions. SQLite extensions can define new functions, aggregates or whole new virtual
table implementations. One well-known extension is the fulltext-search extension distributed with
SQLite.
Note
The sqlite3 module is not built with loadable extension support by default, because some platforms
(notably macOS) have SQLite libraries which are compiled without this feature. To get loadable extension
support, you must pass the --enable-loadable-sqlite-extensions option to configure.
con.enable_load_extension(True)
con.execute("select load_extension('./fts3.so')")
# con.load_extension("./fts3.so")
con.enable_load_extension(False)
con.executescript("""
INSERT INTO recipe (name, ingredients) VALUES('broccoli stew', 'broccoli peppers cheese tomatoes');
INSERT INTO recipe (name, ingredients) VALUES('pumpkin stew', 'pumpkin onions garlic celery');
INSERT INTO recipe (name, ingredients) VALUES('broccoli pie', 'broccoli cheese onions flour');
INSERT INTO recipe (name, ingredients) VALUES('pumpkin pie', 'pumpkin sugar flour butter');
""")
for row in con.execute("SELECT rowid, name, ingredients FROM recipe WHERE name MATCH 'pie'"):
print(row)
con.close()
load_extension(path, /)
Load an SQLite extension from a shared library located at path. Enable extension loading
with enable_load_extension() before calling this method.
iterdump()
Return an iterator to dump the database as SQL source code. Useful when saving an in-memory database
for later restoration. Similar to the .dump command in the sqlite3 shell.
Example:
con = sqlite3.connect('example.db')
f.write('%s\n' % line)
con.close()
Works even if the database is being accessed by other clients or concurrently by the same connection.
216
Parameters
● pages (int) – The number of pages to copy at a time. If equal to or less than 0, the entire
database is copied in a single step. Defaults to -1.
● progress (callback | None) – If set to a callable, it is invoked with three integer arguments for
every backup iteration: the status of the last iteration, the remaining number of pages still to be
copied, and the total number of pages. Defaults to None.
● name (str) – The name of the database to back up. Either "main" (the default) for the main
database, "temp" for the temporary database, or the name of a custom database as attached
using the ATTACH DATABASE SQL statement.
● sleep (float) – The number of seconds to sleep between successive attempts to back up
remaining pages.
src = sqlite3.connect('example.db')
dst = sqlite3.connect('backup.db')
with dst:
dst.close()
src.close()
src = sqlite3.connect('example.db')
dst = sqlite3.connect(':memory:')
src.backup(dst)
getlimit(category, /)
Parameters
217
Return type
int
Raises
Example, query the maximum length of an SQL statement for Connection con (the default is
1000000000):
>>>
>>> con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH)
1000000000
setlimit(category, limit, /)
Set a connection runtime limit. Attempts to increase a limit above its hard upper bound are silently
truncated to the hard upper bound. Regardless of whether or not the limit was changed, the prior value
of the limit is returned.
Parameters
● limit (int) – The value of the new limit. If negative, the current limit is unchanged.
Return type
int
Raises
Example, limit the number of attached databases to 1 for Connection con (the default limit is 10):
>>>
>>> con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 1)
10
>>> con.getlimit(sqlite3.SQLITE_LIMIT_ATTACHED)
serialize(*, name='main')
218
Serialize a database into a bytes object. For an ordinary on-disk database file, the serialization is just a
copy of the disk file. For an in-memory database or a “temp” database, the serialization is the same
sequence of bytes which would be written to disk if that database were backed up to disk.
Parameters
Return type
bytes
Note
This method is only available if the underlying SQLite library has the serialize API.
deserialize(data, /, *, name='main')
Deserialize a serialized database into a Connection. This method causes the database connection to
disconnect from database name, and reopen name as an in-memory database based on the serialization
contained in data.
Parameters
Raises
Note
This method is only available if the underlying SQLite library has the deserialize API.
in_transaction
219
isolation_level
This attribute controls the transaction handling performed by sqlite3. If set to None, transactions are
never implicitly opened. If set to one of "DEFERRED", "IMMEDIATE", or "EXCLUSIVE", corresponding to
the underlying SQLite transaction behaviour, implicit transaction management is performed.
If not overridden by the isolation_level parameter of connect(), the default is "", which is an alias
for "DEFERRED".
row_factory
The initial row_factory for Cursor objects created from this connection. Assigning to this attribute does
not affect the row_factory of existing cursors belonging to this connection, only new ones. Is None by
default, meaning each row is returned as a tuple.
See How to create and use row factories for more details.
text_factory
A callable that accepts a bytes parameter and returns a text representation of it. The callable is invoked
for SQLite values with the TEXT data type. By default, this attribute is set to str. If you want to
return bytes instead, set text_factory to bytes.
Example:
con = sqlite3.connect(":memory:")
cur = con.cursor()
AUSTRIA = "Österreich"
row = cur.fetchone()
con.text_factory = bytes
row = cur.fetchone()
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
220
# database ...
row = cur.fetchone()
con.close()
total_changes
Return the total number of database rows that have been modified, inserted, or deleted since the
database connection was opened.
Cursor objects
A Cursor object represents a database cursor which is used to execute SQL statements, and manage the
context of a fetch operation. Cursors are created using Connection.cursor(), or by using any of
the connection shortcut methods.
Cursor objects are iterators, meaning that if you execute() a SELECT query, you can simply iterate over
the cursor to fetch the resulting rows:
print(row)
class sqlite3.Cursor
execute(sql, parameters=(), /)
Execute SQL statement sql. Bind values to the statement using placeholders that map to
the sequence or dict parameters.
execute() will only execute a single SQL statement. If you try to execute more than one statement with it,
it will raise a ProgrammingError. Use executescript() if you want to execute multiple SQL statements with
one call.
If isolation_level is not None, sql is an INSERT, UPDATE, DELETE, or REPLACE statement, and there is no
open transaction, a transaction is implicitly opened before executing sql.
221
executemany(sql, parameters, /)
Execute parameterized SQL statement sql against all parameter sequences or mappings found in the
sequence parameters. It is also possible to use an iterator yielding parameters instead of a sequence.
Uses the same implicit transaction handling as execute().
Example:
rows = [
("row1",),
("row2",),
executescript(sql_script, /)
Execute the SQL statements in sql_script. If there is a pending transaction, an implicit COMMIT statement
is executed first. No other implicit transaction control is performed; any transaction control must be
added to sql_script.
Example:
cur.executescript("""
BEGIN;
COMMIT;
""")
fetchone()
If row_factory is None, return the next row query result set as a tuple. Else, pass it to the row factory and
return its result. Return None if no more data is available.
fetchmany(size=cursor.arraysize)
Return the next set of rows of a query result as a list. Return an empty list if no more rows are available.
222
The number of rows to fetch per call is specified by the size parameter. If size is not
given, arraysize determines the number of rows to be fetched. If fewer than size rows are available, as
many rows as are available are returned.
Note there are performance considerations involved with the size parameter. For optimal performance, it
is usually best to use the arraysize attribute. If the size parameter is used, then it is best for it to retain
the same value from one fetchmany() call to the next.
fetchall()
Return all (remaining) rows of a query result as a list. Return an empty list if no rows are available. Note
that the arraysize attribute can affect the performance of this operation.
close()
The cursor will be unusable from this point forward; a ProgrammingError exception will be raised if any
operation is attempted with the cursor.
setinputsizes(sizes, /)
setoutputsize(size, column=None, /)
arraysize
Read/write attribute that controls the number of rows returned by fetchmany(). The default value is 1
which means a single row would be fetched per call.
connection
Read-only attribute that provides the SQLite database Connection belonging to the cursor.
A Cursor object created by calling con.cursor() will have a connection attribute that refers to con:
>>>
True
description
Read-only attribute that provides the column names of the last query. To remain compatible with the
Python DB API, it returns a 7-tuple for each column where the last six items of each tuple are None.
lastrowid
223
Read-only attribute that provides the row id of the last inserted row. It is only updated after
successful INSERT or REPLACE statements using the execute() method. For other statements,
after executemany() or executescript(), or if the insertion failed, the value of lastrowid is left unchanged.
The initial value of lastrowid is None.
Note
rowcount
Read-only attribute that provides the number of modified rows for INSERT, UPDATE, DELETE,
and REPLACE statements; is -1 for other statements, including CTE queries. It is only updated by
the execute() and executemany() methods.
row_factory
Control how a row fetched from this Cursor is represented. If None, a row is represented as a tuple. Can
be set to the included sqlite3.Row; or a callable that accepts two arguments, a Cursor object and
the tuple of row values, and returns a custom object representing an SQLite row.
Defaults to what Connection.row_factory was set to when the Cursor was created. Assigning to this
attribute does not affect Connection.row_factory of the parent connection.
See How to create and use row factories for more details.
Row objects
class sqlite3.Row
A Row instance serves as a highly optimized row_factory for Connection objects. It supports iteration,
equality testing, len(), and mapping access by column name and index.
Two Row objects compare equal if they have identical column names and values.
See How to create and use row factories for more details.
keys()
Return a list of column names as strings. Immediately after a query, it is the first member of each tuple
in Cursor.description.
Blob objects
class sqlite3.Blob
224
A Blob instance is a file-like object that can read and write data in an SQLite BLOB. Call len(blob) to get
the size (number of bytes) of the blob. Use indices and slices for direct access to the blob data.
Use the Blob as a context manager to ensure that the blob handle is closed after use.
con = sqlite3.connect(":memory:")
blob.write(b"hello, ")
blob.write(b"world.")
blob[0] = ord("H")
blob[-1] = ord("!")
greeting = blob.read()
close()
The blob will be unusable from this point onward. An Error (or subclass) exception will be raised if any
further operation is attempted with the blob.
read(length=- 1, /)
Read length bytes of data from the blob at the current offset position. If the end of the blob is reached,
the data up to EOF will be returned. When length is not specified, or is negative, read() will read until the
end of the blob.
write(data, /)
Write data to the blob at the current offset. This function cannot change the blob length. Writing beyond
the end of the blob will raise ValueError.
225
tell()
seek(offset, origin=os.SEEK_SET, /)
Set the current access position of the blob to offset. The origin argument defaults
to os.SEEK_SET (absolute blob positioning). Other values for origin are os.SEEK_CUR (seek relative to the
current position) and os.SEEK_END (seek relative to the blob’s end).
PrepareProtocol objects
class sqlite3.PrepareProtocol
The PrepareProtocol type’s single purpose is to act as a PEP 246 style adaption protocol for objects that
can adapt themselves to native SQLite types.
Exceptions
exception sqlite3.Warning
This exception is not currently raised by the sqlite3 module, but may be raised by applications
using sqlite3, for example if a user-defined function truncates data while inserting. Warning is a subclass
of Exception.
exception sqlite3.Error
The base class of the other exceptions in this module. Use this to catch all errors with one
single except statement. Error is a subclass of Exception.
If the exception originated from within the SQLite library, the following two attributes are added to the
exception:
sqlite_errorcode
sqlite_errorname
The symbolic name of the numeric error code from the SQLite API
exception sqlite3.InterfaceError
Exception raised for misuse of the low-level SQLite C API. In other words, if this exception is raised, it
probably indicates a bug in the sqlite3 module. InterfaceError is a subclass of Error.
exception sqlite3.DatabaseError
226
Exception raised for errors that are related to the database. This serves as the base exception for several
types of database errors. It is only raised implicitly through the specialised subclasses. DatabaseError is a
subclass of Error.
exception sqlite3.DataError
Exception raised for errors caused by problems with the processed data, like numeric values out of range,
and strings which are too long. DataError is a subclass of DatabaseError.
exception sqlite3.OperationalError
Exception raised for errors that are related to the database’s operation, and not necessarily under the
control of the programmer. For example, the database path is not found, or a transaction could not be
processed. OperationalError is a subclass of DatabaseError.
exception sqlite3.IntegrityError
Exception raised when the relational integrity of the database is affected, e.g. a foreign key check fails. It
is a subclass of DatabaseError.
exception sqlite3.InternalError
Exception raised when SQLite encounters an internal error. If this is raised, it may indicate that there is a
problem with the runtime SQLite library. InternalError is a subclass of DatabaseError.
exception sqlite3.ProgrammingError
Exception raised for sqlite3 API programming errors, for example supplying the wrong number of
bindings to a query, or trying to operate on a closed Connection. ProgrammingError is a subclass
of DatabaseError.
exception sqlite3.NotSupportedError
Exception raised in case a method or database API is not supported by the underlying SQLite library. For
example, setting deterministic to True in create_function(), if the underlying SQLite library does not
support deterministic functions. NotSupportedError is a subclass of DatabaseError.
The following Python types can thus be sent to SQLite without any problem:
227
The type system of the sqlite3 module is extensible in two ways: you can store additional Python types in
an SQLite database via object adapters, and you can let the sqlite3 module convert SQLite types to
Python types via converters.
The default converters are registered under the name “date” for datetime.date and under the name
“timestamp” for datetime.datetime.
This way, you can use date/timestamps from Python without any additional fiddling in most cases. The
format of the adapters is also compatible with the experimental SQLite date/time functions.
import sqlite3
import datetime
228
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
today = datetime.date.today()
now = datetime.datetime.now()
row = cur.fetchone()
row = cur.fetchone()
con.close()
If a timestamp stored in SQLite has a fractional part longer than 6 numbers, its value will be truncated to
microsecond precision by the timestamp converter.
Note
The default “timestamp” converter ignores UTC offsets in the database and always returns a
naive datetime.datetime object. To preserve UTC offsets in timestamps, either leave converters disabled,
or register an offset-aware converter with register_converter().
How-to guides
229
SQL operations usually need to use values from Python variables. However, beware of using Python’s
string operations to assemble queries, as they are vulnerable to SQL injection attacks. For example, an
attacker can simply close the single quote and inject OR TRUE to select all rows:
>>>
' OR TRUE; --
>>> print(sql)
>>> cur.execute(sql)
Instead, use the DB-API’s parameter substitution. To insert a variable into a query string, use a
placeholder in the string, and substitute the actual values into the query by providing them as a tuple of
values to the second argument of the cursor’s execute() method. An SQL statement may use one of two
kinds of placeholders: question marks (qmark style) or named placeholders (named style). For the qmark
style, parameters must be a sequence. For the named style, it can be either a sequence or dict instance.
The length of the sequence must match the number of placeholders, or a ProgrammingError is raised. If
a dict is given, it must contain keys for all named parameters. Any extra items are ignored. Here’s an
example of both styles:
con = sqlite3.connect(":memory:")
lang_list = [
("Fortran", 1957),
("Python", 1991),
("Go", 2009),
230
# And this is the named style:
print(cur.fetchall())
SQLite supports only a limited set of data types natively. To store custom Python types in SQLite
databases, adapt them to one of the Python types SQLite natively understands.
There are two ways to adapt Python objects to SQLite types: letting your object adapt itself, or using
an adapter callable. The latter will take precedence above the former. For a library that exports a custom
type, it may make sense to enable that type to adapt itself. As an application developer, it may make
more sense to take direct control by registering custom adapter functions.
class Point:
self.x, self.y = x, y
if protocol is sqlite3.PrepareProtocol:
return f"{self.x};{self.y}"
con = sqlite3.connect(":memory:")
cur = con.cursor()
print(cur.fetchone()[0])
The other possibility is to create a function that converts the Python object to an SQLite-compatible type.
This function can then be registered using register_adapter().
class Point:
231
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_point(point):
return f"{point.x};{point.y}"
sqlite3.register_adapter(Point, adapt_point)
con = sqlite3.connect(":memory:")
cur = con.cursor()
print(cur.fetchone()[0])
Writing an adapter lets you convert from custom Python types to SQLite values. To be able to
convert from SQLite values to custom Python types, we use converters.
Let’s go back to the Point class. We stored the x and y coordinates separated via semicolons as strings in
SQLite.
First, we’ll define a converter function that accepts the string as a parameter and constructs
a Point object from it.
Note
Converter functions are always passed a bytes object, no matter the underlying SQLite data type.
def convert_point(s):
x, y = map(float, s.split(b";"))
return Point(x, y)
We now need to tell sqlite3 when it should convert a given SQLite value. This is done when connecting to
a database, using the detect_types parameter of connect(). There are three options:
232
● Both: set detect_types to sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES. Column names
take precedence over declared types.
class Point:
self.x, self.y = x, y
def __repr__(self):
def adapt_point(point):
return f"{point.x};{point.y}"
def convert_point(s):
x, y = list(map(float, s.split(b";")))
return Point(x, y)
sqlite3.register_adapter(Point, adapt_point)
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
cur.close()
233
con.close()
import datetime
import sqlite3
def adapt_date_iso(val):
return val.isoformat()
def adapt_datetime_iso(val):
return val.isoformat()
def adapt_datetime_epoch(val):
return int(val.timestamp())
sqlite3.register_adapter(datetime.date, adapt_date_iso)
sqlite3.register_adapter(datetime.datetime, adapt_datetime_iso)
sqlite3.register_adapter(datetime.datetime, adapt_datetime_epoch)
234
def convert_date(val):
return datetime.date.fromisoformat(val.decode())
def convert_datetime(val):
return datetime.datetime.fromisoformat(val.decode())
def convert_timestamp(val):
return datetime.datetime.fromtimestamp(int(val))
sqlite3.register_converter("date", convert_date)
sqlite3.register_converter("datetime", convert_datetime)
sqlite3.register_converter("timestamp", convert_timestamp)
Using the execute(), executemany(), and executescript() methods of the Connection class, your code can
be written more concisely because you don’t have to create the (often superfluous) Cursor objects
explicitly. Instead, the Cursor objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a SELECT statement and iterate over it directly using only a single call
on the Connection object.
con = sqlite3.connect(":memory:")
data = [
("C++", 1985),
("Objective-C", 1984),
235
# Print the table contents
print(row)
con.close()
A Connection object can be used as a context manager that automatically commits or rolls back open
transactions when leaving the body of the context manager. If the body of the with statement finishes
without exceptions, the transaction is committed. If this commit fails, or if the body of
the with statement raises an uncaught exception, the transaction is rolled back.
If there is no open transaction upon leaving the body of the with statement, the context manager is a
no-op.
Note
The context manager neither implicitly opens a new transaction nor closes the connection.
con = sqlite3.connect(":memory:")
with con:
try:
with con:
236
con.execute("INSERT INTO lang(name) VALUES(?)", ("Python",))
except sqlite3.IntegrityError:
con.close()
>>>
● Do not implicitly create a new database file if it does not already exist; will
raise OperationalError if unable to create a new file:
>>>
db = "file:mem1?mode=memory&cache=shared"
with con1:
While row_factory exists as an attribute both on the Cursor and the Connection, it is recommended to
set Connection.row_factory, so all cursors created from the connection will use the same row factory.
Row provides indexed and case-insensitive named access to columns, with minimal memory overhead
and performance impact over a tuple. To use Row as a row factory, assign it to the row_factory attribute:
>>>
>>>
>>> row.keys()
['name', 'radius']
'Earth'
'Earth'
6378
You can create a custom row_factory that returns each row as a dict, with column names mapped to
values:
>>>
238
>>> con = sqlite3.connect(":memory:")
... print(row)
{'a': 1, 'b': 2}
return cls._make(row)
>>>
>>> row
Row(a=1, b=2)
With some adjustments, the above recipe can be adapted to use a dataclass, or any other custom class,
instead of a namedtuple.
Transaction control
The sqlite3 module does not adhere to the transaction handling recommended by PEP 249.
If the connection attribute isolation_level is not None, new transactions are implicitly opened
before execute() and executemany() executes INSERT, UPDATE, DELETE, or REPLACE statements; for other
239
statements, no implicit transaction handling is performed. Use the commit() and rollback() methods to
respectively commit and roll back pending transactions. You can choose the underlying SQLite
transaction behaviour — that is, whether and what type of BEGIN statements sqlite3 implicitly executes
– via the isolation_level attribute.
If isolation_level is set to None, no transactions are implicitly opened at all. This leaves the underlying
SQLite library in autocommit mode, but also allows the user to perform their own transaction handling
using explicit SQL statements. The underlying SQLite library autocommit mode can be queried using
the in_transaction attribute.
The executescript() method implicitly commits any pending transaction before execution of the given
SQL script, regardless of the value of isolation_level.
Changed in version 3.6: sqlite3 used to implicitly commit an open transaction before DDL statements.
This is no longer the case.
240
What is Django?
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic
design. Built by experienced developers, it takes care of much of the hassle of Web development, so you
can focus on writing your app without needing to reinvent the wheel. It’s free and open source.
With Django, you can build high-performing, beautiful Web applications quickly.
Django’s primary goal is to ease the creation of complex, database-driven websites.
● The framework follows the latest best practices built up over the years of experience of Web
development.
● A large and active community that provides support and training resources for both users and
developers.
To put it simply, Django can help you quickly write the code for your Web applications, so you can focus
on innovating instead of reinventing the wheel.
241
What is Flask?
Flask is a micro framework for Python based on Werkzeug, Jinja 2 and good intentions. Flask is intended
for getting started very quickly and was developed with best intentions in mind. It is a very simple and
extremely flexible micro-framework that will suit your needs.
Flask is intended for getting started very quickly and was developed with best intentions in mind. If you
need fine control, you should consider one of the larger frameworks like Django.
Flask’s codebase is small and easy to understand which makes it great for learning. The documentation is
detailed and extensive so that you will never get stuck during your first development.
It lets you quickly launch new small apps, for example the hello world code is just a few lines of code:
app = Flask(__name__)
@app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host='0.0.0.0', port=81)
242
Flask is the underdog . Flask is not the latest, hottest framework. The Python community is not obsessed
with it (yet). Everyone else is not using it. This means your company or project will stand out if you use
Flask.
You can learn a lot from Flask . Flask exposes you to all the basics of a Python web application. This will
make it easier to learn other frameworks, like Django or Pyramid, in the future.
Django is more than just a web framework. Django is a set of best practices that have been refined over
the last 12 years.
It includes the ORM (Object Relational Manager, maps objects to database), template language, and
many other useful applications that make it easier to build complex web applications. Django is mature.
This means that there aren’t large pieces of the framework which are changing dramatically from year to
year.
Django has a team of people backing it with documentation, training, and support. Django is free and
open source.
Flask is younger than Django and doesn’t have as many widespread use cases. Flask also doesn’t have a
rich ecosystem of libraries like Django does. Flask is mainly used for small web apps, where as Django is
used for larger web sites like Instagram, Pinterest, ABitbucket, etc.
Flask does not have an ORM nor a default models system. You have to use an external module for this
with Flask
Flask uses a modular structure, you can setup your own directory-structure as you please.
243
This means it’s easier to get support and developers for Django. Whenever you stumble upon problems,
there’s also a high chance someone had the same problem before.
Flask is a micro-framework. Flask let’s you do everything yourself. By default it doesn’t even come with
database support, you have to use another Python module for that like SQLAlchemy.
Dependencies
● Werkzeug implements WSGI, the standard Python interface between applications and servers.
● Jinja is a template language that renders the pages your application serves.
● MarkupSafe comes with Jinja. It escapes untrusted input when rendering templates to avoid
injection attacks.
● ItsDangerous securely signs data to ensure its integrity. This is used to protect Flask’s session
cookie.
● Click is a framework for writing command line applications. It provides the flask command and
allows adding custom management commands.
Optional dependencies
These distributions will not be installed automatically. Flask will detect and use them if you install them.
● Watchdog provides a faster, more efficient reloader for the development server.
greenlet
You may choose to use gevent or eventlet with your application. In this case, greenlet>=1.0 is required.
When using PyPy, PyPy>=7.3.7 is required.
These are not minimum supported versions, they only indicate the first versions that added necessary
features. You should use the latest versions of each.
244
Virtual environments
Use a virtual environment to manage the dependencies for your project, both in development and in
production.
What problem does a virtual environment solve? The more Python projects you have, the more likely it is
that you need to work with different versions of Python libraries, or even Python itself. Newer versions of
libraries for one project can break compatibility in another project.
Virtual environments are independent groups of Python libraries, one for each project. Packages installed
for one project will not affect other projects or the operating system’s packages.
Python comes bundled with the venv module to create virtual environments.
Create an environment
macOS/LinuxWindows
> cd myproject
macOS/LinuxWindows
> venv\Scripts\activate
Your shell prompt will change to show the name of the activated environment.
Install Flask¶
Within the activated environment, use the following command to install Flask:
SQLite is convenient because it doesn’t require setting up a separate database server and is built-in to
Python. However, if concurrent requests try to write to the database at the same time, they will slow
down as each write happens sequentially. Small applications won’t notice this. Once you become big,
you may want to switch to a different database.
The project doesn’t go into detail about SQL. If you are not familiar with it, the SQLite docs describe
the language.
245
Connect to the Database
The first thing to do when working with a SQLite database (and most other Python database libraries) is
to create a connection to it. Any queries and operations are performed using the connection, which is
closed after the work is finished.
In web applications this connection is typically tied to the request. It is created at some point when
handling a request, and closed before the response is sent.
flaskr/db.py
import sqlite3
import click
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
g is a special object that is unique for each request. It is used to store data that might be accessed by
multiple functions during the request. The connection is stored and reused instead of creating a new
connection if get_db is called a second time in the same request.
246
current_app is another special object that points to the Flask application handling the request. Since you
used an application factory, there is no application object when writing the rest of your code. get_db will
be called when the application has been created and is handling a request, so current_app can be used.
sqlite3.connect() establishes a connection to the file pointed at by the DATABASE configuration key. This
file doesn’t have to exist yet, and won’t until you initialize the database later.
sqlite3.Row tells the connection to return rows that behave like dicts. This allows accessing the columns
by name.
close_db checks if a connection was created by checking if g.db was set. If the connection exists, it is
closed. Further down you will tell your application about the close_db function in the application factory
so that it is called after each request.
flaskr/schema.sql
);
);
247
Add the Python functions that will run these SQL commands to the db.py file:
flaskr/db.py
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
@click.command('init-db')
def init_db_command():
init_db()
open_resource() opens a file relative to the flaskr package, which is useful since you won’t necessarily
know where that location is when deploying the application later. get_db returns a database connection,
which is used to execute the commands read from the file.
click.command() defines a command line command called init-db that calls the init_db function and
shows a success message to the user. You can read Command Line Interface to learn more about writing
commands.
flaskr/db.py
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
app.teardown_appcontext() tells Flask to call that function when cleaning up after returning the
response.
app.cli.add_command() adds a new command that can be called with the flask command.
Import and call this function from the factory. Place the new code at the end of the factory function
before returning the app.
248
flaskr/__init__.py
def create_app():
app = ...
from . import db
db.init_app(app)
return app
There will now be a flaskr.sqlite file in the instance folder in your project.
A Minimal Application
app = Flask(__name__)
@app.route("/")
def hello_world():
1. First we imported the Flask class. An instance of this class will be our WSGI application.
2. Next we create an instance of this class. The first argument is the name of the application’s
module or package. __name__ is a convenient shortcut for this that is appropriate for most
cases. This is needed so that Flask knows where to look for resources such as templates and
static files.
3. We then use the route() decorator to tell Flask what URL should trigger our function.
249
4. The function returns the message we want to display in the user’s browser. The default content
type is HTML, so HTML in the string will be rendered by the browser.
Save it as hello.py or something similar. Make sure to not call your application flask.py because this
would conflict with Flask itself.
To run the application, use the flask command or python -m flask. You need to tell the Flask where your
application is with the --app option.
This launches a very simple builtin server, which is good enough for testing but probably not what you
want to use in production.
Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting.
If you have the debugger disabled or trust the users on your network, you can make the server publicly
available simply by adding --host=0.0.0.0 to the command line:
250
Getting Started With Flask:
Python 2.6 or higher is required for the installation of the Flask. You can start by import Flask from the
flask package on any python IDE. For installation on any environment, you can click on the installation
link given below.
To test that if the installation is working, check out this code given below.
@app.route('/')
def hello():
return 'HELLO'
if __name__=='__main__':
app.run()
‘/’ URL is bound with hello() function. When the home page of the webserver is opened in the browser,
the output of this function will be rendered accordingly.
The Flask application is started by calling the run() function. The method should be restarted manually
for any change in the code. To overcome this, the debug support is enabled so as to track any error.
app.debug = True
app.run()
app.run(debug = True)
Routing:
Nowadays, the web frameworks provide routing technique so that user can remember the URLs. It is
useful to access the web page directly without navigating from the Home page. It is done through the
following route() decorator, to bind the URL to a function.
251
# decorator to route URL
@app.route(‘/hello’)
def hello_world():
If a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered
in the browser. The add_url_rule() function of an application object can also be used to bind URL with
the function as in above example.
def hello_world():
app = Flask(__name__)
@app.route('/hello/<name>')
def hello_name(name):
if __name__ == '__main__':
app.run(debug = True)
Save the above example as hello.py and run from power shell. Next, open the browser and enter the URL
http://localhost:5000/hello/GeeksforGeeks.
252
Output:
Hello GeeksforGeeks!
In the above example, the parameter of route() decorator contains the variable part attached to the URL
‘/hello’ as an argument. Hence, if URL like http://localhost:5000/hello/GeeksforGeeks is entered then
‘GeeksforGeeks’ will be passed to the hello() function as an argument.
In addition to the default string variable part, other data types like int, float, and path(for directory
separator channel which can take slash) are also used. The URL rules of Flask are based on Werkzeug’s
routing module. This ensures that the URLs formed are unique and based on precedents laid down by
Apache.
Examples:
app = Flask(__name__)
@app.route('/blog/<postID>')
def show_blog(postID):
@app.route('/rev/<revNo>')
def revision(revNo):
if __name__ == '__main__':
app.run()
Output :
253
Building URL in FLask:
Dynamic Building of the URL for a specific function is done using url_for() function. The function accepts
the name of the function as first argument, and one or more keyword arguments. See this example
app = Flask(__name__)
@app.route('/guest/<guest>')
@app.route('/user/<name>')
def hello_user(name):
return redirect(url_for('hello_admin'))
else:
if __name__ == '__main__':
app.run(debug = True)
To test this, save the above code and run through python shell and then open browser and enter the
following URL:-
Input: http://localhost:5000/user/admin
254
Input: http://localhost:5000/user/ABC
The above code has a function named user(name), accepts the value through input URL. It checks that
the received argument matches the ‘admin’ argument or not. If it matches, then the function
hello_admin() is called else the hello_guest() is called.
Flask support various HTTP protocols for data retrieval from the specified URL, these can be defined as:-
Method Description
GET This is used to send the data in an without encryption of the form to the server.
POST Sends the form data to server. Data received by POST method is not cached by server.
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
255
if __name__ == '__main__':
app.run(debug = True)
<html>
<head>
</head>
<body>
</body>
</html>
This code will be inside static folder which will be sibling of the templates folder
function sayHello() {
alert("Hello World")
The above hello.js file will be rendered accordingly to the HTML file.
Object Request of Data from a client’s web page is send to the server as a global request object. It is then
processed by importing the Flask module. These consist of attributes like Form(containing Key-Value
Pair), Args(parsed URL after question mark(?)), Cookies(contain Cookie names and Values), Files(data
pertaining to uploaded file) and Method(current request).
Cookies:
256
A Cookie is a form of text file which is stored on a client’s computer, whose purpose is to remember and
track data pertaining to client’s usage in order to improve the website according to the user’s experience
and statistic of webpage.
The Request object contains cookie’s attribute. It is the dictionary object of all the cookie variables and
their corresponding values. It also contains expiry time of itself. In Flask, cookie are set on response
object.See the example given below:-
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
<html>
<body>
<p><h3>Enter userID</h3></p>
</form>
</body>
</html>
def setcookie():
if request.method == 'POST':
user = request.form['nm']
257
resp = make_response(render_template('cookie.html'))
resp.set_cookie('userID', user)
return resp
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
<html>
<body>
</body>
</html>
Sessions in Flask:
In Session, the data is stored on Server. It can be defined as a time interval in which the client logs into a
server until the user logs out. The data in between them are held in a temporary folder on the Server.
Each user is assigned with a specific Session ID. The Session object is a dictionary that contains the
key-value pair of the variables associated with the session. A SECRET_KEY is used to store the encrypted
data on the cookie.
For example:
Syntax: Flask.abort(code)
The code parameter can take the following values to handle the error accordingly:
File-Uploading in Flask:
File Uploading in Flask is very easy. It needs an HTML form with enctype attribute and URL handler, that
fetches file and saves the object to the desired location. Files are temporary stored on server and then on
the desired location.
The HTML Syntax that handle the uploading URL is :
app = Flask(__name__)
@app.route('/upload')
def upload_file():
return render_template('upload.html')
259
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
if __name__ == '__main__':
app.run(debug = True)
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.html')
def result():
if request.method == 'POST':
result = request.form
260
if __name__ == '__main__':
app.run(debug = True)
<!doctype html>
<html>
<body>
<tr>
</tr>
{% endfor %}
</table>
</body>
</html>
<html>
<body>
261
<p>Chemistry <input type = "text" name = "chemistry" /></p>
</form>
</body>
</html>
Message Flashing:
It can be defined as a pop-up or a dialog box that appears on the web-page or like alert in JavaScript,
which are used to inform the user. This in flask can be done by using the method flash() in Flask. It passes
the message to the next template.
message is actual text to be displayed and category is optional which is to render any error or info.
Example :
app = Flask(__name__)
262
# /login display login form
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
else:
return redirect(url_for('index'))
263
Python with Django
What is Django?
Django is a web development framework for Python which offers standard methods for fast and effective
website development. The primary goal of this high-level web framework is to create complex
database-driven websites. It helps you to build and maintain quality web applications. It enables you to
make the development process smooth and time-saving for rapid development.
● What is Django?
● History of Django
● Features of Django
● Characteristics of Django
● Django Architecture
● Components of Django
● Django is easy to set up and run. It offers a variety of options to get started
● Django is used to build all types of content management systems, social networks as well as
scientific computing platforms.
● It is widely used for rate limiting API requests from a single user.
264
History of Django
Year Milestone
2003 The project was started by Adian Holovaty and Simon Willison as an internal project at Lawrence
Journal-World newspaper
July It was released In July 2005 as “Django,” named after the jazz guitarist Django Reinhard
2005
June Declared that a Django Software Foundation (DSF) would maintain Django.
2008
29 July Django 1.1 version was released with features like Aggregates, transaction-based tests.
2009
17 May Django 1.2 version was released. The update offered features like multiple databases,
2010 Implementation of email backend and improvements for sessions and cookie are made in this
version.
23 Mar 1.3 version with features like Class-based views, static files were introduced
2011
23 Mar 1.4 version launched with new features like timezones and in-browser testing
2012
26 Feb 1.5 version comes with Python 3 Support, configurable user model features.
2013
6 Nov 1.6 version comes with DB transaction management, connection pooling features.
2013
2 Sep 1.7 version had new features like application load, migrations, and configuration
2014
4 Apr 1.11 version becomes the last version to support Python 2.7
2017
265
Year Milestone
1 Aug version 2.1 comes with Model “view” permission support feature.
2018
2021 Removed support for Django 3.0 and Added Django 3.2 support
Now in this Django for beginners tutorial, let’s learn about features of Django.
Features of Django
Below are the features of Django:
● Object-oriented programming language database which offers best in class data storage and
retrieval
● Automatic admin interface feature allows the functionality of adding, editing and deleting items.
You can customize the admin panel as per your need.
Now in this Django framework tutorial, we will learn about characteristics of Django.
Characteristics of Django
Here are the main characteristics of Django:
● Loosely Coupled- Django helps you to make each element of its stack independent of the others.
● Not repeated- Everything should be developed in precisely one place instead of repeating it
again
● Consistent design- Django maintains a clean design and makes it easy to follow the best web
development practices.
266
Django Architecture
MVC Pattern:
When talking about applications which provide UI (web or desktop), we usually talk about MVC
architecture. MVC pattern is based on Model, View, and Controller.
The Model defines the data structure and takes to care for querying the database.
The View defines what data should be presented and returns an HTTP response.
The Controller is that part of the application that handles the user interaction.
The below-given diagram shows how all the components of the MVT pattern interact with each other to
serve specific to a user request.
267
MVT Architecture
As seen in above diagram, a user requests for a resource to Django. Django acts as a controller and
checks to the available resource in URL.
If URL maps, a view is called which interacts with model and template. Django then responds to the user
and sends a template as a response.
Now in this Django tutorials for beginners series, we will learn about components of Django.
Components of Django
Form:
Django has a powerful form library which handles rendering forms as HTML. The library helps in
validating submitted data and converting it to Python types.
Authentication:
Admin:
It reads metadata in your models to provide a robust interface which can be used to manage content on
your site.
Internationalization:
Django provides support for translating text into various languages, locale-specific formatting of dates,
times, numbers, and timezones.
Security:
● Cross-site scripting
● SQL injection
● Clickjacking
268
● Remote code execution
● BitBucket
● DISQUS
● NASA
● Mozilla
● NY Times
● LA Times
● Discovery Channel
269
XML Processing in Python
Python XML Parsing Modules
Python allows parsing these XML documents using two modules namely, the xml.etree.ElementTree
module and Minidom (Minimal DOM Implementation). Parsing means to read information from a file
and split it into pieces by identifying parts of that particular XML file. Let’s move on further to see how
we can use these modules to parse XML data.
xml.etree.ElementTree Module:
This module helps us format XML data in a tree structure which is the most natural representation of
hierarchical data. Element type allows storage of hierarchical data structures in memory and has the
following properties:
Property Description
ElementTree is a class that wraps the element structure and allows conversion to and from XML. Let us
now try to parse the above XML file using python module.
There are two ways to parse the file using ‘ElementTree’ module. The first is by using the parse()
function and the second is fromstring() function. The parse () function parses XML document which is
supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.
EXAMPLE:
1import xml.etree.ElementTree as ET
2mytree = ET.parse('sample.xml')
3myroot = mytree.getroot()
As you can see, The first thing you will need to do is to import the xml.etree.ElementTree module. Then,
the parse() method parses the ‘Sample.xml’ file. The getroot() method returns the root element of
‘Sample.xml’.
270
When you execute the above code, you will not see outputs returned but there will be no errors
indicating that the code has executed successfully. To check for the root element, you can simply use the
print statement as follows:
EXAMPLE:
1import xml.etree.ElementTree as ET
2mytree = ET.parse('sample.xml')
3myroot = mytree.getroot()
4print(myroot)
The above output indicates that the root element in our XML document is ‘metadata’.
1 import xml.etree.ElementTree as ET
3 <metadata>
4 <food>
5 <item name="breakfast">Idly</item>
6 <price>$2.5</price>
7 <description>
9 </description>
10 <calories>553</calories>
11</food>
12</metadata>
13'''
14myroot = ET.fromstring(data)
15#print(myroot)
16print(myroot.tag)
271
The above code will return the same output as the previous one. Please note that the XML document
used as a string is just one part of ‘Sample.xml’ which I have used for better visibility. You can use the
complete XML document as well.
You can also retrieve the root tag by using the ‘tag’ object as follows:
EXAMPLE:
1print(myroot.tag)
OUTPUT: metadata
You can also slice the tag string output by just specifying which part of the string you want to see in your
output.
EXAMPLE:
1print(myroot.tag[0:4])
OUTPUT: meta
As mentioned earlier, tags can have dictionary attributes as well. To check if the root tag has any
attributes you can use the ‘attrib’ object as follows:
EXAMPLE:
1print(myroot.attrib)
OUTPUT: {}
As you can see, the output is an empty dictionary because our root tag has no attributes.
272
Finding Elements of Interest:
The root consists of child tags as well. To retrieve the child of the root tag, you can use the following:
EXAMPLE:
1print(myroot[0].tag)
OUTPUT: food
Now, if you want to retrieve all first-child tags of the root, you can iterate over it using the for loop as
follows:
EXAMPLE:
1for x in myroot[0]:
2 print(x.tag, x.attrib)
OUTPUT:
All the items returned are the child attributes and tags of food.
To separate out the text from XML using ElementTree, you can make use of the text attribute. For
example, in case I want to retrieve all the information about the first food item, I should use the
following piece of code:
EXAMPLE:
1for x in myroot[0]:
2 print(x.text)
OUTPUT:
Idly
$2.5
Two idly’s with chutney
553
As you can see, the text information of the first item has been returned as the output. Now if you want
to display all the items with their particular price, you can make use of the get() method. This method
accesses the element’s attributes.
EXAMPLE:
273
1for x in myroot.findall('food'):
2 item =x.find('item').text
3 price = x.find('price').text
4 print(item, price)
OUTPUT:
Idly $2.5
Paper Dosa $2.7
Upma $3.65
Bisi Bele Bath $4.50
Kesari Bath $1.95
The above output shows all the required items along with the price of each of them. Using ElementTree,
you can also modify the XML files.
Adding to XML:
The following example shows how you can add something to the description of items.
EXAMPLE:
3 description.text = str(new_desc)
4 description.set('updated', 'yes')
6mytree.write('new.xml')
The write() function helps create a new xml file and writes the updated output to the same. However,
you can modify the original file as well, using the same function. After executing the above code, you will
be able to see a new file has been created with the updated results.
274
The above image shows the modified description of our food items. To add a new subtag, you can make
use of the SubElement() method. For example, if you want to add a new specialty tag to the first item
Idly, you can do as follows:
EXAMPLE:
1ET.SubElement(myroot[0], 'speciality')
2for x in myroot.iter('speciality'):
4 x.text = str(new_desc)
6mytree.write('output5.xml')
OUTPUT:
275
As you can see, a new tag has been added under the first food tag. You can add tags wherever you want
by specifying the subscript within [] brackets. Now let us take a look at how to delete items using this
module.
EXAMPLE:
1myroot[0][0].attrib.pop('name', None)
4mytree.write('output5.xml')
OUTPUT:
The above image shows that the name attribute has been removed from the item tag. To remove the
complete tag, you can use the same pop() method as follows:
EXAMPLE:
1myroot[0].remove(myroot[0][0])
2mytree.write('output6.xml')
OUTPUT:
276
The output shows that the first subelement of the food tag has been deleted. In case you want to delete
all tags, you can make use of the clear() function as follows:
EXAMPLE:
1myroot[0].clear()
2mytree.write('output7.xml')
OUTPUT:
When the above code is executed, the first child of food tag will be completely deleted including all the
subtags. Till here we have been making use of the xml.etree.ElementTree module in this Python XML
parser tutorial. Now let us take a look at how to parse XML using Minidom.
xml.dom.minidom Module:
This module is basically used by people who are proficient with DOM (Document Object module). DOM
applications often start by parsing XML into DOM. in xml.dom.minidom, this can be achieved in the
following ways:
EXAMPLE:
2p1 = minidom.parse("sample.xml");
Once you execute this, you will be able to split the XML file and fetch the required data. You can also
parse an open file using this function.
EXAMPLE:
1dat=open('sample.xml')
2p2=minidom.parse(dat)
277
The variable storing the opened file is supplied as a parameter to the parse function in this case.
EXAMPLE:
You can parse XML using any of the above methods. Now let us try to fetch data using this module.
EXAMPLE:
1dat=minidom.parse('sample.xml')
2print(dat)
OUTPUT:
EXAMPLE:
1tagname= dat.getElementsByTagName('item')[0]
2print(tagname)
If I try to fetch the first element using the GetElementByTagName method, I will see the following
output:
OUTPUT:
Please note that just one output has been returned because I have used [0] subscript for convenience
which will be removed in the further examples.
To access the value of the attributes, I will have to make use of the value attribute as follows:
EXAMPLE:
1dat = minidom.parse('sample.xml')
2tagname= dat.getElementsByTagName('item')
3print(tagname[0].attributes['name'].value)
OUTPUT: breakfast
To retrieve the data present in these tags, you can make use of the data attribute as follows:
278
EXAMPLE:
1print(tagname[1].firstChild.data)
You can also split and retrieve the value of the attributes using the value attribute.
EXAMPLE:
1print(items[1].attributes['name'].value)
OUTPUT: breakfast
To print out all the items available in our menu, you can loop through the items and return all the items.
EXAMPLE:
1for x in items:
2 print(x.firstChild.data)
OUTPUT:
Idly
Paper Dosa
Upma
Bisi Bele Bath
Kesari Bath
To calculate the number of items on our menu, you can make use of the len() function as follows:
EXAMPLE:
1print(len(items))
OUTPUT: 5
279
AI based Real-time Projects
Project 1 Tic-Tac-Toe Game Engine
Learners’ Guide attached named as Project 1 Tic-Tac-Toe Game Engine
Project 2 A Chatbot
Learners’ Guide attached named as Project 2 A Chatbot
Project 4 Deploy a Python (Django or Flask) web app with PostgreSQL in Azure
In this project, you'll deploy a data-driven Python web app (Django or Flask) to Azure App Service with
the Azure Database for PostgreSQL relational database service. Azure App Service supports Python 3.7
or higher in a Linux server environment.
● An Azure account with an active subscription exists. If you don't have an Azure account, you can
create one for free.
Sample application
Sample Python applications using the Flask and Django framework are provided to help you follow along
with this project. To deploy them without running them locally, skip this part.
To run the application locally, make sure you have Python 3.7 or higher and PostgreSQL install locally.
Then, download or clone the app:
● Flask
● Django
BashCopy
BashCopy
cd msdocs-python-flask-webapp-quickstart
Create an .env file as shown below using the .env.sample file as a guide. Set the value of DBNAME to the
name of an existing database in your local PostgreSQL instance. Set the values of DBHOST, DBUSER,
and DBPASS as appropriate for your local PostgreSQL instance.
Copy
DBNAME=<database name>
DBHOST=<database-hostname>
DBUSER=<db-user-name>
DBPASS=<db-password>
● Windows
● macOS/Linux
CmdCopy
py -m venv .venv
.venv\scripts\activate
BashCopy
● Flask
● Django
BashCopy
flask db upgrade
flask run
281
In this step, you create the Azure resources. The steps used in this project create a set of
secure-by-default resources that include App Service and Azure Database for PostgreSQL. For the
creation process, you'll specify:
● The Name for the web app. It's the name used as part of the DNS name for your webapp in the
form of https://<app-name>.azurewebsites.net.
● The Region to run the app physically in the world.
● The Runtime stack for the app. It's where you select the version of Python to use for your app.
● The Hosting plan for the app. It's the pricing tier that includes the set of features and scaling
capacity for your app.
● The Resource Group for the app. A resource group lets you group (in a logical container) all the
Azure resources needed for the application.
Sign in to the Azure portal and follow these steps to create your Azure App Service resources.
Step 1. In the Azure portal:
1. Enter "web app database" in the search bar at the top of the Azure portal.
2. Select the item labeled Web App + Database under the Marketplace heading. You can also
navigate to the creation wizard directly.
Step 2. In the Create Web App + Database page, fill out the form as follows.
282
Step 3. The deployment takes a few minutes to complete. Once deployment completes, select the Go to
resource button. You're taken directly to the App Service app, but the following resources are created:
283
● Resource group → The container for all the created resources.
● App Service plan → Defines the compute resources for App Service. A Linux plan in the Basic tier
is created.
● App Service → Represents your app and runs in the App Service plan.
● Virtual network → Integrated with the App Service app and isolates back-end network traffic.
● Azure Database for PostgreSQL flexible server → Accessible only from within the virtual
network. A database and a user are created for you on the server.
● Private DNS zone → Enables DNS resolution of the PostgreSQL server in the virtual network.
The creation wizard generated the connectivity variables for you already as app settings.
Step 1. In the App Service page, in the left menu, select Configuration.
284
Step 2. In the Application settings tab of the Configuration page, verify that
(DBNAME, DBHOST, DBUSER, and DBPASS) are present. They'll be injected into the runtime environment
as environment variables. App settings are a good way to keep connection secrets out of your code
repository.
In this step, you'll configure GitHub deployment using GitHub Actions. It's just one of many ways to
deploy to App Service, but also a great way to have continuous integration in your deployment process.
By default, every git push to your GitHub repository will kick off the build and deploy action.
● Flask
● Django
Step 1. In a new browser window:
1. Sign in to your GitHub account.
2. Navigate to https://github.com/Azure-Samples/msdocs-flask-postgresql-sample-app.
3. Select Fork.
285
4. Select Create fork.
Step 2. In the GitHub page, open Visual Studio Code in the browser by pressing the . key.
286
Step 3. In Visual Studio Code in the browser, open azureproject/production.py in the explorer. See the
environment variables being used in the production environment, including the app settings that you
saw in the configuration page.
Step 4. Back in the App Service page, in the left menu, select Deployment Center.
287
4. In Repository, select msdocs-flask-postgresql-sample-app.
5. In Branch, select main.
6. In the top menu, select Save. App Service commits a workflow file into the chosen GitHub
repository, in the .github/workflows directory.
288
Step 6. In the Deployment Center page:
1. Select Logs. A deployment run is already started.
2. In the log item for the deployment run, select Build/Deploy Logs.
289
Step 7. You're taken to your GitHub repository and see that the GitHub action is running. The workflow
file defines two separate stages, build and deploy. Wait for the GitHub run to show a status of Complete.
It takes about 5 minutes.
290
Having issues? Refer first to the Troubleshooting guide, otherwise, let us know.
● Flask
● Django
With the PostgreSQL database protected by the virtual network, the easiest way to run Run Flask
database migrations is in an SSH session with the App Service container.
Step 4. Back in the App Service page, in the left menu, select Deployment Center.
Step 2. In the SSH terminal, run flask db upgrade. If it succeeds, App Service is connecting successfully to
the database. Only changes to files in /home can persist beyond app restarts. Changes outside
of /home aren't persisted.
291
5. Browse to the app
2. Select the URL of your app. You can also navigate directly
to https://<app-name>.azurewebsites.net.
292
Step 2. Add a few tasks to the list. Congratulations, you're running a secure data-driven Flask app in
Azure App Service, with connectivity to Azure Database for PostgreSQL.
Azure App Service captures all messages output to the console to help you diagnose issues with your
application. The sample app includes print() statements to demonstrate this capability as shown below.
● Flask
● Django
PythonCopy
def index(request):
Step 2. From the left menu, select Log stream. You see the logs for your app, including platform logs and
logs from inside the container.
7. Clean up resources
When you're finished, you can delete all of the resources from your Azure subscription by deleting the
resource group.
294
Step 2. In the resource group page, select Delete resource group.
Step 3.
2. Select Delete.
295
:
● How do I connect to the PostgreSQL server that's secured behind the virtual network with other
tools?
● The App Service plan is created in Basic tier and can be scaled up or down. See App Service
pricing.
● The PostgreSQL flexible server is create in the lowest burstable tier Standard_B1ms, with the
minimum storage size, which can be scaled up or down. See Azure Database for PostgreSQL
pricing.
● The virtual network doesn't incur a charge unless you configure extra functionality, such as
peering. See Azure Virtual Network pricing.
296
● The private DNS zone incurs a small charge. See Azure DNS pricing.
How do I connect to the PostgreSQL server that's secured behind the virtual network with other tools?
● For basic access from a commmand-line tool, you can run psql from the app's SSH terminal.
● To connect from a desktop tool, your machine must be within the virtual network. For example,
it could be an Azure VM that's connected to one of the subnets, or a machine in an on-premises
network that has a site-to-site VPN connection with the Azure virtual network.
● You can also integrate Azure Cloud Shell with the virtual network.
Take the autogenerated workflow file from App Service as an example, each git push kicks off a new build
and deployment run. From a local clone of the GitHub repository, you make the desired updates push it
to GitHub. For example:
terminalCopy
git add .
git commit -m "<some-message>"
git push origin main
The Django sample application configures settings in the azureproject/production.py file so that it can
run in Azure App Service. These changes are common to deploying Django to production, and not
specific to App Service.
● Django validates the HTTP_HOST header in incoming requests. The sample code uses
the WEBSITE_HOSTNAME environment variable in App Service to add the app's domain name to
Django's ALLOWED_HOSTS setting.
PythonCopy
● Django doesn't support serving static files in production. For this project, you use WhiteNoise to
enable serving the files. The WhiteNoise package was already installed with requirements.txt,
and its middleware is added to the list.
PythonCopy
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# Add whitenoise middleware after the security middleware
'whitenoise.middleware.WhiteNoiseMiddleware',
Then the static file settings are configured according to the Django documentation.
PythonCopy
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
297