Python Notes (B.SC)
Python Notes (B.SC)
Python Notes (B.SC)
(Computer Science)
III - YEAR/ V - SEMESTER
THEORY PAPER – VI (Elective - IC)
Programming in Python
UNIT - IV: Python GUI & CGI Programming and Python database connectivity.
Python GUI Programming (Tkinter): Tkinter Programming example, Tkinter widges, standard
attributes, geometry management
Python CGI Programming: CGI Architecture, First CGI Program, HTTP Header, CGI
Environment Variables, GET and POST Methods, Simple FORM Example: Using GET
Method, Passing Information Using POST Method
Python database connectivity: Establishing connection, insert, retrieve, delete, and rollback and
commit operations.
References:
1.Core Python Programming Wesley J. Chun Publisher: Prentice Hall PTR First Edition
2.T. Budd, Exploring Python, TMH, 1st Ed, 2011
3.Python Tutorial/Documentation www.python.or 2010
4.Allen Downey, Jeffrey Elkner, Chris Meyers , How to think like a computer scientist :
learning with Python , Freely available online.2015
5.Web Resource: http://interactivepython.org/courselib/static/pythonds
B.Sc. (Computer Science)
III – YEAR / V - SEMESTER
PRACTICAL PAPER – VI (Elective - IC)
Programming in Python Lab Question Bank
Subject Code: BS.07.201.14C.P
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has
fewer syntactical constructions than other languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming
that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
Python Features
Python's features include −
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This
allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window
system of Unix.
Scalable − Python provides a better structure and support for large programs than shell scripting.
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
IT supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Getting Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official
website of Python https://www.python.org/
In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
In the bash shell (Linux) − type export ATH="$PATH:/usr/local/bin/python" and press Enter.
In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter.
Note − /usr/local/bin/python is the path of the Python directory
A Python script can be executed at command line by invoking the interpreter on your application, as in the
following −
$ python
2.4.3(#1,Nov112010,13:34:43)
GCC 4.1.220080704(RedHat4.1.2-48)] on linux2
Type"help","copyright","credits"or"license"for more information.
>>>
Type the following text at the Python prompt and press the Enter −
>>>print"Hello,Python!" #valid
in python 2 and invalid in python 3
If you are running new version of Python, then you would need to use print statement with parenthesis as in
print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result −
Hello, Python!
Let us write a simple Python program in a script. Python files have extension .py. Type the following source
code in a test.py file −
print"Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file −
#!/usr/bin/python
print"Hello, Python!"
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as
follows −
$ chmod +x test.py # This is to make file executable
$./test.py
This produces the following result −
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.
ifTrue:
print"Answer"
print"True"
else:
print"Answer"
print"False"
Thus, in Python all the continuous lines indented with same number of spaces would form a block. The
following example has various statement blocks −
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line
continuation character (\) to denote that the line should continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For
example −
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the
end of the physical line are part of the comment and the Python interpreter ignores them.
#!/usr/bin/python
# First comment
print"Hello, Python!"# second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "St.Joseph’s" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally
ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a multiline
statement.
Waiting for the User
The following line of the program displays the prompt, the statement saying “Press the enter key to exit”,
and waits for the user to take action −
#!/usr/bin/python
var = input ()
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key,
the program ends. This is a nice trick to keep a console window open until the user is done with an
application.
$ python -h
usage: python [option]...[-c cmd |-m mod | file |-][arg]...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string(terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h :print this help message and exit
[ etc.]
>>> input()
I am learning at St.Joseph’s #(This is where you type in)
Output:
'I am learning at St.Joseph’s' #(The interpreter showing you how the input is
captured.)
Definitions to remember: An argument is a value you pass to a function when calling it. A value is a letter
or a number. A variable is a name that refers to a value. It begins with a letter. An assignment statement
creates new variables and gives them values.
This syntax is valid in both Python 3.x and Python 2.x. For example, if your data is "Guido," you can put
"Guido" inside the parentheses ( ) after print.
>>>print("Guido")
Guido
Python - Variable
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example −
#!/usr/bin/python
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively.
This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string
object with the value "john" is assigned to the variable c.
Numbers
String
List
Tuple
Dictionary
Python - Numbers
Number data types store numeric values. They are immutable data types, means that changing the value of a
number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del
statement is −
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
int (signed integers) − They are often called just integers or ints, are positive or negative whole
numbers with no decimal point.
long (long integers ) − Also called longs, they are integers of unlimited size, written like integers
and followed by an uppercase or lowercase L.
float (floating point real values) − Also called floats, they represent real numbers and are written
with a decimal point dividing the integer and fractional parts. Floats may also be in scientific
notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j)
represents the square root of -1 (which is an imaginary number). The real part of the number is a, and
the imaginary part is b. Complex numbers are not used much in Python programming.
Examples
Here are some examples of numbers
Python allows you to use a lowercase L with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase
L.
A complex number consists of an ordered pair of real floating point numbers denoted by a + bj,
where a is the real part and b is the imaginary part of the complex number.
Number Type Conversion
Python converts numbers internally in an expression containing mixed types to a common type for
evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the
requirements of an operator or function parameter.
Type int(x) to convert x to a plain integer.
Type long(x) to convert x to a long integer.
Type float(x) to convert x to a floating-point number.
Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x
and y are numeric expressions
Mathematical Functions
Python includes following functions that perform mathematical calculations.
Trigonometric Functions
Python includes following functions that perform trigonometric calculations.
Mathematical Constants
The module also defines two mathematical constants −
Python - Strings
Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in
quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a
value to a variable. For example −
To access substrings, use the square brackets for slicing along with the index or indices to obtain your
substring. For example −
#!/usr/bin/python
print "var1[0]: ", var1[0] # valid in python 2.x and invalid in python 3.x
print ("var2[1:5]: ", var2[1:5]) # valid in python 2.x and valid in python 3.x
var1[0]: H
var2[1:5]: ytho
Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new value can be
related to its previous value or to a completely different string altogether. For example −
#!/usr/bin/python
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash
notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Hexadecimal
“Description”
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation, where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or
A.F
#!/usr/bin/python
Here is the list of complete set of symbols which can be used along with % −
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Other supported symbols and functionality are listed in the following table −
Symbol Functionality
* argument specifies width or precision
- left justification
+ display the sign
<sp> leave a blank space before a positive number
# add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X',
depending on whether 'x' or 'X' were used.
0 pad from left with zeros (instead of spaces)
% '%%' leaves you with a single literal '%'
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the number of digits to display after
the decimal point (if appl.)
Triple Quotes
Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim
NEWLINEs, TABs, and any other special characters.
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python
When the above code is executed, it produces the following result. Note how every single special character
has been converted to its printed form, right down to the last NEWLINE at the end of the string between the
"up." and closing triple quotes. Also note that NEWLINEs occur either with an explicit carriage return at the
end of a line or its escape code (\n) −
Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string
stays the way you wrote it −
#!/usr/bin/python
print 'C:\\nowhere'
C:\nowhere
Now let's make use of raw string. We would put expression in r'expression' as follows −
#!/usr/bin/python
print r'C:\\nowhere'
C:\\nowhere
Unicode String
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit
Unicode. This allows for a more varied set of characters, including special characters from most languages
in the world. I'll restrict my treatment of Unicode strings to the following −
#!/usr/bin/python
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.
Python - Lists
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number -
its position or index. The first index is zero, the second index is one, and so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would
see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing, slicing,
adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the
length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list of comma-separated
values (items) between square brackets. Important thing about a list is that items in a list need not be of the
same type.
Creating a list is as simple as putting different comma-separated values between square brackets. For
example −
#!/usr/bin/python
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append() method. For example −
#!/usr/bin/python
In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.
Python - Tuples
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences
between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas
lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these
comma-separated values between parentheses also. For example −
To write a tuple containing a single value you have to include a comma, even though there is only one value
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple elements. You are able
to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python
To explicitly remove an entire tuple, just use the del statement. For example −
#!/usr/bin/python
This produces the following result. Note an exception raised, this is because after del tup tuple does not
exist any more −
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists,
parentheses for tuples, etc., default to tuples, as indicated in these short examples −
#!/usr/bin/python
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing
is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like
this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type,
but the keys must be of an immutable data type such as strings, numbers, or tuples.
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows
−
#!/usr/bin/python
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry as shown below in the simple example −
#!/usr/bin/python
To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −
#!/usr/bin/python
This produces the following result. Note that an exception is raised because after del dict dictionary does not
exist any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate
keys encountered during assignment, the last assignment wins. For example −
#!/usr/bin/python
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed. Following is a simple example −
#!/usr/bin/python
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Literals
Python Literals
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double
quotes for a String.
Eg:"Aman" , '12345'
Types of Strings:
a).Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:>>> text1='hello'
b).Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
Eg:
1. >>> text1='hello\
2. user'
3. >>> text1
4. 'hellouser'
5. >>>
Eg:
1. >>> str2='''''welcome
2. to
3. SSSIT'''
4. >>> print str2
5. welcome
6. to
7. SSSIT
8. >>>
II.Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
A Boolean literal can have any of the two values: True or False.
Eg:
1. >>> val1=10
2. >>> val2=None
3. >>> val1
4. 10
5. >>> val2
6. >>> print val2
7. None
8. >>>
V.Literal Collections.
List:
List contain items of different data types. Lists are mutable i.e., modifiable.
The values stored in List are separated by commas(,) and enclosed within a square brackets([]). We can store
different type of data in a List.
Value stored in a List can be retrieved using the slice operator([] and [:]).
The plus sign (+) is the list concatenation and asterisk(*) is the repetition operator.
Eg:
1. >>> list=['aman',678,20.4,'saurav']
2. >>> list1=[456,'rahul']
3. >>> list
4. ['aman', 678, 20.4, 'saurav']
5. >>> list[1:3]
6. [678, 20.4]
7. >>> list+list1
8. ['aman', 678, 20.4, 'saurav', 456, 'rahul']
9. >>> list1*2
10. [456, 'rahul', 456, 'rahul']
11. >>>
Python programming language provides following types of decision making statements. Click
the following links to check their detail.
1 if statements
An if statement consists of a boolean expression followed by one or
more statements.
2 if...else statements
An if statement can be followed by an optional else statement,
which executes when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else
ifstatement(s).
Let us go through each decision making briefly −
Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.
Here is an example of a one-line if clause −
#!/usr/bin/python
var=100
if(var==100):print"Value of expression is 100"
print"Good bye!"
When the above code is executed, it produces the following result −
Value of expression is 100
Good bye!
if statements
It is similar to that of other languages. The if statement contains a logical expression using
which data is compared and a decision is made based on the result of the comparison.
Syntax :
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of code
after the end of the if statement(s) is executed.
Flow Diagram
Example
#!/usr/bin/python
var1 = 100
if var1:
print "1 - Got a true expression value"
print var1
var2 = 0
if var2:
print "2 - Got a true expression value"
print var2
print "Good bye!"
if...else statements
Flow Diagram
Example
#!/usr/bin/python
var1 =100
if var1:
print"1 - Got a true expression value"
print var1
else:
print"1 - Got a false expression value"
print var1
var2 =0
if var2:
print"2 - Got a true expression value"
print var2
else:
print"2 - Got a false expression value"
print var2
print"Good bye!"
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
2 - Got a false expression value
0
Good bye!
var=100
ifvar==200:
print"1 - Got a true expression value"
printvar
elifvar==150:
print"2 - Got a true expression value"
printvar
elifvar==100:
print"3 - Got a true expression value"
printvar
else:
print"4 - Got a false expression value"
printvar
print"Good bye!"
When the above code is executed, it produces the following result −
3 - Got a true expression value
100
Good bye!
nested if statements
There may be a situation when you want to check for another condition after a
condition resolves to true. In such a situation, you can use the nested ifconstruct.
In a nested if construct, you can have an if...elif...else construct inside
anotherif...elif...else construct.
print"Good bye!"
When the above code is executed, it produces following result −
Expression value is less than 200
Which is 100
Good bye!
Python - Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when
you need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement −
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
1 break statement
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
while loop
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax :The syntax of a while loop in Python programming language is −
while expression:
statement(s)
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the first
statement after the while loop will be executed.
Example
#!/usr/bin/python
count =0
while(count <9):
print'The count is:', count
count = count +1
print"Good bye!"
When the above code is executed, it produces the following result −
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current value
of the index count is displayed and then increased by 1.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never
resolves to a FALSE value. This results in a loop that never ends. Such a loop is
called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs
to run continuously so that client programs can communicate with it as and when
required.
#!/usr/bin/python
var=1
whilevar==1:# This constructs an infinite loop
num = raw_input("Enter a number :")
print"You entered: ", num
print"Good bye!"
When the above code is executed, it produces the following result −
Enter a number :20
You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number between :Traceback (most recent call last):
File "test.py", line 5, in <module>
num = raw_input("Enter a number :")
KeyboardInterrupt
Above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise else statement
gets executed.
#!/usr/bin/python
count =0
while count <5:
print( count," is less than 5")
count = count +1
else:
print(count," is not less than 5")
When the above code is executed, it produces the following result −
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
flag =1
while(flag):print'Given flag is really true!'
print"Good bye!"
It is better not try above example because it goes into infinite loop and you need to
press CTRL+C keys to exit.
for Loop Statements
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item in
the sequence is assigned to the iterating variable iterating_var. Next, the statements
block is executed. Each item in the list is assigned to iterating_var, and the
statement(s) block is executed until the entire sequence is exhausted.
Flow Diagram
Example
#!/usr/bin/python
fruits =['banana','apple','mango']
for fruit infruits:# Second Example
print'Current fruit :', fruit
print"Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
#!/usr/bin/python
fruits =['banana','apple','mango']
for index in range(len(fruits)):
print'Current fruit :', fruits[index]
print"Good bye!"
When the above code is executed, it produces the following result −
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Here, we took the assistance of the len() built-in function, which provides the total
number of elements in the tuple as well as the range() built-in function to give us the
actual sequence to iterate over.
Using else Statement with Loops
Python supports to have an else statement associated with a loop statement
If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 through 20.
lower =10
upper =20
# uncomment the following lines to take input from the user
#lower = int(input("Enter lower range: "))
#upper = int(input("Enter upper range: "))
print("Prime numbers between",lower,"and",upper,"are:")
for num in range(lower,upper +1):
for i in range(2,num):
if(num % i)==0:
break
else:
print'%d is a prime number \n'%(num),
When the above code is executed, it produces the following result −
('Prime numbers between', 10, 'and', 20, 'are:')
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
nested loops :
Python programming language allows to use one loop inside another loop. Following
section shows few examples to illustrate the concept.
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is
as follows −
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that you can put any type of loop inside of any other
type of loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested for loop to find the prime numbers from 2 to
100 −
#!/usr/bin/python
i =2
while(i <100):
j =2
while(j <=(i/j)):
ifnot(i%j):break
j = j +1
if(j > i/j):print i," is prime"
i = i +1
print"Good bye!"
When the above code is executed, it produces following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
break statement
It terminates the current loop and resumes execution at the next statement, just like
the traditional break statement in C.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop. The break statement can be used in
bothwhile and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax :The syntax for a break statement in Python is as follows −
break
Flow Diagram
Example
#!/usr/bin/python
print"Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
continue statement
It returns the control to the beginning of the while loop.. The continuestatement
rejects all the remaining statements in the current iteration of the loop and moves
the control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
Example
#!/usr/bin/python
It is used when a statement is required syntactically but you do not want any
command or code to execute.
The pass statement is a null operation; nothing happens when it executes.
Thepass is also useful in places where your code will eventually go, but has not been
written yet (e.g., in stubs for example) −
Syntax
pass
Example
#!/usr/bin/python
print"Good bye!"
When the above code is executed, it produces following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
File Handling in Python
What is a file?
File is a named location on disk to store related information. It is used to permanently store data in a non-
volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is turned off, we use
files for future use of the data.
When we want to read from or write to a file, we need to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
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 alike other concepts of Python,
this concept here is also easy and short. Python treats file differently as text or binary and this is important.
Each line of code includes a sequence of characters and they form 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 us start with Reading and Writing
files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most of
the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open function. This function
creates a file object, which would be utilized to call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
file_name − Thefile_name argument is a string value that contains the name of the file that you want
to access.
access_mode − Theaccess_mode determines the mode in which the file has to be opened, i.e., read,
write, append, etc. A complete list of possible values is given below in the table. This is optional
parameter and the default file access mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1, line
buffering is performed while accessing a file. If you specify the buffering value as an integer greater
than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size is
the system defaultbehavior.
Here is a list of the different modes of opening a file –
Sr.No. Modes & Description
r
1 Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
rb
2 Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
This is the default mode.
r+
3
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed at the beginning
of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a
new file for writing.
wb
6 Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.
w+
7 Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
wb+
8 Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
a
9 Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a new file for writing.
ab
10 Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
11
exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading
and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the
12
file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −
Sr.No. Attribute & Description
1 file.closed
Returns true if file is closed, false otherwise.
2 file.mode
Returns access mode with which file was opened.
3 file.name
Returns name of the file.
4 file.softspace
Returns false if space explicitly required with print, true otherwise.
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt","wb")
print"Name of the file: ", fo.name
print"Closed or not : ",fo.closed
print"Opening mode : ",fo.mode
print"Softspace flag : ",fo.softspace
This produces the following result −
Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspaceflag : 0
# Open a file
fo= open("foo.txt","wb")
print"Name of the file: ", fo.name
# Open a file
fo= open("foo.txt","wb")
fo.write("Python is a great language.\nYeah its great!!\n");
Syntax
fileObject.write([count]);
# Open a file
fo= open("foo.txt","r+")
str=fo.read(10);
print"Read String is : ",str
# Close opend file
fo.close()
This produces the following result −
Read String is : Python is
File Handling Examples
Let's show some examples
To open a text file, use:
fh = open("hello.txt", "r")
File Positions
The tell method tells you the current position within the file; in other words, the next read or write will occur
at that many bytes from the beginning of the file.
The seekoffset[,from]offset[,from] method changes the current file position. The offset argument indicates
the number of bytes to be moved. The from argument specifies the reference position from where the bytes
are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the current
position as the reference position and if it is set to 2 then the end of the file would be taken as the reference
position.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo= open("foo.txt","r+")
str=fo.read(10);
print"Read String is : ",str
PYTHON - MODULES
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes and
variables. A module can also include runnable code.
Example
The Python code for a module named aname normally resides in a file named aname.py. Here's
an example of a simple module, support.py
You can use any Python source file as a module by executing an import statement in some other
Python source file. The import has the following syntax −
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module support.py, you need to put the
following command at the top of the script −
#!/usr/bin/python
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This prevents
the module execution from happening over and over again if multiple imports occur.
Python's from statement lets you import specific attributes from a module into the current
namespace. Thefrom...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following statement
−
This statement does not import the entire module fib into the current namespace; it just
introduces the item fibonacci from the module fib into the global symbol table of the importing
module.
It is also possible to import all names from a module into the current namespace by using the
following import statement −
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences −
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent
default.
A Python statement can access variables in a local namespace and in the global namespace. If a
local and a global variable have the same name, the local variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as
ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any
variable assigned a value in a function is local.
Therefore, in order to assign a value to a global variable within a function, you must first use the
global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops
searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money,
we assignMoney a value, therefore Python assumes Money as a local variable. However, we
accessed the value of the local variable Money before setting it, so an UnboundLocalError is the
result. Uncommenting the global statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The dir built-in function returns a sorted list of strings containing the names defined by a
module.
The list contains the names of all the modules, variables and functions that are defined in a
module. Following is a simple example −
Live Demo
#!/usr/bin/python
# Import built-in module math
import math
content = dir(math)
print content
Here, the special string variable __name__ is the module's name, and __file__ is the filename
from which the module was loaded.
The globals and locals functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.
If locals is called from within a function, it will return all the names that can be accessed locally
from that function.
If globals is called from within a function, it will return all the names that can be accessed
globally from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using
the keysfunction.
When the module is imported into a script, the code in the top-level portion of a module is
executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload function. The reload function imports a previously imported module again. The
syntax of the reload function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the string containing
the module name. For example, to reload hello module, do the following −
reload(hello)
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and subpackages and sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source code
−
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same name as above
−
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put explicit
import statements in __init__.py as follows −
After you add these lines to __init__.py, you have all of these classes available when you import
the Phone package.
#!/usr/bin/python
Phone.Pots()
Phone.Isdn()
Phone.G3()
Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function
or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
Syntax
def functionname( parameters ) :
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were
defined.
Example : The following function takes a string as input parameter and prints it on standard screen.
def printme( str ) :
"This prints a passed string into this function"
print (str)
return
Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures
the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly
from the Python prompt. Following is the example to call printme() function −
#!/usr/bin/python
#!/usr/bin/python
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
1. Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of
arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows
−
#!/usr/bin/python
2. Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller
identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the
keywords provided to match the values with parameters. You can also make keyword calls to the printme() function
in the following ways −
#!/usr/bin/python
3. Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that
argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their
parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline
statements in C or C++, whose purpose is by passing function stack allocation during invocation for
performance reasons.
Syntax: The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
#!/usr/bin/python
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you have
declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are
two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global
variables can be accessed throughout the program body by all functions. When you call a function, the variables
declared inside it are brought into scope. Following is a simple example −
#!/usr/bin/python
Built-in Functions
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
OR
Function Description
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii
characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the
specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object's properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided
by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate
object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute
(property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified
object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to
each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified
character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by
1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
@staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the __dict__ property of an object
zip() Returns an iterator, from two or more iterators
1. Python abs()
The python abs() is one of the most popular Python built-in functions, which returns the absolute value of a number. A
negative value’s absolute is that value is positive.
1. >>> abs(-7)
7
1. >>> abs(7)
7
1. >>> abs(0)
0
2. Python all()
Python all() function takes a container as an argument. This Built in Functions returns True if all values in a python
iterable have a Boolean value of True. An empty value has a Boolean value of False.
1. >>> all({‘*','',''})
False
1. >>> all([' ',' ',' '])
True
3. Python any()
Like Python all(), it takes one argument and returns True if, even one value in the iterable has a Boolean value of
True.
1. >>> any((1,0,0))
True
1. >>> any((0,0,0))
False
4. Python ascii()
Python ascii(), is important Python built-in functions, returns a printable representation of a python object (like a
string or a Python list). Let’s take a Romanian character.
1. >>> ascii('ș')
2.
3. "'\\u0219'"
Since this was a non-ASCII character in python, the interpreter added a backslash (\) and escaped it using another
backslash.
1. >>> ascii('ușor')
2.
3. "'u\\u0219or'"
Let’s apply it to a list.
1. >>> ascii(['s','ș'])
2.
3. "['s', '\\u0219']"
5. Python bin()
Python bin() converts an integer to a binary string. We have seen this and other functions in our article onPython
Numbers.
1. >>> bin(7)
‘0b111’
We can’t apply it on floats, though.
1. >>> bin(7.0)
2. Traceback (most recent call last):
3. File "<pyshell#20>", line 1, in <module>
4. bin(7.0)
TypeError: ‘float’ object cannot be interpreted as an integer
6. Python bool()
Python bool() converts a value to Boolean.
1. >>> bool(0.5)
True
1. >>> bool('')
False
1. >>> bool(True)
True
7. Python bytearray()
Python bytearray() returns a python array of a given byte size.
1. >>> a=bytearray(4)
2. >>> a
3. bytearray(b'\x00\x00\x00\x00')
4. >>> a.append(1)
5. >>> a
6. bytearray(b'\x00\x00\x00\x00\x01')
7. >>> a[0]=1
8. >>> a
9. bytearray(b'\x01\x00\x00\x00\x01')
10. >>> a[0]
1
Let’s do this on a list.
1. >>> bytearray([1,2,3,4])
2. bytearray(b'\x01\x02\x03\x04')
8. Python bytes()
Python bytes() returns an immutable bytes object.
1. >>> bytes(5)
2. b'\x00\x00\x00\x00\x00'
3. >>> bytes([1,2,3,4,5])
4. b'\x01\x02\x03\x04\x05'
5. >>> bytes('hello','utf-8')
b’hello’
Here, utf-8 is the encoding.
Both bytes() and bytearray() deal with raw data, but bytearray() is mutable, while bytes() is immutable.
1. >>> a=bytes([1,2,3,4,5])
2. >>> a
3. b'\x01\x02\x03\x04\x05'
4. >>> a[4]=
3
1. Traceback (most recent call last):
2. File "<pyshell#46>", line 1, in <module>
3. a[4]=3
TypeError: ‘bytes’ object does not support item assignment
Let’s try this on bytearray().
1. >>> a=bytearray([1,2,3,4,5])
2. >>> a
3. bytearray(b'\x01\x02\x03\x04\x05')
4. >>> a[4]=3
5. >>> a
6. bytearray(b'\x01\x02\x03\x04\x03')
9. Python callable()
Python callable() tells us if an object can be called.
1. >>> callable([1,2,3])
False
1. >>> callable(callable)
True
1. >>> callable(False)
False
1. >>> callable(list)
True
A function is callable, a list is not. Even the callable() python Built In function is callable.
10. Python chr()
Python chr() Built In function returns the character in python for an ASCII value.
1. >>> chr(65)
‘A’
1. >>> chr(97)
‘a’
1. >>> chr(9)
‘\t’
1. >>> chr(48)
‘0’
11. Python classmethod()
Python classmethod() returns a class method for a given method.
1. >>> class fruit:
2. def sayhi(self):
3. print("Hi, I'm a fruit")
4. >>> fruit.sayhi=classmethod(fruit.sayhi)
5. >>> fruit.sayhi()
Hi, I’m a fruit
When we pass the method sayhi() as an argument to classmethod(), it converts it into a python class method one that
belongs to the class. Then, we call it like we would call any static method in python without an object.
12. Python compile()
Python compile() returns a Python code object. We use Python in built function to convert a string code into object
code.
1. >>> exec(compile('a=5\nb=7\nprint(a+b)','','exec'))
12
Here, ‘exec’ is the mode. The parameter before that is the filename for the file form which the code is read.
Finally, we execute it using exec().
13. Python complex()
Python complex() function creates a complex number. We have seen this is our article on Python Numbers.
1. >>> complex(3)
(3+0j)
1. >>> complex(3.5)
(3.5+0j)
1. >>> complex(3+5j)
(3+5j)
14. Python delattr()
Python delattr() takes two arguments- a class, and an attribute in it. It deletes the attribute.
1. >>> class fruit:
2. size=7
3. >>> orange=fruit()
4. >>> orange.size
7
1. >>> delattr(fruit,'size')
2. >>> orange.size
3. Traceback (most recent call last):
4. File "<pyshell#95>", line 1, in <module>
5. orange.size
AttributeError: ‘fruit’ object has no attribute ‘size’
15. Python dict()
Python dict(), as we have seen it, creates a python dictionary.
1. >>> dict()
2. {}
3. >>> dict([(1,2),(3,4)])
{1: 2, 3: 4}
This was about dict() Python Built In function
16. Python dir()
Python dir() returns an object’s attributes.
1. >>> class fruit:
2. size=7
3. shape='round'
4. >>> orange=fruit()
5. >>> dir(orange)
[‘__class__’, ‘__delattr__’, ‘__dict__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’,
‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__ne__’, ‘__new__’,
‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’,
‘__weakref__’, ‘shape’, ‘size’]
17. Python divmod()
Python divmod() in Python built-in functions, takes two parameters, and returns a tuple of their quotient and
remainder. In other words, it returns the floor division and the modulus of the two numbers.
1. >>> divmod(3,7)
(0, 3)
1. >>> divmod(7,3)
(2, 1)
If you encounter any doubt in Python Built-in Function, Please Comment.
18. Python enumerate()
This Python Built In function returns an enumerate object. In other words, it adds a counter to the iterable.
1. >>> for i in enumerate(['a','b','c']):
2. print(i)
(0, ‘a’)
(1, ‘b’)
(2, ‘c’)
19. Python eval()
This Function takes a string as an argument, which is parsed as an expression.
1. >>> x=7
2. >>> eval('x+7')
14
1. >>> eval('x+(x%2)')
8
20. Python exec()
Python exec() runs Python code dynamically.
1. >>> exec('a=2;b=3;print(a+b)')
5
1. >>> exec(input("Enter your program"))
Enter your programprint(2+3)
5
21. Python filter()
Like we’ve seen in python Lambda Expressios, filter() filters out the items for which the condition is True.
1. >>> list(filter(lambda x:x%2==0,[1,2,0,False]))
[2, 0, False]
22. Python float()
This Python Built IN function converts an int or a compatible value into a float.
1. >>> float(2)
2.0
1. >>> float('3')
3.0
1. >>> float('3s')
2. Traceback (most recent call last):
3. File "<pyshell#136>", line 1, in <module>
4. float('3s')
ValueError: could not convert string to float: ‘3s’
1. >>> float(False)
0.0
1. >>> float(4.7)
4.7
23. Python format()
We have seen this Python built-in function, one in our lesson on Python Strings.
1. >>> a,b=2,3
2. >>> print("a={0} and b={1}".format(a,b))
3. a=2 and b=3
4. >>> print("a={a} and b={b}".format(a=3,b=4))
5. a=3 and b=4
24. Python frozenset()
Python frozenset() returns an immutable frozenset object.
1. >>> frozenset((3,2,4))
frozenset({2, 3, 4})
Read Python Sets and Booleans for more on frozenset.
25. Python getattr()
Python getattr() returns the value of an object’s attribute.
1. >>> getattr(orange,'size')
7
26. Python globals()
This Python built-in functions, returns a dictionary of the current global symbol table.
1. >>> globals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’
(built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’: <__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1,
2, 3], ‘i’: (2, 3), ‘x’: 7, ‘b’: 3}
27. Python hasattr()
Like delattr() and getattr(), hasattr() Python built-in functions, returns True if the object has that attribute.
1. >>> hasattr(orange,'size')
True
1. >>> hasattr(orange,'shape')
True
1. >>> hasattr(orange,'color')
False
28. Python hash()
Python hash() function returns the hash value of an object. And in Python, everything is an object.
1. >>> hash(orange)
6263677
1. >>> hash(orange)
6263677
1. >>> hash(True)
1
1. >>> hash(0)
0
1. >>> hash(3.7)
644245917
1. >>> hash(hash)
25553952
This was all about hash() Python In Built function
29. Python help()
To get details about any module, keyword, symbol, or topic, we use the help() function.
1. >>> help()
Welcome to Python 3.6’s help utility!
If this is your first time using Python, you should definitely check out the tutorial on the Internet at
http://docs.python.org/3.6/tutorial/.Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and return to the interpreter, just type “quit”.
To get a list of available modules, keywords, symbols, or topics, type “modules”, “keywords”, “symbols”, or
“topics”. Each module also comes with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as “spam”, type “modules spam”.
help> map
Help on class map in module builtins:
class map(object)
| map(func, *iterables) –> map object
|
| Make an iterator that computes the function using arguments from
| each of the iterables. Stops when the shortest iterable is exhausted.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(…)
| Return state information for pickling.
help>
You are now leaving help and returning to the Python interpreter.If you want to ask for help on a particular object
directly from the interpreter, you can type “help(object)”. Executing “help(‘string’)” has the same effect as typing a
particular string at the help> prompt.
>>>
30. Python hex()
Hex() Python built-in functions, converts an integer to hexadecimal.
1. >>> hex(16)
‘0x10’
1. >>> hex(False)
‘0x0’
31. Python id() Function
Python id() returns an object’s identity.
1. >>> id(orange)
100218832
1. >>> id({1,2,3})==id({1,3,2})
True
32. Python input()
Input() Python built-in functions, reads and returns a line of string.
1. >>> input("Enter a number")
Enter a number7
‘7’
Note that this returns the input as a string. If we want to take 7 as an integer, we need to apply the int() function to it.
1. >>> int(input("Enter a number"))
Enter a number7
7
33. Python int()
Python int() converts a value to an integer.
1. >>> int('7')
7
34. Python isinstance()
We have seen this one in previous lessons. isinstance() takes a variable and a class as arguments. Then, it returns True
if the variable belongs to the class. Otherwise, it returns False.
1. >>> isinstance(0,str)
False
1. >>> isinstance(orange,fruit)
True
35. Python issubclass()
This Python Built In function takes two arguments- twopython classes. If the first class is a subclass of the second, it
returns True. Otherwise, it returns False.
1. >>> issubclass(fruit,fruit)
True
1. >>> class fruit:
2. pass
3. >>> class citrus(fruit):
4. pass
5. >>> class citrus(fruit):
True
1. >>> issubclass(fruit,citrus)
False
36. Python iter()
Iter() Python built-in functions, returns a python iteratorfor an object.
1. >>> for i in iter([1,2,3]):
2. print(i)
1
2
3
37. Python len()
We’ve seen Python len() so many times by now. It returns the length of an object.
1. >>> len({1,2,2,3})
3
Here, we get 3 instead of 4, because the set takes the value ‘2’ only once.
38. Python list()
Python list() creates a list from a sequence of values.
1. >>> list({1,3,2,2})
[1, 2, 3]
39. Python locals()
This function returns a dictionary of the current local symbol table.
1. >>> locals()
{‘__name__’: ‘__main__’, ‘__doc__’: None, ‘__package__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__spec__’: None, ‘__annotations__’: {}, ‘__builtins__’: <module ‘builtins’
(built-in)>, ‘fruit’: <class ‘__main__.fruit’>, ‘orange’: <__main__.fruit object at 0x05F937D0>, ‘a’: 2, ‘numbers’: [1,
2, 3], ‘i’: 3, ‘x’: 7, ‘b’: 3, ‘citrus’: <class ‘__main__.citrus’>}
40. Python map()
Like filter(), map() Python built-in functions, takes a function and applies it on an iterable. It maps True or False
values on each item in the iterable.
1. >>> list(map(lambda x:x%2==0,[1,2,3,4,5]))
[False, True, False, True, False]
41. Python max()
A no-brainer, Python max() returns the item, in a sequence, with the highest value of all.
1. >>> max(2,3,4)
4
1. >>> max([3,5,4])
5
1. >>> max('hello','Hello')
‘hello’
42. Python memoryview()
Python memoryview() shows us the memory view of an argument.
1. >>> a=bytes(4)
2. >>> memoryview(a)
3. <memory at 0x05F9A988>
4. >>> for i in memoryview(a):
5. print(i)
0
0
0
0
43. Python min()
Python min() returns the lowest value in a sequence.
1. >>> min(3,5,1)
1
1. >>> min(True,False)
False
44. Python next()
This Python Built In function returns the next element from the iterator.
1. >>> myIterator=iter([1,2,3,4,5])
2. >>> next(myIterator)
1
1. >>> next(myIterator)
2
1. >>> next(myIterator)
3
1. >>> next(myIterator)
4
1. >>> next(myIterator)
5
Now that we’ve traversed all items, when we call next(), it raises StopIteration.
1. >>> next(myIterator)
2. Traceback (most recent call last):
3. File "<pyshell#392>", line 1, in <module>
4. next(myIterator)
StopIteration
45. Python object()
Object() Python built-in functions, creates a featureless object.
1. >>> o=object()
2. >>> type(o)
<class ‘object’>
1. >>> dir(o)
[‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’,
‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’,
‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’]
Here, the function type() tells us that it’s an object. dir() tells us the object’s attributes. But since this does not have the
__dict__ attribute, we can’t assign to arbitrary attributes.
46. Python oct()
Python oct() converts an integer to its octal representation.
1. >>> oct(7)
‘0o7’
1. >>> oct(8)
‘0o10’
1. >>> oct(True)
‘0o1’
47. Python open()
Python open() lets us open a file. Let’s change the current working directory to Desktop.
1. >>> import os
2. >>> os.chdir('C:\\Users\\lifei\\Desktop')
Now, we open the file ‘topics.txt’.
1. >>> f=open('topics.txt')
2. >>> f
3. <_io.TextIOWrapper name='topics.txt' mode='r' encoding='cp1252'>
4. >>> type(f)
<class ‘_io.TextIOWrapper’>
To read from the file, we use the read() method.
1. >>> print(f.read())
DBMS mappings
projection
union
rdbms vs dbms
doget dopost
how to add maps
OOT
SQL queries
Join
Pattern programs
Output
Default constructor in inheritance
48. Python ord()
The function ord() returns an integer that represents the Unicode point for a given Unicode character.
1. >>> ord('A')
65
1. >>> ord('9')
57
This is complementary to chr().
1. >>> chr(65)
‘A’
49. Python pow()
Python pow() takes two arguments- say, x and y. It then returns the value of x to the power of y.
1. >>> pow(3,4)
81
1. >>> pow(7,0)
1
1. >>> pow(7,-1)
0.14285714285714285
1. >>> pow(7,-2)
0.02040816326530612
50. Python print()
We don’t think we need to explain this anymore. We’ve been seeing this function since the beginning of this article.
1. >>> print("Okay, next function, please!")
Okay, next function, please!
51.Python property()
The function property() returns a property attribute. Alternatively, we can use the syntactic sugar @property. We will
learn this in detail in our tutorial on Python Property.
52. range()
We’ve taken a whole tutorial on this. Read up range() in Python.
1. >>> for i in range(7,2,-2):
2. print(i)
7
5
3
53. Python repr()
Python repr() returns a representable string of an object.
1. >>> repr("Hello")
“‘Hello'”
1. >>> repr(7)
‘7’
1. >>> repr(False)
‘False’
54. Python reversed()
This functions reverses the contents of an iterable and returns an iterator object.
1. >>> a=reversed([3,2,1])
2. >>> a
3. <list_reverseiterator object at 0x02E1A230>
4. >>> for i in a:
5. print(i)
1
2
3
1. >>> type(a)
<class ‘list_reverseiterator’>
55. Python round()
Python round() rounds off a float to the given number of digits (given by the second argument).
1. >>> round(3.777,2)
3.78
1. >>> round(3.7,3)
3.7
1. >>> round(3.7,-1)
0.0
1. >>> round(377.77,-1)
380.0
The rounding factor can be negative.
56. Python set()
Of course, Python set() returns a set of the items passed to it.
1. >>> set([2,2,3,1])
{1, 2, 3}
Remember, a set cannot have duplicate values, and isn’t indexed, but is ordered. Read on Sets and Booleans for the
same.
57. Python setattr()
Like getattr(),Python setattr() sets an attribute’s value for an object.
1. >>> orange.size
7
1. >>> orange.size=8
2. >>> orange.size
8
58. Python slice()
Python slice() returns a slice object that represents the set of indices specified by range(start, stop, step).
1. >>> slice(2,7,2)
slice(2, 7, 2)
We can use this to iterate on an iterable like a string in python.
1. >>> 'Python'[slice(1,5,2)]
‘yh’
59. Python sorted()
Like we’ve seen before, Python sorted() prints out a sorted version of an iterable. It does not, however, alter the
iterable.
1. >>> sorted('Python')
[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]
1. >>> sorted([1,3,2])
[1, 2, 3]
60. Python staticmethod()
Python staticmethod() creates a static method from a function. A static method is bound to a class rather than to an
object. But it can be called on the class or on an object.
1. >>> class fruit:
2. def sayhi():
3. print("Hi")
4. >>> fruit.sayhi=staticmethod(fruit.sayhi)
5. >>> fruit.sayhi()
Hi
You can also use the syntactic sugar @staticmethod for this.
1. >>> class fruit:
2. @staticmethod
3. def sayhi():
4. print("Hi")
5. >>> fruit.sayhi()
Hi
61. Python str()
Python str() takes an argument and returns the string equivalent of it.
1. >>> str('Hello')
‘Hello’
1. >>> str(7)
‘7’
1. >>> str(8.7)
‘8.7’
1. >>> str(False)
‘False’
1. >>> str([1,2,3])
‘[1, 2, 3]’
62. Python sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.
1. >>> sum([3,4,5],3)
15
63. Python super()
Python super() returns a proxy object to let you refer to the parent class.
1. >>> class person:
2. def __init__(self):
3. print("A person")
4. >>> class student(person):
5. def __init__(self):
6. super().__init__()
7. print("A student")
8. >>> Avery=student()
A person
A student
64. Python tuple()
As we’ve seen in our tutorial on Python Tuples, the function tuple() lets us create a tuple.
1. >>> tuple([1,3,2])
(1, 3, 2)
1. >>> tuple({1:'a',2:'b'})
(1, 2)
65. Python type()
We have been seeing the type() function to check the type of object we’re dealing with.
1. >>> type({})
<class ‘dict’>
1. >>> type(set())
<class ‘set’>
1. >>> type(())
<class ‘tuple’>
1. >>> type((1))<span style="background-color: #fafafa;color: #333333;font-family: Verdana, Geneva, sans-
serif;font-size: 16px;font-weight: inherit"> </span>
<class ‘int’>
1. >>> type((1,))
<class ‘tuple’>
66. Python vars()
Python vars() function returns the __dict__ attribute of a class.
1. >>> vars(fruit)
mappingproxy({‘__module__’: ‘__main__’, ‘size’: 7, ‘shape’: ’round’, ‘__dict__’: <attribute ‘__dict__’ of ‘fruit’
objects>, ‘__weakref__’: <attribute ‘__weakref__’ of ‘fruit’ objects>, ‘__doc__’: None})
67. Python zip()
Python zip() returns us an iterator of tuples.
1. >>> set(zip([1,2,3],['a','b','c']))
{(1, ‘a’), (3, ‘c’), (2, ‘b’)}
1. >>> set(zip([1,2],[3,4,5]))
{(1, 3), (2, 4)}
1. >>> a=zip([1,2,3],['a','b','c'])
To unzip this, we write the following code.
1. >>> x,y,z=a
2.
3. >>> x
(1, ‘a’)
1. >>> y
(2, ‘b’)
1. >>> z
(3, ‘c’)
Isn’t this just like tuple unpacking?
A module allows you to logically organize your
Python code. Grouping related code into a module
makes the code easier to understand and use. A
module is a Python object with arbitrarily named
attributes that you can bind and reference.
Simply, a module is a file consisting of Python
code. A module can define functions, classes and
variables. A module can also include runnable code.
Python Modules
A module is a file containing Python definitions and
statements. A module can define functions, classes
and variables. A module can also include runnable
code. Grouping related code into a module makes
the code easier to understand and use.
Example:
# A simple module, calc.py
def add(x, y):
return(x+y)
def subtract(x, y):
return(x-y)
The import statement
We can use any Python source file as a module by
executing an import statement in some other Python
source file.
When interpreter encounters an import statement, it
imports the module if the module is present in the search
path. A search path is a list of directories that the
interpreter searches for importing a module. For
example, to import the module calc.py, we need to put
the following command at the top of the script :
# importing module calc.py
import calc
print(add(10, 2) )
Output:
12
The from import Statement
Python’s from statement lets you import specific
attributes from a module. The from .. import .. has the
following syntax :
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16) )
print(factorial(6) )
Output:
4.0
720
Code Snippet illustrating python built-in modules:
# importing built-in module math
import math
# 1 * 2 * 3 * 4 = 24
printmath.factorial(4)
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06
Example
The Python code for a module
named aname normally resides in a file
named aname.py. Here's an example of a simple
module, support.py
defprint_func( par):
print"Hello : ", par
return
Python Packages
Suppose you have developed a very large application that includes many
modules. As the number of modules grows, it becomes difficult to keep track
of them all if they are dumped into one location. This is particularly so if they
have similar names or functionality. You might wish for a means of grouping
and organizing them.
mod1.py
def foo():
print('[mod1] foo()')
class Foo:
pass
mod2.py
def bar():
print('[mod2] bar()')
class Bar:
pass
Given this structure, if the pkg directory resides in a location where it can be
found (in one of the directories contained in sys.path), you can refer to the
two modules with dot notation(pkg.mod1, pkg.mod2) and import them with the
syntax you are already familiar with:
import<module_name>[,<module_name>...]
>>>importpkg.mod1,pkg.mod2
>>>pkg.mod1.foo()
[mod1] foo()
>>>x=pkg.mod2.Bar()
>>>x
<pkg.mod2.Bar object at 0x033F7290>
from<module_name>import<name(s)>
>>>frompkg.mod1importfoo
>>>foo()
[mod1] foo()
from<module_name>import<name>as<alt_name>
Package Initialization
If a file named __init__.py is present in a package directory, it is invoked when
the package or a module in the package is imported. This can be used for
execution of package initialization code, such as initialization of package-level
data.
For example, consider the following __init__.py file:
__init__.py
>>>importpkg
Invoking __init__.py for pkg
>>>pkg.A
['quux', 'corge', 'grault']
A module in the package can access the global by importing it in turn:
mod1.py
deffoo():
frompkgimportA
print('[mod1] foo() / A = ',A)
classFoo:
pass
>>>frompkgimportmod1
Invoking __init__.py for pkg
>>>mod1.foo()
[mod1] foo() / A = ['quux', 'corge', 'grault']
__init__.py can also be used to effect automaticimporting of modules from a
package. For example, earlier you saw that the statement import pkg only
places the name pkg in the caller’s local symbol table and doesn’t import any
modules. But if __init__.py in the pkgdirectory contains the following:
__init__.py
>>>importpkg
Invoking __init__.py for pkg
>>>pkg.mod1.foo()
[mod1] foo()
>>>pkg.mod2.bar()
[mod2] bar()
Subpackages
Packages can contain nested subpackages to arbitrary depth. For example,
let’s make one more modification to the example package directory as
follows:
The four modules (mod1.py, mod2.py, mod3.py and mod4.py) are defined as
previously. But now, instead of being lumped together into the pkg directory,
they are split out into two subpackage directories, sub_pkg1 and sub_pkg2.
Importing still works the same as shown previously. Syntax is similar, but
additional dot notation is used to separate package name
from subpackage name:
>>>importpkg.sub_pkg1.mod1
>>>pkg.sub_pkg1.mod1.foo()
[mod1] foo()
>>>frompkg.sub_pkg1importmod2
>>>mod2.bar()
[mod2] bar()
>>>frompkg.sub_pkg2.mod3importbaz
>>>baz()
[mod3] baz()
>>>frompkg.sub_pkg2.mod4importquxasgrault
>>>grault()
[mod4] qux()
In addition, a module in one subpackage can reference objects in a sibling
subpackage (in the event that the sibling contains some functionality that you
need). For example, suppose you want to import and execute
function foo() (defined in module mod1) from within module mod3. You can
either use an absolute import:
pkg/sub__pkg2/mod3.py
defbaz():
print('[mod3] baz()')
classBaz:
pass
frompkg.sub_pkg1.mod1importfoo
foo()
>>>frompkg.sub_pkg2importmod3
[mod1] foo()
>>>mod3.foo()
[mod1] foo()
Or you can use a relative import, where .. refers to the package one level
up. From within mod3.py, which is in subpackage sub_pkg2,
pkg/sub__pkg2/mod3.py
defbaz():
print('[mod3] baz()')
classBaz:
pass
from..importsub_pkg1
print(sub_pkg1)
from..sub_pkg1.mod1importfoo
foo()
>>>frompkg.sub_pkg2importmod3
<module 'pkg.sub_pkg1' (namespace)>
[mod1] foo()
Data member − A class variable or instance variable that holds data associated
with a class and its objects.
Creating Classes
The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
class ClassName:
class_suite
Example
Following is an example of a simple Python class −
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
The variable empCount is a class variable whose value is shared among all the
instances of a in this class. This can be accessed as Employee.empCount from
inside the class or outside the class.
The first method __init__() is a special method, which is called class constructor
or initialization method that Python calls when you create a new instance of this
class.
You declare other class methods like normal functions with the exception that
the first argument to each method is self. Python adds the self argument to the
list for you; you do not need to include it when you call the methods.
Accessing Attributes
You access the object's attributes using the dot operator with object. Class
variable would be accessed using class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
#!/usr/bin/python3
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
emp1.displayEmployee()
emp2.displayEmployee()
Instead of using the normal statements to access attributes, you can use
the following functions −
__bases__ − A possibly empty tuple containing the base classes, in the order
of their occurrence in the base class list.
For the above class let us try to access all these attributes −
Live Demo
#!/usr/bin/python3
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
You normally will not notice when the garbage collector destroys an
orphaned instance and reclaims its space. However, a class can implement
the special method __del__(), called a destructor, that is invoked when the
instance is about to be destroyed. This method might be used to clean up
any non-memory resources used by an instance.
Example
This __del__() destructor prints the class name of an instance that is about
to be destroyed −
Live Demo
#!/usr/bin/python3
class Point:
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
pt1 = Point()
pt2 = pt1
pt3 = pt1
del pt1
del pt2
del pt3
Note − Ideally, you should define your classes in a separate file, then you
should import them in your main program file using import statement.
#!/usr/bin/python3
import point
p1 = point.Point()
Class Inheritance
Instead of starting from a scratch, you can create a class by deriving it from
a pre-existing class by listing the parent class in parentheses after the new
class name.
The child class inherits the attributes of its parent class, and you can use
those attributes as if they were defined in the child class. A child class can
also override data members and methods from the parent.
Syntax
Derived classes are declared much like their parent class; however, a list of
base classes to inherit from is given after the class name −
class_suite
Example
Live Demo
#!/usr/bin/python3
parentAttr = 100
def __init__(self):
def parentMethod(self):
Parent.parentAttr = attr
def getAttr(self):
def __init__(self):
def childMethod(self):
In a similar way, you can drive a class from multiple parent classes as
follows −
.....
.....
Overriding Methods
You can always override your parent class methods. One reason for
overriding parent's methods is that you may want special or different
functionality in your subclass.
Example
Live Demo
#!/usr/bin/python3
def myMethod(self):
def myMethod(self):
2 __del__( self )
3 __repr__( self )
4 __str__( self )
5 __cmp__ ( self, x )
Object comparison
Overloading Operators
Suppose you have created a Vector class to represent two-dimensional
vectors. What happens when you use the plus operator to add them? Most
likely Python will yell at you.
You could, however, define the __add__ method in your class to perform
vector addition and then the plus operator would behave as per expectation
−
Example
Live Demo
#!/usr/bin/python3
class Vector:
self.a = a
self.b = b
def __str__(self):
def __add__(self,other):
v1 = Vector(2,10)
v2 = Vector(5,-2)
Data Hiding
An object's attributes may or may not be visible outside the class definition.
You need to name attributes with a double underscore prefix, and those
attributes then will not be directly visible to outsiders.
Example
Live Demo
#!/usr/bin/python3
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)
.........................
print (counter._JustCounter__secretCount)
When the above code is executed, it produces the following result −
1
2
2
A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions
are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re
module raises the exception re.error if an error occurs while compiling or using a regular
expression.
We would cover two important functions, which would be used to handle regular
expressions. But a small thing first: There are various characters, which would have special
meaning when they are used in regular expression. To avoid any confusion while dealing
with regular expressions, we would use Raw Strings as r'expression'.
The match Function
This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Here is the description of the parameters −
Sr.No. Parameter & Description
1 pattern
This is the regular expression to be matched.
2 string
This is the string, which would be searched to match the pattern at
the beginning of string.
3 flags
You can specify different flags using bitwise OR (|). These are
modifiers, which are listed in the table below.
The re.match function returns a match object on success, None on failure. We
usegroup(num) or groups() function of match object to get matched expression.
Sr.No. Match Object Method & Description
1 group(num=0)
This method returns entire match (or specific subgroup num)
2 groups()
This method returns all matching subgroups in a tuple (empty if
there weren't any)
Example
#!/usr/bin/python
import re
ifmatchObj:
print"matchObj.group() : ",matchObj.group()
print"matchObj.group(1) : ",matchObj.group(1)
print"matchObj.group(2) : ",matchObj.group(2)
else:
print"No match!!"
When the above code is executed, it produces following result −
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
The search Function
This function searches for first occurrence of RE pattern within string with optional flags.
Here is the syntax for this function −
re.search(pattern, string, flags=0)
Here is the description of the parameters −
Sr.No. Parameter & Description
1 pattern
This is the regular expression to be matched.
2 string
This is the string, which would be searched to match the pattern
anywhere in the string.
3 flags
You can specify different flags using bitwise OR (|). These are
modifiers, which are listed in the table below.
The re.search function returns a match object on success, none on failure. We
use group(num) or groups() function of match object to get matched expression.
Sr.No. Match Object Methods & Description
1 group(num=0)
This method returns entire match (or specific subgroup num)
2 groups()
This method returns all matching subgroups in a tuple (empty if
there weren't any)
Example
#!/usr/bin/python
import re
ifsearchObj:
print"searchObj.group() : ",searchObj.group()
print"searchObj.group(1) : ",searchObj.group(1)
print"searchObj.group(2) : ",searchObj.group(2)
else:
print"Nothing found!!"
When the above code is executed, it produces following result −
searchObj.group() : Cats are smarter than dogs
searchObj.group(1) : Cats
searchObj.group(2) : smarter
Matching Versus Searching
Python offers two different primitive operations based on regular
expressions: match checks for a match only at the beginning of the string,
while searchchecks for a match anywhere in the string (this is what Perl does by default).
Example
#!/usr/bin/python
import re
ifmatchObj:
else:
print"No match!!"
searchObj=re.search(r'dogs', line,re.M|re.I)
ifsearchObj:
else:
print"Nothing found!!"
When the above code is executed, it produces the following result −
No match!!
search -->matchObj.group() : dogs
Search and Replace
One of the most important re methods that use regular expressions is sub.
Syntax
re.sub(pattern, repl, string, max=0)
This method replaces all occurrences of the RE pattern in string with repl, substituting all
occurrences unless max provided. This method returns modified string.
Example
#!/usr/bin/python
import re
num=re.sub(r'#.*$',"", phone)
1 re.I
Performs case-insensitive matching.
2 re.L
Interprets words according to the current locale. This interpretation
affects the alphabetic group (\w and \W), as well as word boundary
behavior(\b and \B).
3 re.M
Makes $ match the end of a line (not just the end of the string) and
makes ^ match the start of any line (not just the start of the string).
4 re.S
Makes a period (dot) match any character, including a newline.
5 re.U
Interprets letters according to the Unicode character set. This flag
affects the behavior of \w, \W, \b, \B.
6 re.X
Permits "cuter" regular expression syntax. It ignores whitespace
(except inside a set [] or when escaped by a backslash) and treats
unescaped # as a comment marker.
Regular Expression Patterns
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You
can escape a control character by preceding it with a backslash.
Following table lists the regular expression syntax that is available in Python −
Sr.No. Pattern & Description
1 ^
Matches beginning of line.
2 $
Matches end of line.
3 .
Matches any single character except newline. Using m option allows
it to match newline as well.
4 [...]
Matches any single character in brackets.
5 [^...]
Matches any single character not in brackets
6 re*
Matches 0 or more occurrences of preceding expression.
7 re+
Matches 1 or more occurrence of preceding expression.
8 re?
Matches 0 or 1 occurrence of preceding expression.
9 re{ n}
Matches exactly n number of occurrences of preceding expression.
10 re{ n,}
Matches n or more occurrences of preceding expression.
11 re{ n, m}
Matches at least n and at most m occurrences of preceding
expression.
12 a| b
Matches either a or b.
13 (re)
Groups regular expressions and remembers matched text.
14 (?imx)
Temporarily toggles on i, m, or x options within a regular
expression. If in parentheses, only that area is affected.
15 (?-imx)
Temporarily toggles off i, m, or x options within a regular
expression. If in parentheses, only that area is affected.
16 (?: re)
Groups regular expressions without remembering matched text.
17 (?imx: re)
Temporarily toggles on i, m, or x options within parentheses.
18 (?-imx: re)
Temporarily toggles off i, m, or x options within parentheses.
19 (?#...)
Comment.
20 (?= re)
Specifies position using a pattern. Doesn't have a range.
21 (?! re)
Specifies position using pattern negation. Doesn't have a range.
22 (?> re)
Matches independent pattern without backtracking.
23 \w
Matches word characters.
24 \W
Matches nonword characters.
25 \s
Matches whitespace. Equivalent to [\t\n\r\f].
26 \S
Matches nonwhitespace.
27 \d
Matches digits. Equivalent to [0-9].
28 \D
Matches nondigits.
29 \A
Matches beginning of string.
30 \Z
Matches end of string. If a newline exists, it matches just before
newline.
31 \z
Matches end of string.
32 \G
Matches point where last match finished.
33 \b
Matches word boundaries when outside brackets. Matches
backspace (0x08) when inside brackets.
34 \B
Matches nonword boundaries.
36 \1...\9
Matches nth grouped subexpression.
37 \10
Matches nth grouped subexpression if it matched already. Otherwise
refers to the octal representation of a character code.
Regular Expression Examples
Literal characters
Sr.No. Example & Description
1 python
Match "python".
Character classes
Sr.No. Example & Description
1 [Pp]ython
Match "Python" or "python"
2 rub[ye]
Match "ruby" or "rube"
3 [aeiou]
Match any one lowercase vowel
4 [0-9]
Match any digit; same as [0123456789]
5 [a-z]
Match any lowercase ASCII letter
6 [A-Z]
Match any uppercase ASCII letter
7 [a-zA-Z0-9]
Match any of the above
8 [^aeiou]
Match anything other than a lowercase vowel
9 [^0-9]
Match anything other than a digit
Special Character Classes
Sr.No. Example & Description
1 .
Match any character except newline
2 \d
Match a digit: [0-9]
3 \D
Match a nondigit: [^0-9]
4 \s
Match a whitespace character: [ \t\r\n\f]
5 \S
Match nonwhitespace: [^ \t\r\n\f]
6 \w
Match a single word character: [A-Za-z0-9_]
7 \W
Match a nonword character: [^A-Za-z0-9_]
Repetition Cases
Sr.No. Example & Description
1 ruby?
Match "rub" or "ruby": the y is optional
2 ruby*
Match "rub" plus 0 or more ys
3 ruby+
Match "rub" plus 1 or more ys
4 \d{3}
Match exactly 3 digits
5 \d{3,}
Match 3 or more digits
6 \d{3,5}
Match 3, 4, or 5 digits
Nongreedy repetition
This matches the smallest number of repetitions −
Sr.No. Example & Description
1 <.*>
Greedy repetition: matches "<python>perl>"
2 <.*?>
Nongreedy: matches "<python>" in "<python>perl>"
Grouping with Parentheses
Sr.No. Example & Description
1 \D\d+
No group: + repeats \d
2 (\D\d)+
Grouped: + repeats \D\d pair
3 ([Pp]ython(, )?)+
Match "Python", "Python, python, python", etc.
Backreferences
This matches a previously matched group again −
Sr.No. Example & Description
1 ([Pp])ython&\1ails
Match python&pails or Python&Pails
2 (['"])[^\1]*\1
Single or double-quoted string. \1 matches whatever the 1st group
matched. \2 matches whatever the 2nd group matched, etc.
Alternatives
Sr.No. Example & Description
1 python|perl
Match "python" or "perl"
2 rub(y|le))
Match "ruby" or "ruble"
3 Python(!+|\?)
"Python" followed by one or more !or one ?
Anchors
This needs to specify match position.
Sr.No. Example & Description
1 ^Python
Match "Python" at the start of a string or internal line
2 Python$
Match "Python" at the end of a string or line
3 \APython
Match "Python" at the start of a string
4 Python\Z
Match "Python" at the end of a string
5 \bPython\b
Match "Python" at a word boundary
6 \brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not
alone
7 Python(?=!)
Match "Python", if followed by an exclamation point.
8 Python(?!!)
Match "Python", if not followed by an exclamation point.
Special Syntax with Parentheses
Sr.No. Example & Description
1 R(?#comment)
Matches "R". All the rest is a comment
2 R(?i)uby
Case-insensitive while matching "uby"
3 R(?i:uby)
Same as above
4 rub(?:y|le))
Group only without creating \1 backreference
PYTHON - GUI PROGRAMMING TkinterTkinter
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.
wxPython − This is an open-source Python interface for wxWindows.
JPython − JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries
on the local machine.
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 −
Example
#!/usr/bin/python
import tkinter
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
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 −
Sr.No. Operator & Description
1 Button
The Button widget is used to display buttons in your application.
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
The Frame widget is used as a container widget to organize other widgets.
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also contain
images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.
8 Menubutton
The Menubutton widget is used to display menus in your application.
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
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes.
14 Text
The Text widget is used to display text in multiple lines.
15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
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
This module is used to display message boxes in your applications.
Output:
2. Canvas: It is used to draw pictures and other complex layout like graphics, text and widgets.
The general syntax is:
w = Canvas(master, option=value)
master is the parameter used to represent the parent window.
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.
bd: to set the border width in pixels.
bg: to set the normal background color.
cursor: to set the cursor used in the canvas.
highlightcolor: to set the color shown in the focus highlight.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Output:
3. CheckButton: To select any number of options by displaying a number of options to a user as toggle buttons.
The general syntax is:
w = CheckButton(master, option=value)
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.
Title: To set the title of the widget.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
bg: to set he normal backgrouSteganography
Break
Secret Code:
Attach a File:nd color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
from tkinter import *
master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()
Output:
4. 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:
w=Entry(master, option=value)
5. Frame: It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The
general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent window.
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.
bd: to set the border width in pixels.
bg: to set the normal background color.
cursor: to set the cursor used.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()
Output:
6. 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:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
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.
bg: to set he normal background color.
bg to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the button.
width: to set the width of the button.
height” to set the height of the button.
from tkinter import *
root = Tk()
w = Label(root, text='GeeksForGeeks.org!')
w.pack()
root.mainloop()
Output:
7. Listbox: It offers a list to the user from which the user can accept any number of options.
The general syntax is:
w = Listbox(master, option=value)
master is the parameter used to represent the parent window.
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.
bg: to set he normal background color.
bd: to set the border width in pixels.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()
Output:
8. 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:
w = MenuButton(master, option=value)
master is the parameter used to represent the parent window.
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.
activebackground: To set the background when mouse is over the widget.
activeforeground: To set the foreground when mouse is over the widget.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
highlightcolor: To set the color of the focus highlight when widget has to be focused.
from tkinter import *
top = Tk()
mb = Menubutton ( top, text = "GfG")
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
mb.menu.add_checkbutton ( label = 'About', variable = aVar )
mb.pack()
top.mainloop()
Output:
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.
title: To set the title of the widget.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
bg: to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
from tkinter import *
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()
Output:
10. Message: It refers to the multi-line and non-editable text. It works same as that of Label.
The general syntax is:
w = Message(master, option=value)
master is the parameter used to represent the parent window.
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.
bd: to set the border around the indicator.
bg: to set he normal background color.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
main = Tk()
ourMessage ='This is our Message'
messageVar = Message(main, text = ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack( )
main.mainloop( )
Output:
11. 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:
w = RadioButton(master, option=value)
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.
bg: to set he normal background color.
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the label in characters.
height: to set the height of the label in characters.
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()
Output:
12. Scale: It is used to provide a graphical slider that allows to select any value from that scale. The general syntax
is:
w = Scale(master, option=value)
master is the parameter used to represent the parent window.
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.
bg: to set he normal background color.
orient: Set it to HORIZONTAL or VERTICAL according to the requirement.
from_: To set the value of one end of the scale range.
to: To set the value of the other end of the scale range.
image: to set the image on the widget.
width: to set the width of the widget.
from tkinter import *
master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()
Output:
13. Scrollbar: It refers to the slide controller which will be used to implement listed widgets.
The general syntax is:
w = Scrollbar(master, option=value)
master is the parameter used to represent the parent window.
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.
width: to set the width of the widget.
activebackground: To set the background when mouse is over the widget.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
from tkinter import *
root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill = Y )
mylist = Listbox(root, yscrollcommand = scrollbar.set )
for line in range(100):
mylist.insert(END, 'This is line number' + str(line))
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )
mainloop()
Output:
14. Text: To edit a multi-line text and format the way it has to be displayed.
The general syntax is:
w =Text(master, option=value)
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.
insertbackground: To set the background of the widget.
bg: to set he normal background color.
font: to set the font on the button label.
image: to set the image on the widget.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'GeeksforGeeks\nBEST WEBSITE\n')
mainloop()
Output:
15. TopLevel: This widget is directly controlled by the window manager. It don’t need any parent window to work
on.The general syntax is:
w = TopLevel(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.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
width: to set the width of the widget.
height: to set the height of the widget.
from tkinter import *
root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()
Output:
16. SpinBox: It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The
general syntax is:
w = SpinBox(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.
bg: to set he normal background color.
bd: to set the size of border around the indicator.
cursor: To appear the cursor when the mouse over the menubutton.
command: To call a function.
width: to set the width of the widget.
activebackground: To set the background when mouse is over the widget.
disabledbackground: To disable the background when mouse is over the widget.
from_: To set the value of one end of the range.
to: To set the value of the other end of the range.
from tkinter import *
master = Tk()
w = Spinbox(master, from_ = 0, to = 10)
w.pack()
mainloop()
Output:
17. PannedWindowIt is a container widget which is used to handle number of panes arranged in it. The general
syntax is:
w = PannedWindow(master, option=value)
Output:
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.
The place Method − This geometry manager organizes widgets by placing them in a specific position in the
parent widget.
This geometry manager organizes widgets in blocks before placing them in the parent widget.
Syntax
widget.pack( pack_options )
expand − When set to true, widget expands to fill any space not otherwise used in widget's parent.
fill − Determines whether widget fills any extra space allocated to it by the packer, or keeps its own minimal
dimensions: NONE defaultdefault, X fillonlyhorizontallyfillonlyhorizontally,
Y fillonlyverticallyfillonlyvertically, or
BOTH fillbothhorizontallyandverticallyfillbothhorizontallyandvertically.
side − Determines which side of the parent widget packs against: TOP defaultdefault, BOTTOM, LEFT, or
RIGHT.
Example
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text="Red", fg="red")
redbutton.pack( side = LEFT)
root.mainloop()
This geometry manager organizes widgets in a table-like structure in the parent widget.
Syntax
widget.grid( grid_options )
Example
import Tkinter
root = Tkinter.Tk( )
for r in range(3):
for c in range(4):
Tkinter.Label(root, text='R%s/C%s'%(r,c),
borderwidth=1 ).grid(row=r,column=c)
root.mainloop( )
This would produce the following result displaying 12 labels arrayed in a 3 × 4 grid −
This geometry manager organizes widgets by placing them in a specific position in the parent widget.
Syntax
widget.place( place_options )
anchor − The exact spot of widget other options refer to: may be N, E, S, W, NE, NW, SE, or SW, compass
directions indicating the corners and sides of widget; default is
NW theupperleftcornerofwidgettheupperleftcornerofwidget
bordermode − INSIDE thedefaultthedefault to indicate that other options refer to the parent's
inside ignoringtheparent′sborderignoringtheparent′sborder; OUTSIDE otherwise.
height, width − Height and width in pixels.
relheight, relwidth − Height and width as a float between 0.0 and 1.0, as a fraction of the height and width of
the parent widget.
relx, rely − Horizontal and vertical offset as a float between 0.0 and 1.0, as a fraction of the height and width
of the parent widget.
x, y − Horizontal and vertical offset in pixels.
Example
import tkMessageBox
import Tkinter
top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged
between the web server and a custom script. The CGI specs are currently maintained by the NCSA.
What is CGI?
The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with
information servers such as HTTP servers.
The current version is CGI/1.1 and CGI/1.2 is under progress.
Web Browsing
To understand the concept of CGI, let us see what happens when we click a hyper link to browse a
particular web page or URL.
Your browser contacts the HTTP web server and demands for the URL, i.e., filename.
Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser,
otherwise sends an error message indicating that you requested a wrong file.
Web browser takes response from web server and displays either the received file or error message.
However, it is possible to set up the HTTP server so that whenever a file in a certain directory is requested
that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back
for your browser to display. This function is called the Common Gateway Interface or CGI and the
programs are called CGI scripts. These CGI programs can be a Python Script, PERL Script, Shell Script, C
or C++ program, etc.
CGI Architecture Diagram
<Directory"/var/www/cgi-bin">
AllowOverride None
Options ExecCGI
Order allow,deny
</Directory>
<Directory"/var/www/cgi-bin">
Options All
</Directory>
Here, we assume that you have Web Server up and running successfully and you are able to run any other
CGI program like Perl or Shell, etc.
print("Content-type:text/html\r\n\r\n")
print('<html>')
print('<head>')
print('<title>Hello Word - First CGI Program</title>')
print('</head>')
print('<body>')
print('<h2>Hello Word! This is my first CGI program</h2>')
print('</body>')
print('</html>')
If you click hello.py, then this produces the following output −
HTTP Header
The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand
the content. All the HTTP header will be in the following form −
HTTP Field Name: Field Content
For Example
Content-type: text/html\r\n\r\n
There are few other important HTTP headers, which you will use frequently in your CGI Programming.
Sr.No. Header & Description
1 Content-type:
A MIME string defining the format of the file being returned. Example is Content-
type:text/html
2 Expires: Date
The date the information becomes invalid. It is used by the browser to decide when a page
needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.
3 Location: URL
The URL that is returned instead of the URL requested. You can use this field to redirect a
request to any file.
4 Last-modified: Date
The date of last modification of the resource.
5 Content-length: N
The length, in bytes, of the data being returned. The browser uses this value to report the
estimated download time for a file.
6 Set-Cookie: String
Set the cookie passed through the string
1 CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to the server.
For example, file upload.
2 CONTENT_LENGTH
The length of the query information. It is available only for POST requests.
3 HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
4 HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent originating
the request. It is name of the web browser.
5 PATH_INFO
The path for the CGI script.
6 QUERY_STRING
The URL-encoded information that is sent with GET method request.
7 REMOTE_ADDR
The IP address of the remote host making the request. This is useful logging or for
authentication.
8 REMOTE_HOST
The fully qualified name of the host making the request. If this information is not available,
then REMOTE_ADDR can be used to get IR address.
9 REQUEST_METHOD
The method used to make the request. The most common methods are GET and POST.
10 SCRIPT_FILENAME
The full path to the CGI script.
11 SCRIPT_NAME
The name of the CGI script.
12 SERVER_NAME
The server's hostname or IP Address
13 SERVER_SOFTWARE
The name and version of the software the server is running.
Here is small CGI program to list out all the CGI variables. Click this link to see the result Get
Environment
#!/usr/bin/python
import os
print("Content-type: text/html\r\n\r\n";)
print("<font size=+1>Environment</font><\br>");
forparaminos.environ.keys():
print("<b>%20s</b>: %s<\br>"%(param,os.environ[param]))
The GET method is the default method to pass information from browser to web server and it produces a
long string that appears in your browser's Location:box. Never use GET method if you have password or
other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters
can be sent in a request string. The GET method sends information using QUERY_STRING header and
will be accessible in your CGI Program through QUERY_STRING environment variable.
You can pass information by simply concatenating key and value pairs along with any URL or you can use
HTML <FORM> tags to pass information using GET method.
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
first_name=form.getvalue('first_name')
last_name=form.getvalue('last_name')
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>"
print"<title>Hello - Second CGI Program</title>"
print"</head>"
print"<body>"
print"<h2>Hello %s %s</h2>"%(first_name,last_name)
print"</body>"
print"</html>"
This would generate the following result −
<formaction="/cgi-bin/hello_get.py"method="get">
<inputtype="submit"value="Submit"/>
</form>
Here is the actual output of the above form, you enter First and Last Name and then click submit button to
see the result.
First Name:
S u b m it
Last Name:
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
last_name=form.getvalue('last_name')
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>"
print"</head>"
print"<body>"
print"<h2>Hello %s %s</h2>"%(first_name,last_name)
print"</body>"
print"</html>"
Let us take again same example as above which passes two values using HTML FORM and submit button.
We use same CGI script hello_get.py to handle this input.
<formaction="/cgi-bin/hello_get.py"method="post">
<inputtype="submit"value="Submit"/>
</form>
Here is the actual output of the above form. You enter First and Last Name and then click submit button to
see the result.
First Name:
S u b m it
Last Name:
<formaction="/cgi-bin/checkbox.cgi"method="POST"target="_blank">
<inputtype="checkbox"name="maths"value="on"/>Maths
<inputtype="checkbox"name="physics"value="on"/> Physics
<inputtype="submit"value="Select Subject"/>
</form>
The result of this code is the following form −
S e le c t S u b je c t
Maths Physics
Below is checkbox.cgi script to handle input given by web browser for checkbox button.
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
ifform.getvalue('maths'):
math_flag="ON"
else:
math_flag="OFF"
ifform.getvalue('physics'):
physics_flag="ON"
else:
physics_flag="OFF"
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>"
print"</head>"
print"<body>"
print"<h2>CheckBoxMaths is : %s</h2>"%math_flag
print"</body>"
print"</html>"
<formaction="/cgi-bin/radiobutton.py"method="post"target="_blank">
<inputtype="radio"name="subject"value="maths"/>Maths
<inputtype="radio"name="subject"value="physics"/> Physics
<inputtype="submit"value="Select Subject"/>
</form>
The result of this code is the following form −
S e le c t S u b je c t
Maths Physics
Below is radiobutton.py script to handle input given by web browser for radio button −
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
ifform.getvalue('subject'):
subject=form.getvalue('subject')
else:
subject="Not set"
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>"
print"</head>"
print"<body>"
print"</body>"
print"</html>"
<formaction="/cgi-bin/textarea.py"method="post"target="_blank">
<textareaname="textcontent"cols="40"rows="4">
</textarea>
<inputtype="submit"value="Submit"/>
</form>
The result of this code is the following form −
S u b m it
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
ifform.getvalue('textcontent'):
text_content=form.getvalue('textcontent')
else:
text_content="Not entered"
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>";
print"</head>"
print"<body>"
print"</body>"
<formaction="/cgi-bin/dropdown.py"method="post"target="_blank">
<selectname="dropdown">
<optionvalue="Maths"selected>Maths</option>
<optionvalue="Physics">Physics</option>
</select>
<inputtype="submit"value="Submit"/>
</form>
The result of this code is the following form −
M a th s S u b m it
#!/usr/bin/python
importcgi,cgitb
form=cgi.FieldStorage()
ifform.getvalue('dropdown'):
subject=form.getvalue('dropdown')
else:
subject="Not entered"
print"Content-type:text/html\r\n\r\n"
print"<html>"
print"<head>"
print"</head>"
print"<body>"
print"</body>"
print"</html>"
How It Works?
Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the
cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives
at another page on your site, the cookie is available for retrieval. Once retrieved, your server
knows/remembers what was stored.
Cookies are a plain text data record of 5 variable-length fields −
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the
browser.
Domain − The domain name of your site.
Path − The path to the directory or web page that sets the cookie. This may be blank if you want to retrieve the
cookie from any directory or page.
Secure − If this field contains the word "secure", then the cookie may only be retrieved with a secure server. If this
field is blank, no such restriction exists.
Name=Value − Cookies are set and retrieved in the form of key and value pairs.
Setting up Cookies
It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to
Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done
as follows −
#!/usr/bin/python
print"Set-Cookie:UserID = XYZ;\r\n"
print"Set-Cookie:Password = XYZ123;\r\n"
print "Set-Cookie:Path=/perl;\n"
print "Content-type:text/html\r\n\r\n"
Retrieving Cookies
It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable
HTTP_COOKIE and they will have following form −
key1 = value1;key2 = value2;key3 = value3....
#!/usr/bin/python
fromosimport environ
importcgi,cgitb
ifenviron.has_key('HTTP_COOKIE'):
if key =="UserID":
user_id= value
if key =="Password":
password= value
print"User ID = %s"%user_id
<html>
<body>
<formenctype="multipart/form-data"
action="save_file.py"method="post">
<p>File: <inputtype="file"name="filename"/></p>
<p><inputtype="submit"value="Upload"/></p>
</form>
</body>
</html>
The result of this code is the following form −
File:
U p lo a d
Above example has been disabled intentionally to save people uploading file on our server, but you can try
above code with your server.
Here is the script save_file.py to handle file upload −
#!/usr/bin/python
importcgi,os
importcgitb;cgitb.enable()
form=cgi.FieldStorage()
# Get filename here.
fileitem= form['filename']
iffileitem.filename:
fn=os.path.basename(fileitem.filename)
open('/tmp/'+fn,'wb').write(fileitem.file.read())
else:
print"""\
Content-Type: text/html\n
<html>
<body>
<p>%s</p>
</body>
</html>
"""%(message,)
If you run the above script on Unix/Linux, then you need to take care of replacing file separator as follows,
otherwise on your windows machine above open() statement should work fine.
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
#!/usr/bin/python
# HTTP Header
fo= open("foo.txt","rb")
str=fo.read();
printstr
fo.close()
The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this
standard.
You can choose the right database for your application. Python Database API supports a wide range of database
servers such as −
GadFly
mSQL
MySQL
PostgreSQL
Microsoft SQL Server 2000
Informix
Interbase
Oracle
Sybase
Here is the list of available Python database interfaces: Python Database Interfaces and APIs. You must download a
separate DB API module for each database you need to access. For example, if you need to access an Oracle database
as well as a MySQL database, you must download both the Oracle and the MySQL database modules.
The DB API provides a minimal standard for working with databases using Python structures and syntax wherever
possible. This API includes the following −
Importing the API module.
Acquiring a connection with the database.
Issuing SQL statements and stored procedures.
Closing the connection
We would learn all the concepts using MySQL, so let us talk about MySQLdb module.
What is MySQLdb?
MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python
Database API v2.0 and is built on top of the MySQL C API.
How do I Install MySQLdb?
Before proceeding, you make sure you have MySQLdb installed on your machine. Just type the following in your
Python script and execute it −
#!/usr/bin/python
import MySQLdb
If it produces the following result, then it means MySQLdb module is not installed −
Traceback (most recent call last):
File "test.py", line 3, in <module>
import MySQLdb
ImportError: No module named MySQLdb
To install MySQLdb module, use the following command −
For Ubuntu, use the following command -
$ sudo apt-get install python-pip python-dev libmysqlclient-dev
For Fedora, use the following command -
$ sudo dnf install python python-devel mysql-devel redhat-rpm-config gcc
For Python command prompt, use the following command -
pip install MySQL-python
Note − Make sure you have root privilege to install above module.
Database Connection
Before connecting to a MySQL database, make sure of the followings −
You have created a database TESTDB.
You have created a table EMPLOYEE in TESTDB.
This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
User ID "testuser" and password "test123" are set to access TESTDB.
Python module MySQLdb is installed properly on your machine.
You have gone through MySQL tutorial to understand MySQL Basics.
Example
Following is the example of connecting with MySQL database "TESTDB"
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
db.close()
While running this script, it is producing the following result in my Linux machine.
Database version : 5.0.45
If a connection is established with the datasource, then a Connection Object is returned and saved into db for further
use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute
SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are released.
Creating Database Table
Once a database connection is established, we are ready to create tables or records into the database tables
using execute method of the created cursor.
Example
Let us create Database table EMPLOYEE −
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
cursor.execute(sql)
db.close()
INSERT Operation
It is required when you want to create your records into a database table.
Example
The following example, executes SQL INSERT statement to create a record into EMPLOYEE table −
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
# Execute the SQL command
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Above example can be written as follows to create SQL queries dynamically −
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Example
Following code segment is another form of execution where you can pass parameters directly −
..................................
user_id = "test123"
password = "password"
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
db.close()
This will produce the following result −
fname=Mac, lname=Mohan, age=20, sex=M, income=2000
Update Operation
UPDATE Operation on any database means to update one or more records, which are already available in the
database.
The following procedure updates all the records having SEX as 'M'. Here, we increase AGE of all the males by one
year.
Example
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
DELETE Operation
DELETE operation is required when you want to delete some records from your database. Following is the procedure
to delete all the records from EMPLOYEE where AGE is more than 20 −
Example
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
cursor = db.cursor()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
Performing Transactions
Transactions are a mechanism that ensures data consistency. Transactions have the following four properties −
Atomicity − Either a transaction completes or nothing happens at all.
Consistency − A transaction must start in a consistent state and leave the system in a consistent state.
Isolation − Intermediate results of a transaction are not visible outside the current transaction.
Durability − Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
Example
You already know how to implement transactions. Here is again similar example −
try:
cursor.execute(sql)
db.commit()
except:
Your Python scripts should handle these errors, but before using any of the above exceptions, make sure your
MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0
specification.
Python MySQL Create Database
Creating a Database
Run example »
If the above code was executed with no errors, you have successfully created a database.
You can check if a database exist by listing all databases in your system by using the "SHOW DATABASES"
statement:
Example
Or you can try to access the database when making the connection:
Example
As shown in the above figure, a Web browser running on a client machine exchanges
information with a Web server using the Hyper Text Transfer Protocol or HTTP. The Web server
and the CGI program normally run on the same system, on which the web server resides,
Depending on the type of request from the browser, the web server either provides a document
from its own document directory or executes a CGI program.
The sequence of events for creating a dynamic HTML document on the fly through CGI
scripting is as follows:
1. A client makes an HTTP request by means of a URL. This URL could be typed into the
'Location' window of a browser, be a hyperlink or be specified in the 'Action' attribute of an
HTML <form> tag.
2. From the URL, the Web server determines that it should activate the gateway program listed
in the URL and send any parameters passed via the URL to that program.
3. The gateway program processes the information and returns HTML text to the Web server.
The server, in turn, adds a MIME header and returns the HTML text to the Web browser.
4. The Web browser displays the document received from the Web server.
1 CONTENT_TYPE
The data type of the content. Used when the client is sending attached content to
the server. For example, file upload.
2 CONTENT_LENGTH
The length of the query information. It is available only for POST requests.
3 HTTP_COOKIE
Returns the set cookies in the form of key & value pair.
4 HTTP_USER_AGENT
The User-Agent request-header field contains information about the user agent
originating the request. It is name of the web browser.
5 PATH_INFO
The path for the CGI script.
6 QUERY_STRING
The URL-encoded information that is sent with GET method request.
7 REMOTE_ADDR
The IP address of the remote host making the request. This is useful logging or
for authentication.
8 REMOTE_HOST
The fully qualified name of the host making the request. If this information is
not available, then REMOTE_ADDR can be used to get IR address.
9 REQUEST_METHOD
The method used to make the request. The most common methods are GET and
POST.
10 SCRIPT_FILENAME
The full path to the CGI script.
11 SCRIPT_NAME
The name of the CGI script.
12 SERVER_NAME
The server's hostname or IP Address
13 SERVER_SOFTWARE
The name and version of the software the server is running.
Python Programming.
SAQ’s
UNIT – I
UNIT – IV
1. Write a short on CGI in python programming (Introduction).
2. Write a sample program to demonstrate CGI.
3. Explain HTTP header in python CGI.
4. Write a short on Database access in python programming (Introduction).
5. Explain rollback and commit operations using python.
LAQ’s
Unit – I
1. What is Python Programming? Explain the features of Python Programming.
2. Give the Steps for Installing Python.
3. Briefly explain about Strings in Python programming.
4. Define Operators and explain any five Operators with syntax and examples.
5. Explain briefly about Lists. Write about basic functions & methods used in lists.
6. Explain briefly about Tuples. Write about basic functions & methods used in Tuples.
7. Explain briefly about Dictionaries. Write about basic functions & methods used in Dictionaries.
Unit – II
1. Explain Conditional statements in python (if, if-else, elif, nested if).
2. Explain Looping statements in python (while, for & while – else, for - else).
3. Define Functions. Explain about Built-in functions with a syntax and example.
4. What is Function? Explain User defined functions of Python Programming.
Unit – III
1. Briefly Define File and explain File handling mechanism in python.
2. Explain briefly about Modules in python.
3. Explain briefly about Module built-in functions and packages.
4. Briefly discuss about advance python programming (Classes & Objects, Inheritance, and
Regular Expressions).
5. Briefly explain about regular Expressions.
Unit – IV
1. Briefly explain about Python CGI Programming (Architecture, CGI Environment variables, GET
and Post methods).
2. Explain the process to create a Simple Form using GET and POST methods.
3. Explain briefly about Database Connectivity (Establishing Connection, insert, delete, retrieve,
commit, and rollback).