Python Ebook
Python Ebook
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been backported to be
compatible with the version 2.7. This tutorial gives enough understanding on Python 3
version programming language. Please refer to this link for our Python 2 tutorial.
Audience
This tutorial is designed for software programmers who want to upgrade their Python skills
to Python 3. This tutorial can also be used to learn Python programming language from
scratch.
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the
National Research Institute for Mathematics and Computer Science in the Netherlands.
• Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, and Unix shell and other scripting languages.
• Python is copyrighted. Like Perl, Python source code is now available under the
GNU General Public License (GPL).
• Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.
• Python 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
• Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward
compatible with Python 2. The emphasis in Python 3 had been on the removal of
duplicate programming constructs and modules so that "There should be one --
and preferably only one -- obvious way to do it." Python 3.5.1 is the latest
version of Python 3.
Python Features
Python's features include-
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a 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-maintained.
• 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.
• Apart from the above-mentioned features, Python has a big list of good features.
A few are listed below-
• 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.
2. Local Environment Setup
Open a terminal window and type "python" to find out if it is already installed and which
version is installed.
Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page
The following different installation options are available.
Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1.
For versions 3.0 to 3.4.x, Windows XP is acceptable.
Setting up PATH
Programs and other executable files can be in many directories. Hence, the operating
systems provide a search path that lists the directories that it searches for executables.
$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01) [GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)]
on
win32
Type "copyright", "credits" or "license()" for more information.
>>>
Type the following text at the Python prompt and press Enter-
Hello, Python!
Let us write a simple Python program in a script. Python files have the extension.py. Type
the following source code in a test.py file-
On Windows
C:\Python34>Python test.py
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.
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the identifier
is private.
• Starting an identifier with two leading underscores indicates a strong private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language- defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use
them as constants or variables or any other identifier names. All the Python keywords
contain lowercase letters only.
as finally or
continue if return
del in while
elif is with
except
Lines and Indentation
Python does not use braces({}) to indicate blocks of code for class and function definitions
or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example-
if True:
print ("True") else:
print ("False")
if True:
print ("Answer") print ("True")
else:
print "(Answer") print ("False")
Multi-Line Statements
Statements in Python typically end with a new line. Python, however, allows the use of the
line continuation character (\) to denote that the line should continue. For example-
total = item_one +
\ item_two +
\ item_three
The 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 is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and the
Python interpreter ignores them.
#!/usr/bin/python3
# First comment
print ("Hello, Python!") # second comment
# This is a comment.
# This is a comment, too. # This is a comment, too.
# I said that already.
In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.
#!/usr/bin/python3
input("\n\nPress the enter key to exit.")
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.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite. For example −
if expression : suite
elif expression : suite
else :
suite
You can also program your script in such a way that it should accept various options.
Command Line Arguments is an advance topic. Let us understand it.
The Python sys module provides access to any command-line arguments via the
sys.argv. This serves two purposes-
Example
Consider the following script test.py-
#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
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 the
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/python3
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string 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 the 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 the 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. 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 −
del var
del var_a, var_b
Python supports three different numerical types −
All integers in Python 3 are represented as long integers. Hence, there is no separate
number type as long.
Examples
Here are some examples of numbers-
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of strings can
be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of
the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example-
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging to
a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign
is the list concatenation operator, and the asterisk (*) is the repetition operator. For
example-
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element print (tinylist * 2) # Prints list
two times
print (list + tinylist) # Prints concatenated lists
This produces the following result-
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example-
#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.
Function Description
int(x [,base]) Converts x to an integer. The base specifies the base if x is astring.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
5. Python 3 – Basic Operators
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 the operator.
Types of Operators
Python language supports the following types of operators-
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
#!/usr/bin/python3 a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c )
c=a*b
print ("Line 3 - Value of c is ", c)
c=a/b
print ("Line 4 - Value of c is ", c )
c=a%b
print ("Line 5 - Value of c is ", c)
a=2
b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2.1
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
Python Comparison Operators
These operators compare the values on either side of them and decide the relation among
them. They are also called Relational operators.
Assume variable a holds the value 10 and variable b holds the value 20, then-
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
!= If values of two operands are not equal, then condition (a!= b) is true.
becomes true.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal (a >= b) is not true.
to the value of right operand, then condition
becomes true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3 a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program, it produces the following result-
#!/usr/bin/python3
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c = 2 c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Python Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows-
a = 0011 1100
b = 0000 1101
~a = 1100 0011
Pyhton's built-in function bin() can be used to obtain binary representation of an integer
number.
Example
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b)) c = 0
c = a & b; # 12 = 0000 1100
print ("result of AND is ", c,':',bin(c))
c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
a= 60 : 0b111100 b= 13 : 0b1101
result of AND is 12 : 0b1100
result of OR is 61 : 0b111101
result of EXOR is 49 : 0b110001
result of COMPLEMENT is -61 : -0b111101
result of LEFT SHIFT is 240 : 0b11110000
result of RIGHT SHIFT is 15 : 0b111
and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.
or Logical OR If any of the two operands are non-zero then (a or b) is
condition becomes true. True.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b)is
True.
Python Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below-
not in Evaluates to true, if it does not find a variable in the x not in y, here not in results in
specified sequence andfalse otherwise. a 1 if x is not a member of
sequence y.
Example
#!/usr/bin/python3
a = 10
b = 20
list = [1, 2, 3, 4, 5]
if (a in list):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
When you execute the above program, it produces the following result-
is not Evaluates to false if the variables on either side of the x is not y, here is not results
operator point to thesame object and true otherwise. in 1 if id(x) is not equal to
id(y).
Example
#!/usr/bin/python3
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity").
When you execute the above program, it produces the following result-
Operator Description
~+- Complement, unary plus and minus (method names forthe last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator * has
higher precedence than +, so it first multiplies 3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Example
#!/usr/bin/python3
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d) # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)
When you execute the above program, it produces the following result-
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
6. Python 3 – Decision Making
Decision-making is the anticipation of conditions occurring during the execution of a
program and specified actions taken according to the conditions.
Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the
outcome. You need to determine which action to take and which statements to execute if
the outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision-making structure found in most of the
programming languages-
Python programming language assumes any non-zero and non-null values as TRUE, and any
zero or null values as FALSE value.
Statement Description
if statements
An if statement consists of a Boolean expression followed byone or more
statements.
if...else statements
An if statement can be followed by an optional else statement, which
executes when the boolean expression isFALSE.
nested if statements
You can use one if or else if statement insideanother if or else if
statement(s).
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. In Python, statements in a block are uniformly indented after the :
symbol. If boolean expression evaluates to FALSE, then the first set of code after the end of
block is executed.
Flow Diagram
Example
The else statement is an optional statement and there could be at the most only one else
statement following if.
Syntax
The syntax of the if...else statement is-
if expression:
statement(s)
else:
statement(s)
Flow Diagram
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
Similar to the else, the elif statement is optional. However, unlike else, for which there can
be at the most one statement, there can be an arbitrary number of elif statements following
an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows-
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
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 if construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else
construct.
Syntax
The syntax of the nested if...elif...else construct may be-
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
# !/usr/bin/python3
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
When the above code is executed, it produces the following result-
enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
enter number5
not Divisible by 2 not divisible by 3
Programming languages provide various control structures that allow more complicated
execution paths.
Python programming language provides the following types of loops to handle looping
requirements.
Syntax
The syntax of a while loop in Python programming language is-
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent.
The condition may be any expression, and true is any non-zero value. The loop iterates
while the condition is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Flow Diagram
Here, a 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/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
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/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")
When the above code is executed, it produces the following result-
• 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 the else statement
gets executed.
#!/usr/bin/python3 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
#!/usr/bin/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
For Loop Statements
The for statement in Python 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
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a list
object of the sequence, it is typecasted to list(). Now this list can be iterated using the for
statement.
#!/usr/bin/python3
for letter in 'Python': # traversal of a string sequence
print ('Current Letter:', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit:', fruit)
print ("Good bye!")
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!
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset into the sequence itself.
Following is a simple example-
#!/usr/bin/python3
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-
• If the else statement is used with a for loop, the else block is executed only if for
loops terminates normally (and not by encountering break statement).
• 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 even number in given list.
#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number')
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 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 display multiplication tables from 1-10.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Loop Control Statements
The Loop control statements change the execution from its normal sequence. When the
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
break statement Terminates the loop statement and transfers execution to the
statement immediately following the loop.
continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition priorto reiterating.
pass statement The pass statement in Python is used when a statement is required
syntactically but you donot want any command or code to execute.
Let us go through the loop control statements briefly.
Break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the traditional
break statement in C.
The most common use of break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost
loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows-
Break
Flow Diagram
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
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!
The following program demonstrates the use of break in a for loop iterating over a list. User
inputs a number, which is searched in the list. If it is found, then the loop terminates with
the 'found' message.
#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')
The above program will produce the following output-
any number: 33
number found in list
any number: 5
number not found in list
Continue Statement
The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
Syntax
continue
Flow Diagram
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
var = 10 # Second Example
while var > 0:
var = var -1
if var == 5:
continue
print ('Current variable value :', var)
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 : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
Pass Statement
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. The pass
statement is also useful in places where your code will eventually go, but has not been
written yet i.e. in stubs).
Syntax
pass
Example
#!/usr/bin/python3
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
When the above code is executed, it produces the 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!
Iterator and Generator
Iterator is an object, which allows a programmer to traverse through all the elements of a
collection, regardless of its specific implementation. In Python, an iterator object
implements two methods, iter() and next().
list=[1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
A generator is a function that produces or yields a sequence of values using yield method.
When a generator function is called, it returns a generator object without even beginning
execution of the function. When the next() method is called for the first time, the function
starts executing, until it reaches the yield statement, which returns the yielded value. The
yield keeps track i.e. remembers the last execution and the second next() call continues
from previous value.
The following example defines a generator, which generates an iterator for all the Fibonacci
numbers.
!usr/bin/python3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while
True:
try:
print (next(f), end="")
except StopIteration:
sys.exit()
8. Python 3 – Numbers
Number data types store numeric values. They are immutable data types. This means,
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 −
del var
del var_a, var_b
Python supports different numerical types-
• int (signed integers): They are often called just integers or ints. They are positive or
negative whole numbers with no decimal point. Integers in Python 3 are of unlimited
size. Python 2 has two integer types - int and long. There is no 'long integer' in
Python 3 anymore.
• float (floating point real values) : Also called floats, they represent real numbers and
are written with a decimal point dividing the integer and the 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.
Mathematical Functions
Python includes the following functions that perform mathematical calculations.
Syntax
Following is the syntax for abs() method-
abs( x )
Parameters
x - This is a numeric expression.
Return Value
This method returns the absolute value of x.
Example
The following example shows the usage of the abs() method.
#!/usr/bin/python3
print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))
When we run the above program, it produces the following result-
abs(-45) : 45
abs(100.12) : 100.12
Syntax
Following is the syntax for the ceil() method-
import math
math.ceil( x )
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the smallest integer not less than x.
Example
The following example shows the usage of the ceil() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.ceil(-45.17) : ", math.ceil(-45.17))
print ("math.ceil(100.12) : ", math.ceil(100.12))
print ("math.ceil(100.72) : ", math.ceil(100.72))
print ("math.ceil(math.pi) : ", math.ceil(math.pi))
When we run the above program, it produces the following result-
math.ceil(-45.17) : -45
math.ceil(100.12) : 101
math.ceil(100.72) : 101
math.ceil(math.pi) : 4
Syntax
Following is the syntax for the exp() method-
import math
math.exp( x )
Note: This function is not accessible directly. Therefore, we need to import the math module
and then we need to call this function using the math static object.
Parameters
X - This is a numeric expression.
Return Value
This method returns exponential of x: ex.
Example
The following example shows the usage of exp() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.exp(-45.17) : ", math.exp(-45.17))
print ("math.exp(100.12) : ", math.exp(100.12))
print ("math.exp(100.72) : ", math.exp(100.72))
print ("math.exp(math.pi) : ", math.exp(math.pi))
When we run the above program, it produces the following result-
math.exp(-45.17) : 2.4150062132629406e-20
math.exp(100.12) : 3.0308436140742566e+43
math.exp(100.72) : 5.522557130248187e+43
math.exp(math.pi) : 23.140692632779267
Number fabs() Method
Description
The fabs() method returns the absolute value of x. Although similar to the abs() function,
there are differences between the two functions. They are-
Syntax
Following is the syntax for the fabs() method-
import math
math.fabs( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric value.
Return Value
This method returns the absolute value of x.
Example
The following example shows the usage of the fabs() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.fabs(-45.17) : ", math.fabs(-45.17))
print ("math.fabs(100.12) : ", math.fabs(100.12))
print ("math.fabs(100.72) : ", math.fabs(100.72))
print ("math.fabs(math.pi) : ", math.fabs(math.pi))
When we run the above program, it produces following result-
math.fabs(-45.17) : 45.17
math.fabs(100) : 100.0
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793
Number floor() Method
Description
The floor() method returns the floor of x i.e. the largest integer not greater than x.
Syntax
Following is the syntax for the floor() method-
import math
math.floor( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the largest integer not greater than x.
Example
The following example shows the usage of the floor() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
print ("math.floor(100.72) : ", math.floor(100.72))
print ("math.floor(math.pi) : ", math.floor(math.pi))
When we run the above program, it produces the following result-
math.floor(-45.17) : -46
math.floor(100.12) : 100
math.floor(100.72) : 100
math.floor(math.pi) : 3
Syntax
Following is the syntax for the log() method-
import math
math.log( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns natural logarithm of x, for x > 0.
Example
The following example shows the usage of the log() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.log(100.12) : ", math.log(100.12))
print ("math.log(100.72) : ", math.log(100.72))
print ("math.log(math.pi) : ", math.log(math.pi))
When we run the above program, it produces the following result-
math.log(100.12) : 4.6063694665635735
math.log(100.72) : 4.612344389736092
math.log(math.pi) : 1.1447298858494002
Syntax
Following is the syntax for log10() method-
import math
math.log10( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns the base-10 logarithm of x for x > 0.
Example
The following example shows the usage of the log10() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.log10(100.12) : ", math.log10(100.12))
print ("math.log10(100.72) : ", math.log10(100.72))
print ("math.log10(119) : ", math.log10(119))
print ("math.log10(math.pi) : ", math.log10(math.pi))
When we run the above program, it produces the following result-
math.log10(100.12) : 2.0005208409361854
math.log10(100.72) : 2.003115717099806
math.log10(119) : 2.0755469613925306
math.log10(math.pi) : 0.49714987269413385
Number max() Method
Description
The max() method returns the largest of its arguments i.e. the value closest to positive
infinity.
Syntax
Following is the syntax for max() method-
max( x, y, z, )
Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
This method returns the largest of its arguments.
Example
The following example shows the usage of the max() method.
#!/usr/bin/python3
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
print ("max(0, 100, -400) : ", max(0, 100, -400))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for the min() method-
min( x, y, z,)
Parameters
• x - This is a numeric expression.
• y - This is also a numeric expression.
• z - This is also a numeric expression.
Return Value
This method returns the smallest of its arguments.
Example
The following example shows the usage of the min() method.
#!/usr/bin/python3
print ("min(80, 100, 1000) : ", min(80, 100, 1000))
print ("min(-20, 100, 400) : ", min(-20, 100, 400))
print ("min(-80, -20, -10) : ", min(-80, -20, -10))
print ("min(0, 100, -400) : ", min(0, 100, -400))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for the modf() method-
Parameters
x - This is a numeric expression.
Return Value
This method returns the fractional and integer parts of x in a two-item tuple. Both the parts
have the same sign as x. The integer part is returned as a float.
Example
The following example shows the usage of the modf() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.modf(100.12) : ", math.modf(100.12))
print ("math.modf(100.72) : ", math.modf(100.72))
print ("math.modf(119) : ", math.modf(119))
print ("math.modf(math.pi) : ", math.modf(math.pi))
When we run the above program, it produces the following result-
math.modf(100.12) : (0.12000000000000455, 100.0)
math.modf(100.72) : (0.7199999999999989, 100.0)
math.modf(119) : (0.0, 119.0)
math.modf(math.pi) : (0.14159265358979312, 3.0)
Example
The following example shows the usage of the pow() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.pow(100, 2) : ", math.pow(100, 2))
print ("math.pow(100, -2) : ", math.pow(100, -2))
print ("math.pow(2, 4) : ", math.pow(2, 4))
print ("math.pow(3, 0) : ", math.pow(3, 0))
When we run the above program, it produces the following result-
math.pow(100, 2) : 10000.0
math.pow(100, -2) : 0.0001
math.pow(2, 4) : 16.0
math.pow(3, 0) : 1.0
Syntax
Following is the syntax for the round() method-
round( x [, n] )
Parameters
• x - This is a numeric expression.
• n - Represents number of digits from decimal point up to which x is to be rounded.
Default is 0.
Return Value
This method returns x rounded to n digits from the decimal point.
Example
The following example shows the usage of round() method.
#!/usr/bin/python3
print ("round(70.23456) : ", round(70.23456))
print ("round(56.659,1) : ", round(56.659,1))
print ("round(80.264, 2) : ", round(80.264, 2))
print ("round(100.000056, 3) : ", round(100.000056, 3))
print ("round(-100.000056, 3) : ", round(-100.000056, 3))
When we run the above program, it produces the following result-
round(70.23456) : 70
round(56.659,1) : 56.7
round(80.264, 2) : 80.26
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0
Syntax
Following is the syntax for sqrt() method-
import math
math.sqrt( x )
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This is a numeric expression.
Return Value
This method returns square root of x for x > 0.
Example
The following example shows the usage of sqrt() method.
#!/usr/bin/python3
import math # This will import math module
print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))
print ("math.sqrt(math.pi) : ", math.sqrt(math.pi))
When we run the above program, it produces the following result-
math.sqrt(100) : 10.0
math.sqrt(7) : 2.6457513110645907
math.sqrt(math.pi) : 1.7724538509055159
Random Number Functions
Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes the following functions that are commonly used.
Function Description
choice(seq) A random item from a list, tuple, or string.
Syntax
Following is the syntax for choice() method-
choice( seq )
Note: This function is not accessible directly, so we need to import the random module and
then we need to call this function using the random static object.
Parameters
seq - This could be a list, tuple, or string...
Return Value
This method returns a random item.
Example
The following example shows the usage of the choice() method.
Syntax
Following is the syntax for the randrange() method-
Parameters
• start - Start point of the range. This would be included in the range. Default is 0.
• stop - Stop point of the range. This would be excluded from the range.
• step - Value with which number is incremented. Default is 1.
Return Value
This method returns a random item from the given range.
Example
The following example shows the usage of the randrange() method.
randrange(1,100, 2) : 83
randrange (100): 93
Syntax
Following is the syntax for the random() method-
random ( )
Note: This function is not accessible directly, so we need to import the random module and
then we need to call this function using the random static object.
Parameters
NA
Return Value
This method returns a random float r, such that 0.0 <= r <= 1.0
Example
The following example shows the usage of the random() method.
random() : 0.281954791393
random() : 0.309090465205
Syntax
Following is the syntax for the seed() method-
Parameters
• x - This is the seed for the next random number. If omitted, then it takes system
time to generate the next random number. If x is an int, it is used directly.
• Y - This is version number (default is 2). str, byte or byte array object gets
converted in int. Version 1 used hash() of x.
Return Value
This method does not return any value.
Example
The following example shows the usage of the seed() method.
Syntax
Following is the syntax for the shuffle() method-
shuffle (lst,[random])
Note: This function is not accessible directly, so we need to import the shuffle module and
then we need to call this function using the random static object.
Parameters
• lst - This could be a list or tuple.
• random - This is an optional 0 argument function returning float between 0.0 - 1.0.
Default is None.
Return Value
This method returns reshuffled list.
Example
The following example shows the usage of the shuffle() method.
Syntax
Following is the syntax for the uniform() method-
uniform(x, y)
Note: This function is not accessible directly, so we need to import the uniform module and
then we need to call this function using the random static object.
Parameters
• x - Sets the lower limit of the random float.
• y - Sets the upper limit of the random float.
Return Value
This method returns a floating point number r such that x <=r < y.
Example
The following example shows the usage of the uniform() method.
Trigonometric Functions
Python includes the following functions that perform trigonometric calculations.
Function Description
acos(x) Return the arc cosine of x, in radians.
acos(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will
generate 'math domain error'.
Return Value
This method returns arc cosine of x, in radians.
Example
The following example shows the usage of the acos() method.
#!/usr/bin/python3
import math
print ("acos(0.64) : ", math.acos(0.64))
print ("acos(0) : ", math.acos(0))
print ("acos(-1) : ", math.acos(-1))
print ("acos(1) : ", math.acos(1))
When we run the above program, it produces the following result-
acos(0.64) : 0.876298061168
acos(0) : 1.57079632679
acos(-1) : 3.14159265359
acos(1) : 0.0
Number asin() Method
Description
The asin() method returns the arc sine of x (in radians).
Syntax
Following is the syntax for the asin() method-
asin(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function usingthe math static object.
Parameters
x - This must be a numeric value in the range -1 to 1. If x is greater than 1 then it will
generate 'math domain error'.
Return Value
This method returns arc sine of x, in radians.
Example
The following example shows the usage of the asin() method.
#!/usr/bin/python3
import math
print ("asin(0.64) : ", math.asin(0.64))
print ("asin(0) : ", math.asin(0))
print ("asin(-1) : ", math.asin(-1))
print ("asin(1) : ", math.asin(1))
When we run the above program, it produces the following result-
asin(0.64) : 0.694498265627
asin(0) : 0.0
asin(-1) : -1.57079632679
asin(1) : 1.5707963267
Number atan() Method
Description
The atan() method returns the arc tangent of x, in radians.
Syntax
Following is the syntax for atan() method-
atan(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns arc tangent of x, in radians.
Example
The following example shows the usage of the atan() method.
#!/usr/bin/python3
import math
print ("atan(0.64) : ", math.atan(0.64))
print ("atan(0) : ", math.atan(0))
print ("atan(10) : ", math.atan(10))
print ("atan(-1) : ", math.atan(-1))
print ("atan(1) : ", math.atan(1))
When we run the above program, it produces the following result-
atan(0.64) : 0.569313191101
atan(0) : 0.0
atan(10) : 1.4711276743
atan(-1) : -0.785398163397
atan(1) : 0.785398163397
Number atan2() Method
Description
The atan2() method returns atan(y / x), in radians.
Syntax
Following is the syntax for atan2() method-
atan2(y, x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
y - This must be a numeric value.
Return Value
This method returns atan(y / x), in radians.
Example
The following example shows the usage of atan2() method.
#!/usr/bin/python3
import math
print ("atan2(-0.50,-0.50) : ", math.atan2(-0.50,-0.50))
print ("atan2(0.50,0.50) : ", math.atan2(0.50,0.50))
print ("atan2(5,5) : ", math.atan2(5,5))
print ("atan2(-10,10) : ", math.atan2(-10,10))
print ("atan2(10,20) : ", math.atan2(10,20))
When we run the above program, it produces the following result-
atan2(-0.50,-0.50) : -2.35619449019
atan2(0.50,0.50) : 0.785398163397
atan2(5,5) : 0.785398163397
atan2(-10,10) : -0.785398163397
atan2(10,20) : 0.463647609001
Syntax
Following is the syntax for cos() method-
cos(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the cosine of the
angle.
Example
The following example shows the usage of cos() method.
#!/usr/bin/python3
import math
print ("cos(3) : ", math.cos(3))
print ("cos(-3) : ", math.cos(-3))
print ("cos(0) : ", math.cos(0))
print ("cos(math.pi) : ", math.cos(math.pi))
print ("cos(2*math.pi) : ", math.cos(2*math.pi))
When we run the above program, it produces the following result-
cos(3) : -0.9899924966
cos(-3) : -0.9899924966
cos(0) : 1.0
cos(math.pi) : -1.0
cos(2*math.pi) : 1.0
Syntax
Following is the syntax for hypot() method-
hypot(x, y)
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using math static object.
Parameters
x - This must be a numeric value.
y - This must be a numeric value.
Return Value
This method returns Euclidean norm, sqrt(x*x + y*y).
Example
The following example shows the usage of hypot() method.
#!/usr/bin/python3
import math
print ("hypot(3, 2) : ", math.hypot(3, 2))
print ("hypot(-3, 3) : ", math.hypot(-3, 3))
print ("hypot(0, 2) : ", math.hypot(0, 2))
When we run the above program, it produces the following result-
hypot(3, 2) : 3.60555127546
hypot(-3, 3) : 4.24264068712
hypot(0, 2) : 2.0
Syntax
Following is the syntax for sin() method-
sin(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the sine of the
parameter x.
Example
The following example shows the usage of sin() method.
sin(3) : 0.14112000806
sin(-3) : -0.14112000806
sin(0) : 0.0
sin(math.pi) : 1.22460635382e-16
sin(math.pi/2) : 1
tan(x)
Note: This function is not accessible directly, so we need to import math module and then
we need to call this function using math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns a numeric value between -1 and 1, which represents the tangent of the
parameter x.
Example
The following example shows the usage of tan() method.
#!/usr/bin/python3
import math
print ("(tan(3) : ", math.tan(3))
print ("tan(-3) : ", math.tan(-3))
print ("tan(0) : ", math.tan(0))
print ("tan(math.pi) : ", math.tan(math.pi))
print ("tan(math.pi/2) : ", math.tan(math.pi/2))
print ("tan(math.pi/4) : ", math.tan(math.pi/4))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for degrees() method-
degrees(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns the degree value of an angle.
Example
The following example shows the usage of degrees() method.
#!/usr/bin/python3
import math
print ("degrees(3) : ", math.degrees(3))
print ("degrees(-3) : ", math.degrees(-3))
print ("degrees(0) : ", math.degrees(0))
print ("degrees(math.pi) : ", math.degrees(math.pi))
print ("degrees(math.pi/2) : ", math.degrees(math.pi/2))
print ("degrees(math.pi/4) : ", math.degrees(math.pi/4))
When we run the above program, it produces the following result-
degrees(3) : 171.88733853924697
degrees(-3) : -171.88733853924697
degrees(0) : 0.0
degrees(math.pi) : 180.0
degrees(math.pi/2) : 90.0
degrees(math.pi/4) : 45.0
Syntax
Following is the syntax for radians() method-
radians(x)
Note: This function is not accessible directly, so we need to import the math module and
then we need to call this function using the math static object.
Parameters
x - This must be a numeric value.
Return Value
This method returns radian value of an angle.
Example
The following example shows the usage of radians() method.
#!/usr/bin/python3
import math
print ("radians(3) : ", math.radians(3))
print ("radians(-3) : ", math.radians(-3))
print ("radians(0) : ", math.radians(0))
print ("radians(math.pi) : ", math.radians(math.pi))
print ("radians(math.pi/2) : ", math.radians(math.pi/2))
print ("radians(math.pi/4) : ", math.radians(math.pi/4))
When we run the above program, it produces the following result-
radians(3) : 0.0523598775598
radians(-3) : -0.0523598775598
radians(0) : 0.0
radians(math.pi) : 0.0548311355616
radians(math.pi/2) : 0.0274155677808
radians(math.pi/4) : 0.0137077838904
9. Python 3 – 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/python3
var1 = 'Hello World!'
var2 = "Python Programming"
print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])
When the above code is executed, it produces the following result-
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/python3
var1 = 'Hello World!'
print ("Updated String :- ", var1[:6] + 'Python')
When the above code is executed, it produces the following result-
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
\s 0x20 Space
\t 0x09 Tab
String Special Operators
Assume string variable a holds 'Hello' and variable b holds 'Python', then-
[:] Range Slice - Gives the characters from the given a[1:4] will give ell
range
in Membership - Returns true if a character exists in H in a will give 1
the given string
not in Membership - Returns true if a character does not M not in a will give
exist in the given string 1
r/R Raw String - Suppresses actual meaning of Escape print r'\n' prints \n
characters. The syntax for raw strings is exactly the and print
same as for normal strings with the exception of the R'\n'prints \n
raw string operator, the letter "r," which precedes
the quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately
preceding the first quote mark.
String Formatting Operator
One of Python's coolest features is the string format operator %. This operator is unique to
strings and makes up for the pack of having functions from C's printf() family. Following is a
simple example −
#!/usr/bin/python3
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
When the above code is executed, it produces the following result −
%o octal integer
Symbol Functionality
* argument specifies width or precision
- left justification
The syntax for triple quotes consists of three consecutive single or double quotes.
#!/usr/bin/python3
para_str = """this is a long string that is made up of several lines and non-printable
characters such as
TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string,
whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the
variable assignment will also show up.
"""
print (para_str)
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) −
#!/usr/bin/python3
print ('C:\\nowhere')
When the above code is executed, it produces the following result-
C:\nowhere
Now let us make use of raw string. We would put expression in r'expression' as follows-
print (r'C:\\nowhere')
When the above code is executed, it produces the following result-
C:\\nowhere
Unicode String
In Python 3, all strings are represented in Unicode. In Python 2 are stored internally as 8-
bit ASCII, hence it is required to attach 'u' to make it Unicode. It is no longer necessary
now.
Built-in String Methods
Python includes the following built-in methods to manipulate strings-
1 capitalize()
Capitalizes first letter of string
center(width, fillchar)
2
Returns a string padded with fillchar with the original string centered to a totalof width columns.
count(str, beg= 0,end=len(string))
3 Counts how many times str occurs in string or in a substring of string if startingindex beg and
ending index end are given.
decode(encoding='UTF-8',errors='strict')
4
Decodes the string using the codec registered for encoding. encoding defaultsto the default
string encoding.
encode(encoding='UTF-8',errors='strict')
5
Returns encoded string version of string; on error, default is to raise aValueError
unless errors is given with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))
6 Determines if string or a substring of string (if starting index beg and endingindex end are
given) ends with suffix; returns true if so and false otherwise.
expandtabs(tabsize=8)
7
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsizenot provided.
find(str, beg=0 end=len(string))
8
Determine if str occurs in string or in a substring of string if starting index begand ending index
end are given returns index if found and -1 otherwise.
index(str, beg=0, end=len(string))
9
Same as find(), but raises an exception if str not found.
isalnum()
10
Returns true if string has at least 1 character and all characters arealphanumeric and false
otherwise.
isalpha()
11
Returns true if string has at least 1 character and all characters are alphabeticand false
otherwise.
isdigit()
12
Returns true if the string contains only digits and false otherwise.
islower()
13
Returns true if string has at least 1 cased character and all cased charactersare in lowercase
and false otherwise.
isnumeric()
14
Returns true if a unicode string contains only numeric characters and falseotherwise.
isspace()
15
Returns true if string contains only whitespace characters and false otherwise.
istitle()
16
Returns true if string is properly "titlecased" and false otherwise.
isupper()
17
Returns true if string has at least one cased character and all cased charactersare in uppercase
and false otherwise.
join(seq)
18
Merges (concatenates) the string representations of elements in sequence seqinto a string, with
separator string.
len(string)
19
Returns the length of the string
ljust(width[, fillchar])
20
Returns a space-padded string with the original string left-justified to a totalof width
columns.
lower()
21
Converts all uppercase letters in string to lowercase.
lstrip()
22
Removes all leading whitespace in string.
maketrans()
23
Returns a translation table to be used in translate function.
max(str)
24
Returns the max alphabetical character from the string str.
min(str)
25
Returns the min alphabetical character from the string str.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
rstrip()
30
Removes all trailing whitespace of string.
split(str="", num=string.count(str))
31
Splits string according to delimiter str (space if not provided) and returns listof substrings;
split into at most num substrings if given.
splitlines( num=string.count('\n'))
32
Splits string at all (or num) NEWLINEs and returns a list of each line withNEWLINEs
removed.
startswith(str, beg=0,end=len(string))
33
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
strip([chars])
34
Performs both lstrip() and rstrip() on string
swapcase()
35
Inverts case for all letters in string.
title()
36
Returns "titlecased" version of string, that is, all words begin with uppercaseand the rest are
lowercase.
translate(table, deletechars="")
37
Translates string according to translation table str(256 chars), removing thosein the del string.
upper()
38
Converts lowercase letters in string to uppercase.
zfill (width)
39
Returns original string leftpadded with zeros to a total of width characters;intended for
numbers, zfill() retains any sign given (less one zero).
isdecimal()
40
Returns true if a unicode string contains only decimal characters and falseotherwise.
Syntax
str.capitalize()
Parameters
NA
Return Value
string
Example
#!/usr/bin/python3
str = "this is string example. wow!!!"
print ("str.capitalize() : ", str.capitalize())
Result
str.capitalize() : This is string example. wow!!!
Syntax
str.center(width[, fillchar])
Parameters
• width - This is the total width of the string.
• fillchar - This is the filler character.
Return Value
This method returns a string that is at least width characters wide, created by padding the
string with the character fillchar (default is a space).
Example
The following example shows the usage of the center() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print ("str.center(40, 'a') : ", str.center(40, 'a'))
Result
str.center(40, 'a') : aaaathis is string example. wow!!!aaaa
String count() Method
Description
The count() method returns the number of occurrences of substring sub in the range [start,
end]. Optional arguments start and end are interpreted as in slice notation.
Syntax
str.count(sub, start= 0,end=len(string))
Parameters
• sub - This is the substring to be searched.
• start - Search starts from this index. First character starts from 0 index. By default
search starts from 0 index.
• end - Search ends from this index. First character starts from 0 index. By default
search ends at the last index.
Return Value
Centered in a string of length width.
Example
#!/usr/bin/python3
str="this is string example. wow!!!"
sub='i'
print ("str.count('i') : ", str.count(sub)) sub='exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
Result
str.count('i') : 3
str.count('exam', 4, 40) :
String decode() Method
Description
The decode() method decodes the string using the codec registered for encoding. It defaults
to the default string encoding.
Syntax
Str.decode(encoding='UTF-8',errors='strict')
Parameters
• encoding - This is the encodings to be used. For a list of all encoding schemes please
visit: Standard Encodings.
• errors - This may be given to set a different error handling scheme. The default for
errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible
values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other
name registered via codecs.register_error()..
Return Value
Decoded string.
Example
#!/usr/bin/python3
Str = "this is string example. wow!!!";
Str = Str.encode('base64','strict'); print "Encoded String: " + Str
print "Decoded String: " + Str.decode('base64','strict')
Result
Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE=' Decoded String:
this is string example. wow!!!
Syntax
str.encode(encoding='UTF-8',errors='strict')
Parameters
• encoding - This is the encodings to be used. For a list of all encoding schemes please
visit: Standard Encodings.
• errors - This may be given to set a different error handling scheme. The default for
errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible
values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other
name registered via codecs.register_error().
Return Value
Decoded string.
Example
#!/usr/bin/python3
import base64
Str = "this is string example. wow!!!"
Str=base64.b64encode(Str.encode('utf-8',errors='strict')) print ("Encoded String: " , Str)
Result
Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chISE='
String endswith() Method
Description
It returns True if the string ends with the specified suffix, otherwise return False optionally
restricting the matching with the given indices start and end.
Syntax
str.endswith(suffix[, start[, end]])
Parameters
• suffix - This could be a string or could also be a tuple of suffixes to look for.
• start - The slice begins from here.
• end - The slice ends here.
Return Value
TRUE if the string ends with the specified suffix, otherwise FALSE.
Example
#!/usr/bin/python3
Str='this is string example wow!!!'
suffix='!!'
print (Str.endswith(suffix)) print (Str.endswith(suffix,20)) suffix='exam'
print (Str.endswith(suffix))
print (Str.endswith(suffix, 0, 19))
Result
True True False True
String expandtabs() Method
Description
The expandtabs() method returns a copy of the string in which the tab characters ie. '\t' are
expanded using spaces, optionally using the given tabsize (default 8)..
Syntax
str.expandtabs(tabsize=8)
Parameters
tabsize - This specifies the number of characters to be replaced for a tab character '\t'.
Return Value
This method returns a copy of the string in which tab characters i.e., '\t' have been
expanded using spaces.
Example
#!/usr/bin/python3
str = "this is\tstring example wow!!!"
print ("Original string: " + str)
print ("Defualt exapanded tab: " + str.expandtabs())
print ("Double exapanded tab: " + str.expandtabs(16))
Result
Original string: this is string example. wow!!!
Defualt exapanded tab: this is string examplewow!!!
Double exapanded tab: this is string example wow!!!
Return Value
Index if found and -1 otherwise.
Example
#!/usr/bin/python3
str1 = "this is string example wow!!!"
str2 = "exam";
print (str1.find(str2)) print (str1.find(str2, 10))
print (str1.find(str2, 40))
Result
15
15
-1
String index() Method
Description
The index() method determines if the string str occurs in string or in a substring of string, if
the starting index beg and ending index end are given. This method is same as find(), but
raises an exception if sub is not found.
Syntax
str.index(str, beg=0 end=len(string))
Parameters
• str - This specifies the string to be searched.
• beg - This is the starting index, by default its 0.
• end - This is the ending index, by default its equal to the length of the string.
Return Value
Index if found otherwise raises an exception if str is not found.
Example
#!/usr/bin/python3
str1 = "this is string example wow!!!"
str2 = "exam";
print (str1.index(str2)) print (str1.index(str2, 10))
print (str1.index(str2, 40))
Result
15
15
Traceback (most recent call last):
File "test.py", line 7, in print (str1.index(str2, 40))
ValueError: substring not found
shell returned 1
String isalnum() Method
Description
The isalnum() method checks whether the string consists of alphanumeric characters.
Syntax
Following is the syntax for isalnum() method-
str.isa1num()
Parameters
NA
Return Value
This method returns true if all the characters in the string are alphanumeric and there is at
least one character, false otherwise.
Example
The following example shows the usage of isalnum() method.
#!/usr/bin/python3
str = "this2016" # No space in this string print (str.isalnum())
str = "this is string example. wow!!!"
print (str.isalnum())
When we run the above program, it produces the following result-
True False
String isalpha() Method
Description
The isalpha() method checks whether the string consists of alphabetic characters only.
Syntax
Following is the syntax for islpha() method-
str.isalpha()
Parameters
NA
Return Value
This method returns true if all the characters in the string are alphabetic and there is at
least one character, false otherwise.
Example
The following example shows the usage of isalpha() method.
#!/usr/bin/python3
str = "this"; # No space & digit in this string
print (str.isalpha())
str = "this is string example. wow!!!"
print (str.isalpha())
Result
True False
String isdigit() Method
Description
The method isdigit() checks whether the string consists of digits only.
Syntax
Following is the syntax for isdigit() method-
str.isdigit()
Parameters
NA
Return Value
This method returns true if all characters in the string are digits and there is at least one
character, false otherwise.
Example
The following example shows the usage of isdigit() method.
#!/usr/bin/python3
str = "123456"; # Only digit in this string
print (str.isdigit())
str = "this is string example. wow!!!"
print (str.isdigit())
Result
True False
String islower() Method
Description
The islower() method checks whether all the case-based characters (letters) of the string
are lowercase.
Syntax
Following is the syntax for islower() method-
str.islower()
Parameters
NA
Return Value
This method returns true if all cased characters in the string are lowercase and there is at
least one cased character, false otherwise.
Example
The following example shows the usage of islower() method.
#!/usr/bin/python3
str = "THIS is string example wow!!!"
print (str.islower())
str = "this is string example. wow!!!"
print (str.islower())
Result
False True
String isnumeric() Method
Description
The isnumeric() method checks whether the string consists of only numeric characters. This
method is present only on unicode objects.
Note: Unlike Python 2, all strings are represented in Unicode in Python 3. Given below is an
example illustrating it.
Syntax
Following is the syntax for isnumeric() method-
str.isnumeric()
Parameters
NA
Return Value
This method returns true if all characters in the string are numeric, false otherwise.
Example
The following example shows the usage of isnumeric() method.
#!/usr/bin/python3
str = "this2016"
print (str.isnumeric())
str = "23443434"
print (str.isnumeric())
Result
False True
String isspace() Method
Description
The isspace() method checks whether the string consists of whitespace..
Syntax
Following is the syntax for isspace() method-
str.isspace()
Parameters
NA
Return Value
This method returns true if there are only whitespace characters in the string and there is at
least one character, false otherwise.
Example
The following example shows the usage of isspace() method.
#!/usr/bin/python3
str = " " print (str.isspace())
str = "This is string example. wow!!!"
print (str.isspace())
Result
True False
String istitle() Method
Description
The istitle() method checks whether all the case-based characters in the string following
non-casebased letters are uppercase and all other case-based characters are lowercase.
Syntax
Following is the syntax for istitle() method-
str.istitle()
Parameters
NA
Return Value
This method returns true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters and
lowercase characters only cased ones. It returns false otherwise.
Example
The following example shows the usage of istitle() method.
#!/usr/bin/python3
str = "This Is String Example...Wow!!!" print (str.istitle())
str = "This is string example. wow!!!"
print (str.istitle())
Result
True False
String isupper() Method
Description
The isupper() method checks whether all the case-based characters (letters) of the string
are uppercase.
Syntax
Following is the syntax for isupper() method-
str.isupper()
Parameters
NA
Return Value
This method returns true if all the cased characters in the string are uppercase and there is
at least one cased character, false otherwise.
Example
The following example shows the usage of isupper() method.
#!/usr/bin/python3
str = "THIS IS STRING EXAMPLE. WOW!!!"
print (str.isupper())
str = "THIS is string example. wow!!!"
print (str.isupper())
Result
True False
String join() Method
Description
The join() method returns a string in which the string elements of sequence have been
joined by str separator.
Syntax
Following is the syntax for join() method-
str.join(sequence)
Parameters
sequence - This is a sequence of the elements to be joined.
Return Value
This method returns a string, which is the concatenation of the strings in the sequence
seq. The separator between elements is the string providing this method.
Example
The following example shows the usage of join() method.
#!/usr/bin/python3
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print (s.join( seq ))
Result
a-b-c
String len() Method
Description
The len() method returns the length of the string.
Syntax
Following is the syntax for len() method −
len( str )
Parameters
NA
Return Value
This method returns the length of the string.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print ("Length of the string: ", len(str))
Result
Length of the string: 32
String ljust() Method
Description
The method ljust() returns the string left justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned if width
is less than len(s).
Syntax
Following is the syntax for ljust() method −
str.ljust(width[, fillchar])
Parameters
• width - This is string length in total after padding.
• fillchar - This is filler character, default is a space.
Return Value
This method returns the string left justified in a string of length width. Padding is done using
the specified fillchar (default is a space). The original string is returned if width is less than
len(s).
Example
The following example shows the usage of ljust() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print str.ljust(50, '*')
Result
this is string examplewow!!!******************
String lower() Method
Description
The method lower() returns a copy of the string in which all case-based characters have
been lowercased.
Syntax
Following is the syntax for lower() method −
str.lower()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
lowercased.
Example
The following example shows the usage of lower() method.
#!/usr/bin/python3
str = "THIS IS STRING EXAMPLE. WOW!!!"
print (str.lower())
Result
this is string examplewow!!!
String lstrip() Method
Description
The lstrip() method returns a copy of the string in which all chars have been stripped from
the beginning of the string (default whitespace characters).
Syntax
Following is the syntax for lstrip() method-
str.lstrip([chars])
Parameters
chars - You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from the
beginning of the string (default whitespace characters).
Example
The following example shows the usage of lstrip() method.
#!/usr/bin/python3
str = " this is string examplewow!!!"
print (str.lstrip())
str = "*****this is string example. wow!!!*****"
print (str.lstrip('*'))
Result
this is string examplewow!!!
this is string examplewow!!!*****
String maketrans() Method
Description
The maketrans() method returns a translation table that maps each character in the
intabstring into the character at the same position in the outtab string. Then this table is
passed to the translate() function.
Note: Both intab and outtab must have the same length.
Syntax
Following is the syntax for maketrans() method-
str.maketrans(intab, outtab]);
Parameters
• intab - This is the string having actual characters.
• outtab - This is the string having corresponding mapping character.
Return Value
This method returns a translate table to be used translate() function.
Example
The following example shows the usage of maketrans() method. Under this, every vowel in
a string is replaced by its vowel position −
#!/usr/bin/python3
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab) str = "this is string example. wow!!!"
print (str.translate(trantab))
Result
th3s 3s str3ng 2x1mpl2 w4w!!!
Syntax
Following is the syntax for max() method-
max(str)
Parameters
str - This is the string from which max alphabetical character needs to be returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
str = "this is a string example. really!!!"
print ("Max character: " + max(str))
str = "this is a string example. wow!!!"
print ("Max character: " + max(str))
Result
Max character: y
Max character: x
String min() Method
Description
The min() method returns the min alphabetical character from the string str.
Syntax
Following is the syntax for min() method-
min(str)
Parameters
str - This is the string from which min alphabetical character needs to be returned.
Return Value
This method returns the max alphabetical character from the string str.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
str = "www.helloworld.com"
print ("Min character: " + min(str))
str = "TUTORIALSPOINT"
print ("Min character: " + min(str))
Result
Min character: .
Min character: A
String replace() Method
Description
The replace() method returns a copy of the string in which the occurrences of old have been
replaced with new, optionally restricting the number of replacements to max.
Syntax
Following is the syntax for replace() method-
Return Value
This method returns a copy of the string with all occurrences of substring old replaced by
new. If the optional argument max is given, only the first count occurrences are replaced.
Example
The following example shows the usage of replace() method.
#!/usr/bin/python3
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Result
Syntax
Following is the syntax for rfind() method-
Return Value
This method returns last index if found and -1 otherwise.
Example
The following example shows the usage of rfind() method.
#!/usr/bin/python3
str1 = "this is really a string example wow!!!"
str2 = "is"
print (str1.rfind(str2))
print (str1.rfind(str2, 0, 10))
print (str1.rfind(str2, 10, 0))
print (str1.find(str2))
print (str1.find(str2, 0, 10))
print (str1.find(str2, 10, 0))
Result
5
5
-1
2
2
-1
String rindex() Method
Description
The rindex() method returns the last index where the substring str is found, or raises an
exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method-
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
#!/usr/bin/python3
str1 = "this is really a string example. wow!!!"
str2 = "is"
print (str1.rindex(str2)) print (str1.rindex(str2,10))
Result
5
Traceback (most recent call last):
File "test.py", line 5, in print (str1.rindex(str2,10))
ValueError: substring not found
String rjust() Method
Description
The rjust() method returns the string right justified in a string of length width. Padding is
done using the specified fillchar (default is a space). The original string is returned if width
is less than len(s).
Syntax
Following is the syntax for rjust() method-
str.rjust(width[, fillchar])
Parameters
• width - This is the string length in total after padding.
• fillchar - This is the filler character, default is a space.
Return Value
This method returns the string right justified in a string of length width. Padding is done
using the specified fillchar (default is a space). The original string is returned if the width is
less than len(s).
Example
The following example shows the usage of rjust() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print (str.rjust(50, '*'))
Result
******************this is string example wow!!!
Syntax
Following is the syntax for rstrip() method-
str.rstrip([chars])
Parameters
chars - You can supply what chars have to be trimmed.
Return Value
This method returns a copy of the string in which all chars have been stripped from the end
of the string (default whitespace characters).
Example
The following example shows the usage of rstrip() method.
#!/usr/bin/python3
str = " this is string example....wow!!! " print (str.rstrip())
str = "*****this is string example. wow!!!*****"
print (str.rstrip('*'))
Result
Syntax
Following is the syntax for split() method-
str.split(str="", num=string.count(str)).
Parameters
• str - This is any delimeter, by default it is space.
• num - this is number of lines to be made
Return Value
This method returns a list of lines.
Example
The following example shows the usage of split() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print (str.split( )) print (str.split('i',1))
print (str.split('w'))
Result
['this', 'is', 'string', 'example. wow!!!']
['th', 's is string example. wow!!!']
['this is string example....', 'o', '!!!']
String splitlines() Method
Description
The splitlines() method returns a list with all the lines in string, optionally including the line
breaks (if num is supplied and is true).
Syntax
Following is the syntax for splitlines() method-
str.splitlines( num=string.count('\n'))
Parameters
num - This is any number, if present then it would be assumed that the line breaks need to
be included in the lines.
Return Value
This method returns true if found matching with the string otherwise false.
Example
The following example shows the usage of splitlines() method.
#!/usr/bin/python3
str = "this is \nstring example \nwow!!!"
print (str.splitlines( ))
Result
['this is ', 'string example....', 'wow!!!']
String startswith() Method
Description
The startswith() method checks whether the string starts with str, optionally restricting the
matching with the given indices start and end.
Syntax
Following is the syntax for startswith() method-
str.startswith(str, beg=0,end=len(string));
Parameters
• str - This is the string to be checked.
• beg - This is the optional parameter to set start index of the matching boundary.
• end - This is the optional parameter to set start index of the matching boundary.
Return Value
This method returns true if found matching with the string otherwise false.
Example
The following example shows the usage of startswith() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print (str.startswith( 'this' ))
print (str.startswith( 'string', 8 ))
print (str.startswith( 'this', 2, 4 ))
Result
True True False
String strip() Method
Description
The strip() method returns a copy of the string in which all chars have been stripped from
the beginning and the end of the string (default whitespace characters).
Syntax
Following is the syntax for strip() method −
str.strip([chars]);
Parameters
chars - The characters to be removed from beginning or end of the string.
Return Value
This method returns a copy of the string in which all the chars have been stripped from the
beginning and the end of the string.
Example
The following example shows the usage of strip() method.
#!/usr/bin/python3
str = "*****this is string example wow!!!*****"
print (str.strip( '*' ))
Result
this is string examplewow!!!
String swapcase() Method
Description
The swapcase() method returns a copy of the string in which all the case-based characters
have had their case swapped.
Syntax
Following is the syntax for swapcase() method-
str.swapcase();
Parameters
NA
Return Value
This method returns a copy of the string in which all the case-based characters have had
their case swapped.
Example
The following example shows the usage of swapcase() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print (str.swapcase())
str = "This Is String Example. WOW!!!"
print (str.swapcase())
Result
THIS IS STRING EXAMPLE WOW!!!
tHIS iS sTRING eXAMPLE wow!!!
String title() Method
Description
The title() method returns a copy of the string in which first characters of all the words are
capitalized.
Syntax
Following is the syntax for title() method-
str.title();
Parameters
NA
Return Value
This method returns a copy of the string in which first characters of all the words are
capitalized.
Example
The following example shows the usage of title() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print (str.title())
Result
This Is String Example Wow!!!
String translate() Method
Description
The method translate() returns a copy of the string in which all the characters have been
translated using table (constructed with the maketrans() function in the string module),
optionally deleting all characters found in the string deletechars.
Syntax
Following is the syntax for translate() method-
str.translate(table[, deletechars]);
Parameters
• table - You can use the maketrans() helper function in the string module to create a
translation table.
• deletechars - The list of characters to be removed from the source string.
Return Value
This method returns a translated copy of the string.
Example
The following example shows the usage of translate() method. Under this, every vowel in a
string is replaced by its vowel position.
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example. wow!!!";
print (str.translate(trantab))
Result
th3s 3s str3ng 2x1mpl2 w4w!!!
Following is the example to delete 'x' and 'm' characters from the string-
#!/usr/bin/python3
from string import maketrans # Required to call maketrans function.
intab = "aeiouxm"
outtab = "1234512"
trantab = maketrans(intab, outtab)
str = "this is string example. wow!!!";
print (str.translate(trantab))
Result
th3s 3s str3ng 21pl2.w4w!!!
String upper() Method
Description
The upper() method returns a copy of the string in which all case-based characters have
been uppercased.
Syntax
Following is the syntax for upper() method −
str.upper()
Parameters
NA
Return Value
This method returns a copy of the string in which all case-based characters have been
uppercased.
Example
The following example shows the usage of upper() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print ("str.upper : ",str.upper())
Result
str.upper : THIS IS STRING EXAMPLE WOW!!!
String zfill() Method
Description
The zfill() method pads string on the left with zeros to fill width.
Syntax
Following is the syntax for zfill() method-
str.zfill(width)
Parameters
width - This is final width of the string. This is the width which we would get after filling
zeros.
Return Value
This method returns padded string.
Example
The following example shows the usage of zfill() method.
#!/usr/bin/python3
str = "this is string example. wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))
Result
Note: Unlike in Python 2, all strings are represented as Unicode in Python 3. Given Below is
an example illustrating it.
Syntax
Following is the syntax for isdecimal() method-
str.isdecimal()
Parameters
NA
Return Value
This method returns true if all the characters in the string are decimal, false otherwise.
Example
The following example shows the usage of isdecimal() method.
#!/usr/bin/python3
str = "this2016"
print (str.isdecimal())
str = "23443434"
print (str.isdecimal())
Result
False True
10. Python 3 – 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 the 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 the 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 the items in a list need not be of the same type.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
When the above code is executed, it produces the following result −
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000] print ("Value available at index 2 : ", list[2])
list[2] = 2001
print ("New value available at index 2 : ", list[2])
Note: The append() method is discussed in the subsequent section. When the above code is
executed, it produces the following result −
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000] print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
When the above code is executed, it produces the following result-
In fact, lists respond to all of the general sequence operations we used on strings in the
prior chapter.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.
Syntax
Following is the syntax for len() method-
len(list)
Parameters
list - This is a list for which, number of elements are to be counted.
Return Value
This method returns the number of elements in the list.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths'] print (len(list1))
list2=list(range(5)) #creates list of numbers between 0-4
print (len(list2))
When we run above program, it produces following result-
3
5
List max() Method
Description
The max() method returns the elements from the list with maximum value.
Syntax
Following is the syntax for max() method-
max(list)
Parameters
list - This is a list from which max valued element are to be returned.
Return Value
This method returns the elements from the list with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
When we run above program, it produces following result-
Syntax
Following is the syntax for min() method-
min(list)
Parameters
list - This is a list from which min valued element is to be returned.
Return Value
This method returns the elements from the list with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
list1, list2 = ['C++','Java', 'Python'], [456, 700, 200]
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
When we run above program, it produces following result-
Note: Tuple are very similar to lists with only difference that element values of a tuple can
not be changed and tuple elements are put between parentheses instead of square bracket.
This function also converts characters in a string into a list.
Syntax
Following is the syntax for list() method-
list( seq )
Parameters
seq - This is a tuple or string to be converted into list.
Return Value
This method returns the list.
Example
The following example shows the usage of list() method.
#!/usr/bin/python3
aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)
str="Hello World"
list2=list(str)
print ("List elements : ", list2)
When we run above program, it produces following result-
list.reverse()
8 Reverses objects of list in place
list.sort([func])
9 Sorts objects of list, use compare func if given
Syntax
Following is the syntax for append() method-
list.append(obj)
Parameters
obj - This is the object to be appended in the list.
Return Value
This method does not return any value but updates existing list.
Example
The following example shows the usage of append() method.
#!/usr/bin/python3
list1 = ['C++', 'Java', 'Python']
list1.append('C#')
print ("updated list : ", list1)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for count() method-
list.count(obj)
Parameters
obj - This is the object to be counted in the list.
Return Value
This method returns count of how many times obj occurs in list.
Example
The following example shows the usage of count() method.
#!/usr/bin/python3
aList = [123, 'xyz', 'zara', 'abc', 123];
print ("Count for 123 : ", aList.count(123))
print ("Count for zara : ", aList.count('zara'))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for extend() method-
list.extend(seq)
Parameters
seq - This is the list of elements
Return Value
This method does not return any value but adds the content to an existing list.
Example
The following example shows the usage of extend() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
list2=list(range(5)) #creates list of numbers between 0-4
list1.extend('Extended List :', list2)
print (list1)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for index() method-
list.index(obj)
Parameters
obj - This is the object to be find out.
Return Value
This method returns index of the found object otherwise raises an exception indicating that
the value is not found.
Example
The following example shows the usage of index() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))
When we run the above program, it produces the following result-
Index of chemistry 1
Traceback (most recent call last):
File "test.py", line 3, in
print ('Index of C#', list1.index('C#'))
ValueError: 'C#' is not in list
List insert() Method
Description
The insert() method inserts object obj into list at offset index.
Syntax
Following is the syntax for insert() method-
list.insert(index, obj)
Parameters
• index - This is the Index where the object obj need to be inserted.
• obj - This is the Object to be inserted into the given list.
Return Value
This method does not return any value but it inserts the given element at the given index.
Example
The following example shows the usage of insert() method.
#!/usr/bin/python3
list1 = ['physics', 'chemistry', 'maths']
list1.insert(1, 'Biology')
print ('Final list : ', list1)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for pop() method-
list.pop(obj=list[-1])
Parameters
obj - This is an optional parameter, index of the object to be removed from the list.
Return Value
This method returns the removed object from the list.
Example
The following example shows the usage of pop() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.pop()
print ("list now : ", list1)
list1.pop(1)
print ("list now : ", list1)
When we run the above program, it produces the following result-
Return Value
This method does not return any value but removes the given object from the list.
Example
The following example shows the usage of remove() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.remove('Biology')
print ("list now : ", list1)
list1.remove('maths')
print ("list now : ", list1)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for reverse() method-
list.reverse()
Parameters
NA
Return Value
This method does not return any value but reverse the given object from the list.
Example
The following example shows the usage of reverse() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.reverse()
print ("list now : ", list1)
When we run above program, it produces following result-
Syntax
Following is the syntax for sort() method-
list.sort([func])
Parameters
NA
Return Value
This method does not return any value but reverses the given object from the list.
Example
The following example shows the usage of sort() method.
#!/usr/bin/python3
list1 = ['physics', 'Biology', 'chemistry', 'maths']
list1.sort()
print ("list now : ", list1)
When we run the above program, it produces the following result-
tup1 = ();
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.
#!/usr/bin/python3
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the following result-
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable, which means you cannot update or change the values of tuple
elements. You are able to take portions of the existing tuples to create new tuples as the
following example demonstrates.
#!/usr/bin/python3
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples # tup1[0] = 100;
# So let's create a new tuple as follows tup3 = tup1 + tup2
print (tup3)
When the above code is executed, it produces the following result-
To explicitly remove an entire tuple, just use the del statement. For example-
#!/usr/bin/python3
tup = ('physics', 'chemistry', 1997, 2000); print (tup)
del tup;
print ("After deleting tup : ")
print (tup)
This produces the following result.
Note: An exception is 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
previous chapter.
No Enclosing Delimiters
No enclosing Delimiters is 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.
Built-in Tuple Functions
Python includes the following tuple functions-
cmp(tuple1, tuple2)
1
No longer available in Python 3.
len(tuple)
2
Gives the total length of the tuple.
max(tuple)
3
Returns item from the tuple with max value.
min(tuple)
4
Returns item from the tuple with min value.
tuple(seq)
5
Converts a list into tuple.
Tuple len() Method
Description
The len() method returns the number of elements in the tuple.
Syntax
Following is the syntax for len() method-
len(tuple)
Parameters
tuple - This is a tuple for which number of elements to be counted.
Return Value
This method returns the number of elements in the tuple.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print ("First tuple length : ", len(tuple1))
print ("Second tuple length : ", len(tuple2))
When we run above program, it produces following result-
Syntax
Following is the syntax for max() method-
max(tuple)
Parameters
tuple - This is a tuple from which max valued element to be returned.
Return Value
This method returns the elements from the tuple with maximum value.
Example
The following example shows the usage of max() method.
#!/usr/bin/python3
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for min() method-
min(tuple)
Parameters
tuple - This is a tuple from which min valued element is to be returned.
Return Value
This method returns the elements from the tuple with minimum value.
Example
The following example shows the usage of min() method.
#!/usr/bin/python3
tuple1, tuple2 = ('maths', 'che', 'phy', 'bio'), (456, 700, 200)
print ("min value element : ", min(tuple1))
print ("min value element : ", min(tuple2))
When we run the above program, it produces the following result-
min value element : bio
min value element : 200
Tuple tuple() Method
Description
The tuple() method converts a list of items into tuples.
Syntax
Following is the syntax for tuple() method-
tuple( seq )
Parameters
seq - This is a tuple to be converted into tuple.
Return Value
This method returns the tuple.
Example
The following example shows the usage of tuple() method.
#!/usr/bin/python3
list1= ['maths', 'che', 'phy', 'bio']
tuple1=tuple(list1)
print ("tuple elements : ", tuple1)
When we run the above program, it produces the following result-
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/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
When the above code is executed, it produces the following result-
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not a part of the dictionary, we get
an error as follows-
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print "dict['Alice']: ", dict['Alice']
When the above code is executed, it produces the following result-
dict['Zara']:
Traceback (most recent call last): File
"test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice']; KeyError:
'Alice'
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 in a simple example given below.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
When the above code is executed, it produces the following result-
To explicitly remove an entire dictionary, just use the del statement. Following is a simple
example-
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear() # remove all entries in dict del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
This produces the following result.
Note: An exception is raised because after del dict, the dictionary does not exist anymore.
dict['Age']:
Traceback (most recent call last): File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note: The del() method is discussed in subsequent section.
(a) More than one entry per key is not allowed. This means no duplicate key is allowed.
When duplicate keys are encountered during assignment, the last assignment wins. For
example-
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result-
dict['Name']: Manni
(b) Keys must be immutable. This 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/python3
dict = {['Name']: 'Zara', 'Age': 7}
print ("dict['Name']: ", dict['Name'])
When the above code is executed, it produces the following result-
Syntax
Following is the syntax for len() method-
len(dict)
Parameters
dict - This is the dictionary, whose length needs to be calculated.
Return Value
This method returns the length.
Example
The following example shows the usage of len() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Length : %d" % len (dict))
When we run the above program, it produces the following result-
Length : 3
Dictionary str() Method
Description
The method str() produces a printable string representation of a dictionary.
Syntax
Following is the syntax for str() method −
str(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns string representation.
Example
The following example shows the usage of str() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for type() method-
type(dict)
Parameters
dict - This is the dictionary.
Return Value
This method returns the type of the passed variable.
Example
The following example shows the usage of type() method.
#!/usr/bin/python3
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Variable Type : %s" % type (dict))
Syntax
Following is the syntax for clear() method-
dict.clear()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of clear() method.
Start Len : 2
End Len : 0
Dictionary copy() Method
Description
The method copy() returns a shallow copy of the dictionary.
Syntax
Following is the syntax for copy() method-
dict.copy()
Parameters
NA
Return Value
This method returns a shallow copy of the dictionary.
Example
The following example shows the usage of copy() method.
#!/usr/bin/python3
dict1 = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
dict2 = dict1.copy()
print ("New Dictionary : ",dict2)
When we run the above program, it produces following result-
Syntax
Following is the syntax for fromkeys() method-
dict.fromkeys(seq[, value]))
Parameters
• seq - This is the list of values which would be used for dictionary keys preparation.
• value - This is optional, if provided then value would be set to this value
Return Value
This method returns the list.
Example
The following example shows the usage of fromkeys() method.
#!/usr/bin/python3
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("New Dictionary : %s" % str(dict))
dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" % str(dict))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for get() method-
dict.get(key, default=None)
Parameters
• key - This is the Key to be searched in the dictionary.
• default - This is the Value to be returned in case key does not exist.
Return Value
This method returns a value for the given key. If the key is not available, then returns
default value as None.
Example
The following example shows the usage of get() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 27}
print ("Value : %s" % dict.get('Age'))
print ("Value : %s" % dict.get('Sex', "NA"))
When we run the above program, it produces the following result-
Value : 27 Value : NA
Dictionary items() Method
Description
The method items() returns a list of dict's (key, value) tuple pairs.
Syntax
Following is the syntax for items() method-
dict.items()
Parameters
NA
Return Value
This method returns a list of tuple pairs.
Example
The following example shows the usage of items() method.
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.items())
When we run the above program, it produces the following result-
Syntax
Following is the syntax for keys() method-
dict.keys()
Parameters
NA
Return Value
This method returns a list of all the available keys in the dictionary.
Example
The following example shows the usage of keys() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.keys())
When we run the above program, it produces the following result-
Value : ['Age', 'Name']
Dictionary setdefault() Method
Description
The method setdefault() is similar to get(), but will set dict[key]=default if the key is not
already in dict.
Syntax
Following is the syntax for setdefault() method-
dict.setdefault(key, default=None)
Parameters
• key - This is the key to be searched.
• default - This is the Value to be returned in case key is not found.
Return Value
This method returns the key value available in the dictionary and if given key is not
available then it will return provided default value.
Example
The following example shows the usage of setdefault() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for update() method-
dict.update(dict2)
Parameters
dict2 - This is the dictionary to be added into dict.
Return Value
This method does not return any value.
Example
The following example shows the usage of update() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print ("updated dict : ", dict)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for values() method-
dict.values()
Parameters
NA
Return Value
This method returns a list of all the values available in a given dictionary.
Example
The following example shows the usage of values() method.
#!/usr/bin/python3
dict = {'Sex': 'female', 'Age': 7, 'Name': 'Zara'}
print ("Values : ", list(dict.values()))
When we run above program, it produces following result-
Unlike other collections in Python, there is no index attached to the elements of the set, i.e.,
we cannot directly access any element of the set by the index. However, we can print them
all together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly
braces {}. Python also provides the set() method, which can be used to create the set by
the passed sequence.
Creating an empty set is a bit different because empty curly {} braces are also used to
create a dictionary as well. So Python provides the set() method used without an argument
to create an empty set.
set5 = {1,2,4,4,5,8,9,9,10}
print("Return set with unique elements:",set5)
Output:
Return set with unique elements: {1, 2, 4, 5, 8, 9, 10}
In the above code, we can see that set5 consisted of multiple duplicate elements when we
printed it remove the duplicity from the set.
Consider the following example to remove the item from the set using pop() method.
Python provides the clear() method to remove all the items from the set.
If the key to be deleted from the set using discard() doesn't exist in the set, the Python will
not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in the
set, the Python will raise an error.
{'castle'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or
intersection() method. Suppose there are two sets A and B, and the difference is A-B that
denotes the resulting set will be obtained that element of A, which is not present in the set
B.
The elements of the frozen set cannot be changed after the creation. We cannot change or
append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is
passed into this method which is converted into the frozen set as a return type of the
method.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after
creation
Output:
<class 'frozenset'>
printing the content of frozen set...
1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after
creation
AttributeError: 'frozenset' object has no attribute 'add'
Frozenset for the dictionary
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the
keys from the dictionary and returns a frozenset that contains the key of the dictionary as
its elements.
Consider the following example.
Example - 6: Write the program to find the issuperset, issubset and superset.
set1 = set(["Peter","James","Camroon","Ricky","Donald"])
set2 = set(["Camroon","Washington","Peter"])
set3 = set(["Peter"])
issubset = set1 >= set2
print(issubset)
issuperset = set1 <= set2
print(issuperset)
issubset = set3 <= set2
print(issubset)
issuperset = set2 >= set3
print(issuperset)
Output:
False
False
True
True
14. Python 3 – Date & Time
A Python program can handle date and time in several ways. Converting between date
formats is a common chore for computers. Python's time and calendar modules help track
dates and times.
What is Tick?
Time intervals are floating-point numbers in units of seconds. Particular instants in time are
expressed in seconds since 12:00am, January 1, 1970(epoch).
There is a popular time module available in Python, which provides functions for working
with times, and for converting between representations. The function time.time() returns
the current system time in ticks since 12:00am, January 1, 1970(epoch).
Example
#!/usr/bin/python3
import time; # This is required to include time module.
ticks = time.time()
print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
This would produce a result something as follows-
What is TimeTuple?
Many of the Python's time functions handle time as a tuple of 9 numbers, as shown below-
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
>>>import time
>>> print (time.localtime())
This would produce a result as follows-
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=9, tm_min=29,
tm_sec=2, tm_wday=0, tm_yday=46, tm_isdst=0)
The above tuple is equivalent to struct_time structure. This structure has the following
attributes-
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("Local current time :", localtime)
This would produce the following result, which could be formatted in any other presentable
form-
#!/usr/bin/python3
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("Local current time :", localtime)
This would produce the following result-
#!/usr/bin/python3
import calendar
cal = calendar.month(2016, 2)
print ("Here is the calendar:")
print (cal)
This would produce the following result-
DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if
daylight is nonzero.
Syntax
Following is the syntax for altzone() method-
time.altzone
Parameters
NA
Return Value
This method returns the offset of the local DST timezone, in seconds west of UTC, if one is
defined.
Example
The following example shows the usage of altzone() method.
#!/usr/bin/python3
import time
print ("time.altzone : ", time.altzone)
When we run the above program, it produces the following result-
time.altzone : -23400
Time asctime() Method
Description
The method asctime() converts a tuple or struct_time representing a time as returned by
gmtime() or localtime() to a 24-character string of the following form: 'Tue Feb 17 23:21:05
2009'.
Syntax
Following is the syntax for asctime() method-
time.asctime([t]))
Parameters
t - This is a tuple of 9 elements or struct_time representing a time as returned by gmtime()
or localtime() function.
Return Value
This method returns 24-character string of the following form: 'Tue Feb 17 23:21:05 2009'.
Example
The following example shows the usage of asctime() method.
#!/usr/bin/python3
import time
t = time.localtime()
print ("asctime : ",time.asctime(t))
When we run the above program, it produces the following result-
On Windows, this function returns wall-clock seconds elapsed since the first call to this
function, as a floating point number, based on the Win32 function Query Performance
Counter.
Syntax
Following is the syntax for clock() method-
time.clock()
Parameters
NA
Return Value
This method returns the current processor time as a floating point number expressed in
seconds on Unix and in Windows it returns wall-clock seconds elapsed since the first call to
this function, as a floating point number.
Example
The following example shows the usage of clock() method.
#!/usr/bin/python3
import time
def procedure(): time.sleep(2.5)
# measure process time t0 = time.clock() procedure()
print (time.clock() - t0, "seconds process time") # measure wall time
t0 = time.time()
procedure()
print (time.time() - t0, "seconds wall time")
When we run the above program, it produces the following result-
Syntax
Following is the syntax for ctime() method-
time.ctime([ sec ])
Parameters
sec - These are the number of seconds to be converted into string representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of ctime() method.
#!/usr/bin/python3
import time
print ("ctime : ", time.ctime())
When we run the above program, it produces the following result-
Syntax
Following is the syntax for gmtime() method-
time.gmtime([ sec ])
Parameters
sec - These are the number of seconds to be converted into structure struct_time
representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of gmtime() method.
#!/usr/bin/python3
import time
print ("gmtime :", time.gmtime(1455508609.34375))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for localtime() method-
time.localtime([ sec ])
Parameters
sec - These are the number of seconds to be converted into structure struct_time
representation.
Return Value
This method does not return any value.
Example
The following example shows the usage of localtime() method.
#!/usr/bin/python3
import time
print ("time.localtime() : %s" , time.localtime())
When we run the above program, it produces the following result-
time.localtime():time.struct_time(tm_year=2016,tm_mon=2,tm_mday=15, tm_hour=10,
tm_min=13, tm_sec=50, tm_wday=0, tm_yday=46, tm_isdst=0)
Time mktime() Method
Description
The method mktime() is the inverse function of localtime(). Its argument is the struct_time
or full 9-tuple and it returns a floating point number, for compatibility with time().
If the input value cannot be represented as a valid time, either OverflowError or ValueError
will be raised.
Syntax
Following is the syntax for mktime() method-
time.mktime(t)
Parameters
t - This is the struct_time or full 9-tuple.
Return Value
This method returns a floating point number, for compatibility with time().
Example
The following example shows the usage of mktime() method.
#!/usr/bin/python3
import time
t = (2016, 2, 15, 10, 13, 38, 1, 48, 0)
d=time.mktime(t)
print ("time.mktime(t) : %f" % d)
print ("asctime(localtime(secs)): %s" % time.asctime(time.localtime(d)))
When we run the above program, it produces the following result-
time.mktime(t) : 1455511418.000000
asctime(localtime(secs)): Mon Feb 15 10:13:38 2016
Time sleep() Method
Description
The method sleep() suspends execution for the given number of seconds. The argument
may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal will
terminate the sleep() following execution of that signal's catching routine.
Syntax
Following is the syntax for sleep() method-
time.sleep(t)
Parameters
t - This is the number of seconds for which the execution is to be suspended.
Return Value
This method does not return any value.
Example
The following example shows the usage of sleep() method.
#!/usr/bin/python3
import time
print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
When we run the above program, it produces the following result-
Start : Mon Feb 15 12:08:42 2016
End : Mon Feb 15 12:08:47 2016
Time strftime() Method
Description
The method strftime() converts a tuple or struct_time representing a time as returned by
gmtime() or localtime() to a string as specified by the format argument.
If t is not provided, the current time as returned by localtime() is used. The format must be
a string. An exception ValueError is raised if any field in t is outside of the allowed range.
Syntax
Following is the syntax for strftime() method-
time.strftime(format[, t])
Parameters
• t - This is the time in number of seconds to be formatted.
• format - This is the directive which would be used to format given time.
Directive
• %a - abbreviated weekday name
• %A - full weekday name
• %b - abbreviated month name
• %B - full month name
• %c - preferred date and time representation
• %C - century number (the year divided by 100, range 00 to 99)
• %d - day of the month (01 to 31)
• %D - same as %m/%d/%y
• %e - day of the month (1 to 31)
• %g - like %G, but without the century
• %G - 4-digit year corresponding to the ISO week number (see %V).
• %h - same as %b
• %H - hour, using a 24-hour clock (00 to 23)
• %I - hour, using a 12-hour clock (01 to 12)
• %j - day of the year (001 to 366)
• %m - month (01 to 12)
• %M - minute
• %n - newline character
• %p - either am or pm according to the given time value
• %r - time in a.m. and p.m. notation
• %R - time in 24 hour notation
• %S - second
• %t - tab character
• %T - current time, equal to %H:%M:%S
• %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
• %U - week number of the current year, starting with the first Sunday as the first day
of the first week
• %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is
the first week that has at least 4 days in the current year, and with Monday as the
first day of the week
• %W - week number of the current year, starting with the first Monday as the first
day of the first week
• %w - day of the week as a decimal, Sunday=0
• %x - preferred date representation without the time
• %X - preferred time representation without the date
• %y - year without a century (range 00 to 99)
• %Y - year including the century
• %Z or %z - time zone or name or abbreviation
• %% - a literal % character
Return Value
This method does not return any value.
Example
The following example shows the usage of strftime() method.
#!/usr/bin/python3
import time
t = (2015, 12, 31, 10, 39, 45, 1, 48, 0)
t = time.mktime(t)
print (time.strftime("%b %d %Y %H:%M:%S", time.localtime(t)))
When we run the above program, it produces the following result-
The format parameter uses the same directives as those used by strftime(); it defaults to
"%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
If string cannot be parsed according to format, or if it has excess data after parsing,
ValueError is raised.
Syntax
Following is the syntax for strptime() method-
time.strptime(string[, format])
Parameters
• string - This is the time in string format which would be parsed based on the given
format.
• format - This is the directive which would be used to parse the given string.
Directive
The following directives can be embedded in the format string-
• %a - abbreviated weekday name
• %A - full weekday name
• %b - abbreviated month name
• %B - full month name
• %c - preferred date and time representation
• %C - century number (the year divided by 100, range 00 to 99)
• %d - day of the month (01 to 31)
• %D - same as %m/%d/%y
• %e - day of the month (1 to 31)
• %g - like %G, but without the century
• %G - 4-digit year corresponding to the ISO week number (see %V).
• %h - same as %b
• %H - hour, using a 24-hour clock (00 to 23)
• %I - hour, using a 12-hour clock (01 to 12)
• %j - day of the year (001 to 366)
• %m - month (01 to 12)
• %M - minute
• %n - newline character
• %p - either am or pm according to the given time value
• %r - time in a.m. and p.m. notation
• %R - time in 24 hour notation
• %S - second
• %t - tab character
• %T - current time, equal to %H:%M:%S
• %u - weekday as a number (1 to 7), Monday=1. Warning: In Sun Solaris Sunday=1
• %U - week number of the current year, starting with the first Sunday as the first day
of the first week
• %V - The ISO 8601 week number of the current year (01 to 53), where week 1 is
the first week that has at least 4 days in the current year, and with Monday as the
first day of the week
• %W - week number of the current year, starting with the first Monday as the first
day of the first week
• %w - day of the week as a decimal, Sunday=0
• %x - preferred date representation without the time
• %X - preferred time representation without the date
• %y - year without a century (range 00 to 99)
• %Y - year including the century
• %Z or %z - time zone or name or abbreviation
• %% - a literal % character
Return Value
This return value is struct_time as returned by gmtime() or localtime().
Example
The following example shows the usage of strptime() method.
#!/usr/bin/python3
import time
struct_time = time.strptime("30 12 2015", "%d %m %Y")
print ("tuple : ", struct_time)
When we run the above program, it produces the following result-
Note: Even though the time is always returned as a floating point number, not all systems
provide time with a better precision than 1 second. While this function normally returns
non-decreasing values, it can return a lower value than a previous call if the system clock
has been set back between the two calls.
Syntax
Following is the syntax for time() method-
time.time()
Parameters
NA
Return Value
This method returns the time as a floating point number expressed in seconds since the
epoch, in UTC.
Example
The following example shows the usage of time() method.
#!/usr/bin/python3
import time
print ("time.time(): %f " % time.time())
print (time.localtime( time.time() ))
print (time.asctime( time.localtime(time.time()) ))
When we run the above program, it produces the following result-
time.time(): 1455519806.011433
time.struct_time(tm_year=2016, tm_mon=2, tm_mday=15, tm_hour=12, tm_min=33,
tm_sec=26, tm_wday=0, tm_yday=46, tm_isdst=0)
Mon Feb 15 12:33:26 2016
Time tzset() Method
Description
The method tzset() resets the time conversion rules used by the library routines. The
environment variable TZ specifies how this is done.
The standard format of the TZ environment variable is (whitespace added for clarity)-
Syntax
Following is the syntax for tzset() method-
time.tzset()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of tzset() method.
#!/usr/bin/python3
import time
import os
os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
time.tzset()
print time.strftime('%X %x %Z')
os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
time.tzset()
print time.strftime('%X %x %Z')
When we run the above program, it produces the following result-
By default, calendar takes Monday as the first day of the week and Sunday as the last one.
To change this, call the calendar.setfirstweekday() function.
As you already know, Python gives you many built-in functions like print(), etc. but you can
also create your own functions. These functions are called user-defined functions.
Defining a Function
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 the standard
screen.
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 an example to call the
printme() function-
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result-
#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Here, we are maintaining reference of the passed object and appending values in the same
object. Therefore, this would produce the following result-
#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
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/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function" print (str)
return
# Now you can call printme function
printme()
When the above code is executed, it produces the following result-
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-
My string
The following example gives a clearer picture. Note that the order of parameters does not
matter.
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
When the above code is executed, it produces the following result-
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result-
#!/usr/bin/python3
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result-
Output is: 10
Output is: 70
60
50
The Anonymous Functions
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 lambdas are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is to stack allocation by
passing function, during invocation for performance reasons.
Syntax
The syntax of lambda function contains only a single statement, which is as follows-
#!/usr/bin/python3
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
When the above code is executed, it produces the following result-
Value of total : 30
Value of total : 40
The return Statement
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 examples given above are not returning any value. You can return a value from a
function as follows-
#!/usr/bin/python3
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total )
When the above code is executed, it produces the following result-
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
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/python3
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
When the above code is executed, it produces the following result-
Example
# all values true
k = [1, 3, 4, 6]
print(all(k))
# all values false
k = [0, False]
print(all(k))
# one false value
k = [1, 3, 7, 0]
print(all(k))
# one true value
k = [0, False, 5]
print(all(k))
# empty iterable
k = []
print(all(k))
Output:
True
False
False
False
True
Python bin() Function
The python bin() function is used to return the binary representation of a specified integer.
A result always starts with the prefix 0b.
Example
x = 10
y = bin(x)
print (y)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth
testing procedure.
Example
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))
Output:
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version
of the bytearray() function.
Example
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Output:
b ' Hello World.'
Python callable() Function
A python callable() function in Python is something that can be called. This built-in function
checks and returns true if the object passed appears to be callable, otherwise false.
Example
x=8
print(callable(x))
Output:
False
Python compile() Function
The python compile() function takes source code as input and returns a code object which
can later be executed by exec() function.
Example
# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, 'sum.py', 'exec')
print(type(code))
exec(code)
exec(x)
Output:
<class 'code'>
sum = 15
Python exec() Function
The python exec() function is used for the dynamic execution of Python program which can
either be a string or object code and it accepts large blocks of code, unlike the eval()
function which only accepts a single expression.
Example
x=8
exec('print(x==8)')
exec('print(x+4)')
Output:
True
12
Python sum() Function
As the name says, python sum() function is used to get the sum of numbers of an iterable,
i.e., list.
Example
s = sum([1, 2,4 ])
print(s)
s = sum([1, 2, 4], 10)
print(s)
Output:
7
17
Python any() Function
The python any() function returns true if any item in an iterable is true. Otherwise, it
returns False.
Example
l = [4, 3, 2, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Output:
True
False
True
False
Python ascii() Function
The python ascii() function returns a string containing a printable representation of an
object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.
Example
normalText = 'Python is interesting'
print(ascii(normalText))
otherText = 'Pythön is interesting'
print(ascii(otherText))
print('Pyth\xf6n is interesting')
Output:
'Python is interesting'
'Pyth\xf6n is interesting'
Pythön is interesting
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray
objects, or create an empty bytearray object of the specified size.
Example
string = "Python is a programming language."
# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)
Output:
bytearray(b'Python is a programming language.')
Python eval() Function
The python eval() function parses the expression passed to it and runs python
expression(code) within the program.
Example
x=8
print(eval('x + 1'))
Output:
9
Python float()
The python float() function returns a floating-point number from a number or string.
Example
# for integers
print(float(9))
# for floats
print(float(8.19))
# for string floats
print(float("-24.27"))
# for string floats with whitespaces
print(float(“-17.19\n"))
# string float error
print(float("xyz"))
Output:
9.0
8.19
-24.27
-17.19
ValueError: could not convert string to float: 'xyz'
Python format() Function
The python format() function returns a formatted representation of the given value.
Example
# d, f and b are a type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
Output:
123
123.456790
1100
Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with
elements from the given iterable.
Example
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')
fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
Empty frozen set is: frozenset()
Python getattr() Function
The python getattr() function returns the value of a named attribute of an object. If it is not
found, it returns the default value.
Example
class Details:
age = 22
name = "Phill"
details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', details.age)
Output:
The age is: 22
The age is: 22
Python globals() Function
The python globals() function returns the dictionary of the current global symbol table.
A Symbol table is defined as a data structure which contains all the necessary information
about the program. It includes variable names, methods, classes, etc.
Example
age = 22
globals()['age'] = 22
print('The age is:', age)
Output:
The age is: 22
Python hasattr() Function
The python any() function returns true if any item in an iterable is true, otherwise it returns
False.
Example
l = [4, 3, 2, 0]
print(any(l))
l = [0, False]
print(any(l))
l = [0, False, 5]
print(any(l))
l = []
print(any(l))
Output:
True
False
True
False
Python iter() Function
The python iter() function is used to return an iterator object. It creates an object which can
be iterated one element at a time.
Example
# list of numbers
list = [1,2,3,4,5]
listIter = iter(list)
# prints '1'
print(next(listIter))
# prints '2'
print(next(listIter))
# prints '3'
print(next(listIter))
# prints '4'
print(next(listIter))
# prints '5'
print(next(listIter))
Output:
1
2
3
4
5
Python len() Function
The python len() function is used to return the length (the number of items) of an object.
Example
strA = 'Python'
print(len(strA))
Output:
6
Python list()
The python list() creates a list in python.
Example
# empty list
print(list())
# string
String = 'abcde'
print(list(String))
# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))
Output:
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]
[1,2,3,4,5]
Python locals() Function
The python locals() method updates and returns the dictionary of the current local symbol
table.
A Symbol table is defined as a data structure which contains all the necessary information
about the program. It includes variable names, methods, classes, etc.
Example
def localsAbsent():
return locals()
def localsPresent():
present = True
return locals()
print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())
Output:
localsAbsent: {}
localsPresent: {'present': True}
Python map() Function
The python map() function is used to return a list of results after applying a given function
to each item of an iterable(list, tuple etc.).
Example
def calculateAddition(n):
return n+n
numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)
# converting map object to set
numbersAddition = set(result)
print(numbersAddition)
Output:
<map object at 0x7fb04a6bec18>
{8, 2, 4, 6}
Python memoryview() Function
The python memoryview() function returns a memoryview object of the given argument.
Example
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')
mv = memoryview(randomByteArray)
# access the memory view's zeroth index
print(mv[0])
# It create byte from memory view
print(bytes(mv[0:2]))
# It create list from memory view
print(list(mv[0:3]))
Output:
65
b'AB'
[65, 66, 67]
Python object()
The python object() returns an empty object. It is a base for all the classes and holds the
built-in properties and methods which are default for all the classes.
Example
python = object()
print(type(python))
print(dir(python))
Output:
<class 'object'>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__']
Python open() Function
The python open() function opens the file and returns a corresponding file object.
Example
# opens python.text file of the current directory
f = open("python.txt")
# specifying full path
f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Python chr() Function
Python chr() function is used to get a string representing a character which points to a
Unicode code integer. For example, chr(97) returns the string 'a'. This function takes an
integer argument and throws an error if it exceeds the specified range. The standard range
of the argument is from 0 to 1,114,111.
Example
# Calling function
result = chr(102) # It returns string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)
Output:
Example
# Python complex() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)
Output:
(1.5+0j)
(1.5+2.2j)
Python delattr() Function
Python delattr() function is used to delete an attribute from a class. It takes two
parameters, first is an object of the class and second is an attribute which we want to
delete. After deleting the attribute, it no longer available in the class and throws an error if
try to call it using the class object.
Example
class Student:
id = 101
name = "Pranshu"
email = "pranshu@abc.com"
# Declaring function
def getinfo(self):
print(self.id, self.name, self.email)
s = Student()
s.getinfo()
delattr(Student,'course') # Removing attribute which is not available
s.getinfo() # error: throws an error
Output:
101 Pranshu pranshu@abc.com
AttributeError: course
Python dir() Function
Python dir() function returns the list of names in the current local scope. If the object on
which method is called has a method named __dir__(), this method will be called and must
return the list of attributes. It takes a single object type argument.
Example
# Calling function
att = dir()
# Displaying result
print(att)
Output:
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__']
Python divmod() Function
Python divmod() function is used to get remainder and quotient of two numbers. This
function takes two numeric arguments and returns a tuple. Both arguments are required
and numeric
Example
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)
Output:
(5, 0)
Python enumerate() Function
Python enumerate() function returns an enumerated object. It takes two parameters, first is
a sequence of elements and the second is the start index of the sequence. We can get the
elements in sequence either through a loop or next() method.
Example
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))
Output:
<enumerate object at 0x7ff641093d80>
[(0, 1), (1, 2), (2, 3)]
Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary provides
three different constructors to create a dictionary:
If a positional argument is given, a dictionary is created with the same key-value pairs.
Otherwise, pass an iterable object.
If keyword arguments are given, the keyword arguments and their values are added to the
dictionary created from the positional argument.
Example
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)
Output:
{}
{'a': 1, 'b': 2}
Python filter() Function
Python filter() function is used to get filtered elements. This function takes two arguments,
first is a function and the second is iterable. The filter function returns a sequence of those
elements of iterable object for which function returns true value.
The first argument can be none, if the function is not available and returns only elements
that are true.
Example
# Python filter() function example
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
Output:
[6]
Python hash() Function
Python hash() function is used to get the hash value of an object. Python calculates the
hash value by using the hash algorithm. The hash values are integers and used to compare
dictionary keys during a dictionary lookup. We can hash only the types which are given
below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
Example
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)
print(result2)
Output:
21
461168601842737174
Python help() Function
Python help() function is used to get help related to the object passed during the call. It
takes an optional parameter and returns help information. If no argument is given, it shows
the Python help console. It internally calls python's help function.
Example
# Calling function
info = help() # No argument
# Displaying result
print(info)
Output:
Example
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result
print(small)
print(small2)
Output:
325
1000.25
Python set() Function
In python, a set is a built-in class, and this function is a constructor of this class. It is used
to create a new set using elements passed during the call. It takes an iterable object as an
argument and returns a new set object.
Example
# Calling function
result = set() # empty set
result2 = set('12')
result3 = set('javatpoint')
# Displaying result
print(result)
print(result2)
print(result3)
Output:
set()
{'1', '2'}
{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}
Python hex() Function
Python hex() function is used to generate hex value of an integer argument. It takes an
integer argument and returns an integer converted into a hexadecimal string. In case, we
want to get a hexadecimal value of a float, then use float.hex() function.
Example
# Calling function
result = hex(1)
# integer value
result2 = hex(342)
# Displaying result
print(result)
print(result2)
Output:
0x1
0x156
Python id() Function
Python id() function returns the identity of an object. This is an integer which is guaranteed
to be unique. This function takes an argument as an object and returns a unique integer
number which represents identity. Two objects with non-overlapping lifetimes may have the
same id() value.
Example
# Calling function
val = id("Javatpoint") # string object
val2 = id(1200) # integer object
val3 = id([25,336,95,236,92,3225]) # List object
# Displaying result
print(val)
print(val2)
print(val3)
Output:
139963782059696
139963805666864
139963781994504
Python setattr() Function
Python setattr() function is used to set a value to the object's attribute. It takes three
arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is helpful
when we want to add a new attribute to an object and set a value to it.
Example
class Student:
id = 0
name = ""
student = Student(102,"Sohan")
print(student.id)
print(student.name)
#print(student.email) product error
setattr(student, 'email','sohan@abc.com') # adding new attribute
print(student.email)
Output:
102
Sohan
sohan@abc.com
Python slice() Function
Python slice() function is used to get a slice of elements from the collection of elements.
Python provides two overloaded slice functions. The first function takes a single argument
while the second function takes three arguments and returns a slice object. This slice object
can be used to get a subsection of the collection.
Example
# Calling function
result = slice(5) # returns slice object
result2 = slice(0,5,3) # returns slice object
# Displaying result
print(result)
print(result2)
Output:
slice(None, 5, None)
slice(0, 5, 3)
Python sorted() Function
Python sorted() function is used to sort elements. By default, it sorts elements in an
ascending order but can be sorted in descending also. It takes four arguments and returns a
collection in sorted order. In the case of a dictionary, it sorts only keys, not values.
Example
str = "javatpoint" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)
Output:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Python next() Function
Python next() function is used to fetch next item from the collection. It takes two
arguments, i.e., an iterator and a default value, and returns an element.
This method calls on iterator and throws an error if no item is present. To avoid the error,
we can set a default value.
Example
number = iter([256, 32, 82]) # Creating iterator
# Calling function
item = next(number)
# Displaying result
print(item)
# second item
item = next(number)
print(item)
# third item
item = next(number)
print(item)
Output:
256
32
82
Python input() Function
Python input() function is used to get an input from the user. It prompts for the user input
and reads a line. After reading data, it converts it into a string and returns it. It throws an
error EOFError if EOF is read.
Example
# Calling function
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
Python int() Function
Python int() function is used to get an integer value. It returns an expression converted into
an integer number. If the argument is a floating-point, the conversion truncates the
number. If the argument is outside the integer range, then it converts the number into a
long type.
If the number is not a number or if a base is given, the number must be a string.
Example
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
Output:
integer values : 10 10 10
Python isinstance() Function
Python isinstance() function is used to check whether the given object is an instance of that
class. If the object belongs to the class, it returns true. Otherwise returns False. It also
returns true if the class is a subclass.
The isinstance() function takes two arguments, i.e., object and classinfo, and then it returns
either True or False.
Example
class Student:
id = 101
name = "John"
def __init__(self, id, name):
self.id=id
self.name=name
student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))
Output:
True
False
Python oct() Function
Python oct() function is used to get an octal value of an integer number. This method takes
an argument and returns an integer converted into an octal string. It throws an error
TypeError, if argument type is other than an integer.
Example
# Calling function
val = oct(10)
# Displaying result
print("Octal value of 10:",val)
Output:
Octal value of 10: 0o12
Python ord() Function
The python ord() function returns an integer representing Unicode code point for the given
Unicode character.
Example
# Code point of an integer
print(ord('8'))
# Code point of an alphabet
print(ord('R'))
# Code point of a character
print(ord('&'))
Output:
56
82
38
Python pow() Function
The python pow() function is used to compute the power of a number. It returns x to the
power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e.
(x, y) % z.
Example
# positive x, positive y (x**y)
print(pow(4, 2))
# negative x, positive y
print(pow(-4, 2))
# positive x, negative y (x**-y)
print(pow(4, -2))
# negative x, negative y
print(pow(-4, -2))
Output:
16
16
0.0625
0.0625
Python print() Function
The python print() function prints the given object to the screen or other standard output
devices.
Example
print("Python is programming language.")
x=7
# Two objects passed
print("x =", x)
y=x
# Three objects passed
print('x =', x, '= y')
Output:
Python is programming language.
x=7
x=7=y
Python range() Function
The python range() function returns an immutable sequence of numbers starting from 0 by
default, increments by 1 (by default) and ends at a specified number.
Example
# empty range
print(list(range(0)))
# using the range(stop)
print(list(range(4)))
# using the range(start, stop)
print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Python reversed() Function
The python reversed() function returns the reversed iterator of the given sequence.
Example
# for string
String = 'Java'
print(list(reversed(String)))
# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
# for range
Range = range(8, 12)
print(list(reversed(Range)))
# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))
Output:
['a', 'v', 'a', 'J']
['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]
Python round() Function
The python round() function rounds off the digits of a number and returns the floating point
number.
Example
# for integers
print(round(10))
# for floating point
print(round(10.8))
# even choice
print(round(6.6))
Output:
10
11
7
Python issubclass() Function
The python issubclass() function returns true if object argument(first argument) is a
subclass of second class(second argument).
Example
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)
class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')
print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))
Output:
True
False
True
True
Python str
The python str() converts a specified value into a string.
Example
str('4')
Output:
'4'
Python tuple() Function
The python tuple() function is used to create a tuple object.
Example
t1 = tuple()
print('t1=', t1)
# creating a tuple from a list
t2 = tuple([1, 6, 9])
print('t2=', t2)
# creating a tuple from a string
t1 = tuple('Java')
print('t1=',t1)
# creating a tuple from a dictionary
t1 = tuple({4: 'four', 5: 'five'})
print('t1=',t1)
Output:
t1= ()
t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)
Python type()
The python type() returns the type of the specified object if a single argument is passed to
the type() built in function. If three arguments are passed, then it returns a new type
object.
Example
List = [4, 5]
print(type(List))
Dict = {4: 'four', 5: 'five'}
print(type(Dict))
class Python:
a=0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
Python vars() function
The python vars() function returns the __dict__ attribute of the given object.
Example
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y
InstanceOfPython = Python()
print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}
Python zip() Function
The python zip() Function returns a zip object, which maps a similar index of multiple
containers. It takes iterables (can be zero or more), makes it an iterator that aggregates
the elements based on iterables passed, and returns an iterator of tuples.
Example
numList = [4,5, 6]
strList = ['four', 'five', 'six']
# No iterables are passed
result = zip()
# Converting itertor to list
resultList = list(result)
print(resultList)
# Two iterables are passed
result = zip(numList, strList)
# Converting itertor to set
resultSet = set(result)
print(resultSet)
Output:
[]
{(5, 'five'), (4, 'four'), (6, 'six')}
16. Python 3 – 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 namedaname.py.
Here is an example of a simple module, support.py-
#!/usr/bin/python3
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result-
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening repeatedly, if multiple imports occur.
#!/usr/bin/python3
# Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
>>> from fib import fib
>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
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.
#!/usr/bin/python3
# Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
if name == " main ":
f=fib(100)
print(f)
When you run the above code, the following output will be displayed.
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.
Namespaces and Scoping
Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).
• 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 assign Money 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/python3
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)
The dir( ) Function
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-
#!/usr/bin/python3
# Import built-in module math
import math
content = dir(math)
print (content)
When the above code is executed, it produces the following result-
[' doc ', ' file ', ' name ', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e',
'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
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
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 keys() function.
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 the following line of source
code-
#!/usr/bin/python3
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same name as above.
They are −
Now, create one more file init .py in the Phone directory-
To make all of your functions available when you have imported Phone, you need to put
explicit import statements in init .py as follows-
#!/usr/bin/python3
print ("Python is really a great language,", "isn't it?")
This produces the following result on your standard screen-
In Python 3, raw_input() function is deprecated. Moreover, input() functions read data from
keyboard as string, irrespective of whether it is enclosed with quotes ('' or "" ) or not.
#!/usr/bin/python3
>>> x=input("something:") something:10
>>> x '10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x "'10'"
Opening and Closing Files
Until now, you have been reading and writing to the standard input and output. Now, we
will see how to use actual data 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.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details-
• file_name: The file_name argument is a string value that contains the name of the
file that you want to access.
• access_mode: The access_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 an 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 default (default
behavior).
Modes Description
Opens a file for reading only. The file pointer is placed at the beginning of the
r
file. This is the default mode.
Opens a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the
r+
beginning of the file.
Opens a file for both reading and writing in binary format. The file pointer
rb+
placed at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the file
w
does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the file
wb
exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if the file
w+
exists. If the file does not exist, creates a new file for reading and writing.
Opens a file for both writing and reading in binary format. Overwrites the
wb+ existing file if the file exists. If the file does not exist, creates a new file for
reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the file
a exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.
Opens a file for appending in binary format. The file pointer is at the end of the
ab file if the file exists. That is, the file is in the append mode. If the file doesnot
exist, it creates a new file for writing.
Opens a file for both appending and reading. The file pointer is at the end of
a+ the 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.
Opens a file for both appending and reading in binary format. The file pointeris
ab+ at the end of the file if the file exists. The file opens in the append mode. Ifthe
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.
Attribute Description
file.closed Returns true if file is closed, false otherwise.
Example
#!/usr/bin/python3
# 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)
fo.close()
This produces the following result-
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
fileObject.close();
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
This produces the following result-
The write() method does not add a newline character ('\n') to the end of the string-
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file fo.close()
The above method would create foo.txt file and would write given content in that file and
finally it would close that file. If you would open this file, it would have the following
content-
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it tries to
read as much as possible, maybe until the end of file.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str) # Close opened file
fo.close()
This produces the following result-
If from is set to 0, the beginning of the file is used as the reference position. If it is set to 1,
the current position is used as the reference position. 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/python3
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Check current position
position = fo.tell()
print ("Current file position : ", position)
# Reposition pointer at the beginning once again
position = fo.seek(0, 0)
str = fo.read(10)
print ("Again read String is : ", str) # Close opened file
fo.close()
This produces the following result-
To use this module, you need to import it first and then you can call any related functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is an example to rename an existing file test1.txt-
#!/usr/bin/python3
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.
Syntax
os.remove(file_name)
Example
Following is an example to delete an existing file test2.txt-
#!/usr/bin/python3
import os
# Delete file test2.txt
os.remove("text2.txt")
Directories in Python
All files are contained within various directories, and Python has no problem handling these
too. The os module has several methods that help you create, remove, and change
directories.
Syntax
os.mkdir("newdir")
Example
Following is an example to create a directory test in the current directory-
#!/usr/bin/python3
Import os
# Create a directory "test"
os.mkdir("test")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes
an argument, which is the name of the directory that you want to make the current
directory.
Syntax
os.chdir("newdir")
Example
Following is an example to go into "/home/newdir" directory-
#!/usr/bin/python3
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
The getcwd() Method
The getcwd() method displays the current working directory.
Syntax
os.getcwd()
Example
Following is an example to give current directory-
#!/usr/bin/python3
import os
# This would give location of the current directory
os.getcwd()
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an argument in the method.
Before removing a directory, all the contents in it should be removed.
Syntax
os.rmdir('dirname')
Example
Following is an example to remove the "/tmp/test" directory. It is required to give fully
qualified name of the directory, otherwise it would search for that directory in the current
directory.
#!/usr/bin/python3
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to handle
and manipulate files & directories on Windows and Unix operating systems. They are as
follows-
• File Object Methods: The file object provides functions to manipulate files.
• OS Object Methods: This provides methods to process files as well as directories.
File Methods
A file object is created using open function and here is a list of functions which can be called
on this object.
S.No.
Methods with Description
file.close()
1
Close the file. A closed file cannot be read or written any more.
file.flush()
2 Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like
objects.
file.fileno()
3 Returns the integer file descriptor that is used by the underlying implementation
to request I/O operations from the operating system.
file.isatty()
4
Returns True if the file is connected to a tty(-like) device, else False.
next(file)
5
Returns the next line from the file each time it is being called.
file.read([size])
6 Reads at most size bytes from the file (less if the read hits EOF before obtaining
size bytes).
file.readline([size])
7 Reads one entire line from the file. A trailing newline character is kept in the
string.
file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the
8 optional sizehint argument is present, instead of reading up to EOF, whole lines
totalling approximately sizehint bytes (possibly after rounding up to an internal
buffer size) are read.
file.seek(offset[, whence])
9
Sets the file's current position
file.tell()
10
Returns the file's current position
file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
file.write(str)
12
Writes a string to the file. There is no return value.
file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.
Let us go through the above mentions methods briefly.
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax
Following is the syntax for close() method-
fileObject.close()
Parameters
NA
Return Value
This method does not return any value.
Example
The following example shows the usage of close() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
# Close opened file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for fileno() method-
fileObject.fileno()
Parameters
NA
Return Value
This method returns the integer file descriptor.
Example
The following example shows the usage of fileno() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fid = fo.fileno()
print ("File Descriptor: ", fid)
# Close opend file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for isatty() method-
fileObject.isatty()
Parameters
NA
Return Value
This method returns true if the file is connected (is associated with a terminal device) to a
tty(-like) device, else false.
Example
The following example shows the usage of isatty() method-
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
ret = fo.isatty()
print ("Return value : ", ret)
# Close opend file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for next() method-
next(iterator[,default])
Parameters
• iterator : file object from which lines are to be read
• default : returned if iterator exhausted. If not given, StopIteration is raised
Return Value
This method returns the next input line.
Example
The following example shows the usage of next() method-
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
for index in range(5):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for read() method-
fileObject.read( size );
Parameters
size - This is the number of bytes to be read from the file.
Return Value
This method returns the bytes read in string.
Example
The following example shows the usage of read() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.read(10)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for readline() method-
fileObject.readline( size );
Parameters
size - This is the number of bytes to be read from the file.
Return Value
This method returns the line read from the file.
Example
The following example shows the usage of readline() method.
Syntax
Following is the syntax for readlines() method-
fileObject.readlines( sizehint );
Parameters
sizehint - This is the number of bytes to be read from the file.
Return Value
This method returns a list containing the lines.
Example
The following example shows the usage of readlines() method.
#!/usr/bin/python3
# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
line = fo.readlines(2)
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
When we run above program, it produces following result-
There is no return value. Note that if the file is opened for appending using either 'a' or 'a+',
any seek() operations will be undone at the next write.
If the file is only opened for writing in append mode using 'a', this method is essentially a
no-op, but it remains useful for files opened in append mode with reading enabled (mode
'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of
other offsets causes undefined behavior.
Syntax
Following is the syntax for seek() method-
fileObject.seek(offset[, whence])
Parameters
• offset- This is the position of the read/write pointer within the file.
• whence- This is optional and defaults to 0 which means absolute file positioning,
other values are 1 which means seek relative to the current position and 2 means
seek relative to the file's end.
Return Value
This method does not return any value.
Example
The following example shows the usage of seek() method.
Syntax
Following is the syntax for tell() method-
fileObject.tell()
Parameters
NA
Return Value
This method returns the current position of the file read/write pointer within the file.
Example
The following example shows the usage of tell() method-
#!/usr/bin/python3
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
pos=fo.tell()
print ("current position : ",pos)
# Close opened file
fo.close()
When we run the above program, it produces the following result-
The size defaults to the current position. The current file position is not changed. Note that
if a specified size exceeds the file's current size, the result is platform-dependent.
Note: This method will not work in case the file is opened in read-only mode.
Syntax
Following is the syntax for truncate() method-
fileObject.truncate( [ size ])
Parameters
size - If this optional argument is present, the file is truncated to (at most) that size.
Return Value
This method does not return any value.
Example
The following example shows the usage of truncate() method.
#!/usr/bin/python3
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))
# Close opened file
fo.close()
When we run the above program, it produces the following result-
Name of the file: foo.txt
Read Line: This is 1s
Read Line: []
File write() Method
Description
The method write() writes a string str to the file. There is no return value. Due to buffering,
the string may not actually show up in the file until the flush() or close() method is called.
Syntax
Following is the syntax for write() method-
fileObject.write( str )
Parameters
str - This is the String to be written in the file.
Return Value
This method does not return any value.
Example
The following example shows the usage of write() method.
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
str = "This is 6th line"
# Write a line at the end of the file.
fo.seek(0, 2)
line = fo.write( str )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(6):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
When we run the above program, it produces the following result-
Syntax
Following is the syntax for writelines() method −
fileObject.writelines( sequence )
Parameters
sequence - This is the Sequence of the strings.
Return Value
This method does not return any value.
Example
The following example shows the usage of writelines() method.
#!/usr/bin/python3
# Open a file in read/write mode
fo = open("abc.txt", "r+")
print ("Name of the file: ", fo.name)
seq = ["This is 6th line\n", "This is 7th line"]
#Writesequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = next(fo)
print ("Line No %d - %s" % (index, line))
# Close opened file
fo.close()
When we run the above program, it produces the following result-
os.chdir() Method
Description
The method chdir() changes the current working directory to the given path.It returns None
in all the cases.
Syntax
Following is the syntax for chdir() method-
os.chdir(path)
Parameters
path - This is complete path of the directory to be changed to a new location.
Return Value
This method does not return any value. It throws FileNotFoundError if the specified path is
not found.
Example
The following example shows the usage of chdir() method.
#!/usr/bin/python3
import os
path = "d:\\python3" #change path for linux # Now change the directory
os.chdir( path )
# Check current working directory.
retval = os.getcwd()
print ("Directory changed successfully %s" % retval)
When we run the above program, it produces the following result-
Syntax
Following is the syntax for getcwd() method-
os.getcwd(path)
Parameters
NA
Return Value
This method returns the current working directory of a process.
Example
The following example shows the usage of getcwd() method-
#!/usr/bin/python3
import os, sys
# First go to the "/var/www/html" directory
os.chdir("/var/www/html" )
# Print current working directory
print ("Current working dir : %s" % os.getcwd())
# Now open a directory "/tmp"
fd = os.open( "/tmp", os.O_RDONLY )
# Use os.fchdir() method to change the dir
os.fchdir(fd)
# Print current working directory
print ("Current working dir : %s" % os.getcwd())
# Close opened directory.
os.close( fd )
When we run the above program, it produces the following result-
os.mkdir(path[, mode])
Parameters
• path - This is the path, which needs to be created.
• mode - This is the mode of the directories to be given.
Return Value
This method does not return any value.
Example
The following example shows the usage of mkdir() method.
#!/usr/bin/python3
import os, sys
# Path to be created
path = "/tmp/home/monthly/daily/hourly"
os.mkdir( path, 0755 );
print(“Path is created")
When we run the above program, it produces the following result-
Path is created
os.remove() Method
Description
The method remove() removes the file path. If the path is a directory, OSError is raised.
Syntax
Following is the syntax for remove() method-
os.remove(path)
Parameters
path - This is the path, which is to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of remove() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))
# removing
os.remove("test.java")
# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))
When we run above program, it produces following result-
Syntax
Following is the syntax for rename() method-
os.rename(src, dst)
Parameters
• src - This is the actual name of the file or directory.
• dst - This is the new name of the file or directory.
Return Value
This method does not return any value.
Example
The following example shows the usage of rename() method.
#!/user/bin/python3
import os, sys
os.chdir("d:\\tmp")
# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))
# renaming directory
os.rename("python3","python2")
print ("Successfully renamed.")
# listing directories after renaming "python3"
print ("the dir is: %s" %os.listdir(os.getcwd()))
When we run the above program, it produces the following result-
Syntax
Following is the syntax for rmdir() method-
os.rmdir(path)
Parameters
path - This is the path of the directory, which needs to be removed.
Return Value
This method does not return any value.
Example
The following example shows the usage of rmdir() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")
# listing directories
print ("the dir is: %s" %os.listdir(os.getcwd()))
# removing path
os.rmdir("newdir")
# listing directories after removing directory path
print ("the dir is:" %os.listdir(os.getcwd()))
When we run the above program, it produces the following result-
• Exception Handling.
• Assertions.
Standard Exceptions
Raised when the next() method of an iterator does not point toany
StopIteration
object.
ArithmeticError Base class for all errors that occur for numeric calculation.
OverflowError Raised when a calculation exceeds maximum limit for a numeric type.
KeyError Raised when the specified key is not found in the dictionary.
RuntimeError Raised when a generated error does not fall into any category.
Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you are done with your
testing of the program.
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))
When the above code is executed, it produces the following result-
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!" AssertionError: Colder than
absolute zero!
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object
that represents an error.
When a Python script raises an exception, it must either handle the exception immediately
otherwise it terminates and quits.
Handling an Exception
If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an
except: statement, followed by a block of code which handles the problem as elegantly as
possible.
Syntax
Here is simple syntax of try....except...else blocks-
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block. except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax-
• A single try statement can have multiple except statements. This is useful when the
try block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's protection.
Example
This example opens a file, writes content in the file and comes out gracefully because there
is no problem at all.
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()
This produces the following result-
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
This produces the following result-
try:
You do your operations here
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind of
try-except statement is not considered a good programming practice though, because it
catches all exceptions but does not make the programmer identify the root cause of the
problem that may occur.
try:
You do your operations here
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list, then execute this block.
......................
else:
If there is no exception then execute this block.
The try-finally Clause
You can use a finally: block along with a try: block. The finally: block is a place to put any
code that must execute, whether the try-block raised an exception or not. The syntax of the
try-finally statement is this-
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Note: You can provide except clause(s), or a finally clause, but not both. You cannot use
else clause as well along with a finally clause.
Example
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()
If you do not have permission to open the file in writing mode, then this will produce the
following result-
#!/usr/bin/python3
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print ("Going to close the file")
fh.close()
except IOError:
print ("Error: can\'t find file or read data")
When an exception is thrown in the try block, the execution immediately passes to the
finally block. After all the statements in the finally block are executed, the exception is
raised again and is handled in the except statements if present in the next higher layer of
the try-except statement.
Raising an Exception
You can raise exceptions in several ways by using the raise statement. The general syntax
for the raise statement is as follows-
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value
for the exception argument. The argument is optional; if not supplied, the exception
argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present,
is the traceback object used for the exception.
Example
An exception can be a string, a class or an object. Most of the exceptions that the Python
core raises are classes, with an argument that is an instance of the class. Defining new
exceptions is quite easy and can be done as follows-
try:
Business Logic here...
except Exception as e:
Exception handling here using e.args...
else:
Rest of the code here...
The following example illustrates the use of raising an exception-
#!/usr/bin/python3
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",e.args[0])
This will produce the following result-
Here is an example related to RuntimeError. Here, a class is created that is subclassed from
RuntimeError. This is useful when you need to display more specific information when an
exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def init (self, arg):
self.args = arg
So once you have defined the above class, you can raise the exception as follows-
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print(e.args)
Python 3 – Advanced Tutorial
19. Python 3 – Object Oriented
Python has been an object-oriented language since the time it existed. Due to this, creating
and using classes and objects are downright easy. This chapter helps you become an expert
in using Python's object-oriented programming support.
If you do not have any previous experience with object-oriented (OO) programming, you
may want to consult an introductory course on it or at least a tutorial of some sort so that
you have a grasp of the basic concepts.
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:
'Optional class documentation string'
class_suite
• The class has a documentation string, which can be accessed via
ClassName.__doc__.
• The class_suite consists of all the component statements defining class members,
data attributes and functions.
Example
Following is an example of a simple Python class-
class Employee:
'Common base class for all employees'
empCount = 0
def init (self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
• 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.
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
Now, putting all the concepts together-
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def init (self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
#This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
#This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
When the above code is executed, it produces the following result-
#!/usr/bin/python3
class Employee:
'Common base class for all employees'
empCount = 0
def init (self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
print ("Employee. doc :", Employee. doc )
print ("Employee. name :", Employee. name )
print ("Employee. module :", Employee. module )
print ("Employee. bases :", Employee. bases )
print ("Employee. dict :", Employee. dict )
When the above code is executed, it produces the following result-
Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes.
Example
This del __()__ destructor prints the class name of an instance that is about to be
destroyed.
#!/usr/bin/python3
class Point:
def init( self, x=0, y=0):
self.x = x
self.y = y
def del (self):
class_name = self. class . name
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts)
del pt1
del pt2
del pt3
When the above code is executed, it produces the following result-
In the above example, assuming definition of a Point class is contained in point.py and there
is no other executable code in it.
#!/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 −
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
#!/usr/bin/python3
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method')
class Child(Parent): # define child class
def myMethod(self):
print ('Calling child method')
c = Child() # instance of child
c.myMethod() # child calls overridden method
When the above code is executed, it produces the following result-
__str__( self )
4 Printable string representationSample Call : str(obj)
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
#!/usr/bin/python3
class Vector:
def init (self, a, b):
self.a = a
self.b = b
def str (self):
return 'Vector (%d, %d)' % (self.a, self.b)
def add (self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
When the above code is executed, it produces the following result-
Vector(7,8)
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
#!/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)
When the above code is executed, it produces the following result-
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module> print counter. secretCount
AttributeError: JustCounter instance has no attribute ' secretCount'
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className attrName. If you would replace your
last line as following, then it works for you-
.........................
print (counter._JustCounter secretCount)
When the above code is executed, it produces the following result-
1
2
2
20. Python 3 – Regular Expressions
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. Nevertheless, 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 asr'expression'.
Compilation flags
Compilation flags let you modify some aspects of how regular expressions work. Flags are
available in the re module under two names, a long name such as IGNORECASE and a
short, one-letter form such as I.
Flag Meaning
Makes several escapes like \w, \b, \s and \d match only on ASCII
ASCII, A
characters with the respective property.
VERBOSE, X (for Enable verbose REs, which can be organized more cleanly and
‘extended’) understandably
The match Function
This function attempts to match RE pattern to string with optional flags. Here is the syntax
for this function-
Parameter Description
pattern This is the regular expression to be matched.
Match Object
Description
Methods
group(num=0) This method returns entire match (or specific subgroup num)
Example
#!/usr/bin/python3
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
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 the following result-
Parameter Description
pattern This is the regular expression to be matched.
Example
#!/usr/bin/python3
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print ("match --> matchObj.group() : ", matchObj.group())
else:
print ("No match!!")
searchObj = re.search( r'dogs', line, re.M|re.I)
if searchObj:
print ("search --> searchObj.group() : ", searchObj.group())
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 is provided. This method returns modified string.
Example
#!/usr/bin/python3
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print ("Phone Num : ", num)
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print ("Phone Num : ", num)
When the above code is executed, it produces the following result-
Modifier Description
re.I Performs case-insensitive matching.
re.U Interprets letters according to the Unicode character set. This flag
affects the behavior of \w, \W, \b, \B.
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 the control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match
themselves. You can escape a control character by preceding it with a backslash.
The following table lists the regular expression syntax that is available in Python-
Pattern Description
^ Matches beginning of line.
(?#...) Comment.
(?= re) Specifies position using a pattern. Does not have a range.
(?! re) Specifies position using pattern negation. Does not have a range.
\S Matches nonwhitespace.
\D Matches nondigits.
Example Description
<.*> Greedy repetition: matches "<python>perl>"
Example Description
([Pp])ython&\1ails Match python&pails or Python&Pails
Example Description
^Python Match "Python" at the start of a string or internal line
\brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not
alone
Python(?=!) Match "Python", if followed by an exclamation point.
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
• SQLite
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:
Python has an in-built support for SQLite. In this section, we would learn all the concepts
using MySQL. MySQLdb module, a popular interface with MySQL is not compatible with
Python 3. Instead, we shall use PyMySQL module.
What is PyMySQL ?
PyMySQL is an interface for connecting to a MySQL database server from Python. It
implements the Python Database API v2.0 and contains a pure-Python MySQL client library.
The goal of PyMySQL is to be a drop-in replacement for MySQLdb .
#!/usr/bin/python3
import PyMySQL
If it produces the following result, then it means MySQLdb module is not installed-
Note: Make sure you have root privilege to install the above module.
Database Connection
Before connecting to a MySQL database, make sure of the following points-
Example
Following is an example of connecting with MySQL database "TESTDB"-
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor()
method cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# disconnect from server
db.close()
INSERT Operation
The INSERT Operation 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 in the EMPLOYEE
table-
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
The above example can be written as follows to create SQL queries dynamically-
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
Example
The following code segment is another form of execution where you can pass parameters
directly-
..................................
user_id = "test123" password = "password"
Once the database connection is established, you are ready to make a query into this
database. You can use either fetchone() method to fetch a single record or
fetchall() method to fetch multiple values from a database table.
• fetchone(): It fetches the next row of a query result set. A result set is an object that
is returned when a cursor object is used to query a table.
• fetchall(): It fetches all the rows in a result set. If some rows have already been
extracted from the result set, then it retrieves the remaining rows from the result
set.
• rowcount: This is a read-only attribute and returns the number of rows that were
affected by an execute() method.
Example
The following procedure queries all the records from EMPLOYEE table having salary more
than 1000-
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results: fname = row[0] lname = row[1] age = row[2]
sex = row[3] income = row[4]
# Now print fetched result
print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \ (fname, lname, age,
sex, income ))
except:
print ("Error: unable to fecth data")
# disconnect from server
db.close()
This will produce the following result-
The following procedure updates all the records having SEX as 'M'. Here, we increase the
AGE of all the males by one year.
Example
#!/usr/bin/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
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/python3
import PyMySQL
# Open database connection
db = PyMySQL.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
Performing Transactions
Transactions are a mechanism that ensure data consistency. Transactions have the
following four properties-
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 a similar example-
db.commit()
ROLLBACK Operation
If you are not satisfied with one or more of the changes and you want to revert back those
changes completely, then use the rollback() method.
db.rollback()
Disconnecting Database
To disconnect the Database connection, use the close() method.
db.close()
If the connection to a database is closed by the user with the close() method, any
outstanding transactions are rolled back by the DB. However, instead of depending on any
of the DB lower level implementation details, your application would be better off calling
commit or rollback explicitly.
Handling Errors
There are many sources of errors. A few examples are a syntax error in an executed SQL
statement, a connection failure, or calling the fetch method for an already cancelled or
finished statement handle.
The DB API defines a number of errors that must exist in each database module. The
following table lists these exceptions.
Exception Description
Warning Used for non-fatal issues. Must subclass StandardError.
InterfaceError Used for errors in the database module, not the database itself.
Must subclass Error.
DatabaseError Used for errors in the database. Must subclass Error.
OperationalError Subclass of DatabaseError that refers to errors such as the loss ofa
connection to the database. These errors are generally outside of
the control of the Python scripter.
IntegrityError Subclass of DatabaseError for situations that would damage the
relational integrity, such as uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors internal to the
database module, such as a cursor no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table
name and other things that can safely be blamed on you.
NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported
functionality.
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.
22. Python 3 – MySQL Database (II)
Environment Setup
To build the real-world applications, connecting with the databases is the necessity for the
programming languages. However, python allows us to connect our application to the
databases like MySQL, SQLite, MongoDB, and many others.
In this section of the tutorial, we will discuss Python - MySQL connectivity, and we will
perform the database operations in python. We will also cover the Python connectivity with
the databases like MongoDB and SQLite later in this tutorial.
Install mysql.connector
To connect the python application with the MySQL database, we must import the
mysql.connector module in the program.
The mysql.connector is not a built-in module that comes with the python installation. We
need to install it to get it working.
There are the following steps to connect a python application to our database.
Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")
#printing the connection object
print(myconn)
Output:
<mysql.connector.connection.MySQLConnection object at 0x7fb142edd78
Creating a cursor object
The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It
facilitates us to have multiple separate working environments through the same connection
to the database. We can create the cursor object by calling the 'cursor' function of the
connection object. The cursor object is an important aspect of executing queries to the
databases.
<my_cur> = conn.cursor()
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google",
database = "mydb")
#printing the connection object
print(myconn)
#creating the cursor object
cur = myconn.cursor()
print(cur)
Output:
<mysql.connector.connection.MySQLConnection object at 0x7faa17a15748>
MySQLCursor: (Nothing executed yet)
Creating new databases
In this section of the tutorial, we will create the new database PythonDB.
We can create the new table by using the CREATE TABLE statement of SQL. In our database
PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and
department_id initially.
> create table Employee (name varchar(20) not null, id int primary key, salary float not
null, Dept_Id int not null)
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Creating a table with name Employee having four columns i.e., name, id, salary, and
department id
dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not
null primary key, salary float not null, Dept_id int not null)")
except:
myconn.rollback()
myconn.close()
Alter Table
Sometimes, we may forget to create some columns, or we may need to update the table
schema. The alter statement used to alter the table schema if required. Here, we will add
the column branch_name to the table Employee. The following SQL query is used for this
purpose.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#adding a column branch name to the table Employee
cur.execute("alter table Employee add branch_name varchar(20) not null")
except:
myconn.rollback()
myconn.close()
Insert Operation
Adding a record to the table
The INSERT INTO statement is used to add a record to the table. In python, we can mention
the format specifier (%s) in place of values.
We provide the actual values in the form of tuple in the execute() method of the cursor.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
#The row values are provided in the form of tuple
val = ("John", 110, 25000.00, 201, "Newyork")
try:
#inserting the values into the table
cur.execute(sql,val)
#commit the transaction
myconn.commit()
except:
myconn.rollback()
print(cur.rowcount,"record inserted!")
myconn.close()
Output:
1 record inserted!
Insert multiple rows
We can also insert multiple rows at once using the python script. The multiple rows are
mentioned as the list of various tuples.
Each element of the list is treated as one particular row, whereas each element of the tuple
is treated as one particular column value (attribute).
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
val = [("John", 102, 25000.00, 201, "Newyork"),("David",103,25000.00,202,"Port of
spain"),("Nick",104,90000.00,201,"Newyork")]
try:
#inserting the values into the table
cur.executemany(sql,val)
#commit the transaction
myconn.commit()
print(cur.rowcount,"records inserted!")
except:
myconn.rollback()
myconn.close()
Output:
3 records inserted!
Row ID
In SQL, a particular row is represented by an insertion id which is known as row id. We can
get the last inserted row id by using the attribute lastrowid of the cursor object.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
sql = "insert into Employee(name, id, salary, dept_id, branch_name) values (%s, %s,
%s, %s, %s)"
val = ("Mike",105,28000,202,"Guyana")
try:
#inserting the values into the table
cur.execute(sql,val)
#commit the transaction
myconn.commit()
#getting rowid
print(cur.rowcount,"record inserted! id:",cur.lastrowid)
except:
myconn.rollback()
myconn.close()
Output:
1 record inserted! Id: 0
Read Operation
The SELECT statement is used to read the values from the databases. We can restrict the
output of a select query by using various clause in SQL like where, limit, etc.
Python provides the fetchall() method returns the data stored inside the table in the form of
rows. We can iterate the result to get the individual rows.
In this section of the tutorial, we will extract the data from the database by using the
python script. We will also format the output to print it on the console.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select * from Employee")
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Output:
('John', 101, 25000.0, 201, 'Newyork')
('John', 102, 25000.0, 201, 'Newyork')
('David', 103, 25000.0, 202, 'Port of spain')
('Nick', 104, 90000.0, 201, 'Newyork')
('Mike', 105, 28000.0, 202, 'Guyana')
Reading specific columns
We can read the specific columns by mentioning their names instead of using star (*).
In the following example, we will read the name, id, and salary from the Employee table
and print it on the console.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
for x in result:
print(x);
except:
myconn.rollback()
myconn.close()
Output:
('John', 101, 25000.0)
('John', 102, 25000.0)
('David', 103, 25000.0)
('Nick', 104, 90000.0)
('Mike', 105, 28000.0)
The fetchone() method
The fetchone() method is used to fetch only one row from the table. The fetchone() method
returns the next row of the result-set.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
#fetching the first row from the cursor object
result = cur.fetchone()
#printing the result
print(result)
except:
myconn.rollback()
myconn.close()
Output:
('John', 101, 25000.0)
Formatting the result
We can format the result by iterating over the result produced by the fetchall() or
fetchone() method of cursor object since the result exists as the tuple object which is not
readable. Consider the following example.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee")
#fetching the rows from the cursor object
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 25000
Nick 104 90000
Mike 105 28000
Using where clause
We can restrict the result produced by the select statement by using the where clause. This
will extract only those columns which satisfy the where condition.
Example:
printing the names that start with j
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where name like 'J%'")
#fetching the rows from the cursor object
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
Example:
printing the names with id = 101, 102, and 103
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee where id in (101,102,103)")
#fetching the rows from the cursor object
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
John 101 25000
John 102 25000
David 103 2500
Ordering the result
The ORDER BY clause is used to order the result. Consider the following example.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name")
#fetching the rows from the cursor object
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
David 103 25000
John 101 25000
John 102 25000
Mike 105 28000
Nick 104 90000
Order by DESC
This orders the result in the decreasing order of a particular column.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Reading the Employee data
cur.execute("select name, id, salary from Employee order by name desc")
#fetching the rows from the cursor object
result = cur.fetchall()
#printing the result
print("Name id Salary");
for row in result:
print("%s %d %d"%(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Output:
Name id Salary
Nick 104 90000
Mike 105 28000
John 101 25000
John 102 25000
David 103 25000
Update Operation
The UPDATE-SET statement is used to update any column inside the table. The following
SQL query is used to update a column.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#updating the name of the employee whose id is 110
cur.execute("update Employee set name = 'alex' where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Delete Operation
The DELETE FROM statement is used to delete a specific record from the table. Here, we
must impose a condition using WHERE clause otherwise all the records from the table will be
removed.
The following SQL query is used to delete the employee detail whose id is 110 from the
table.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#Deleting the employee details whose id is 110
cur.execute("delete from Employee where id = 110")
myconn.commit()
except:
myconn.rollback()
myconn.close()
Join Operation
We can combine the columns from two or more tables by using some common column
among them by using the join statement.
We have only one table in our database, let's create one more table Departments with two
columns department_id and department_name.
create table Departments (Dept_id int(20) primary key not null, Dept_Name varchar(20)
not null);
As we have created a new table Departments as shown in the above image. However, we
haven't yet inserted any value inside it.
Let's insert some Departments ids and departments names so that we can map this to our
Employee table.
Now, let's create a python script that joins the two tables on the common column, i.e.,
dept_id.
Example
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google",database = "PythonDB")
#creating the cursor object
cur = myconn.cursor()
try:
#joining the two tables on departments_id
cur.execute("select Employee.id, Employee.name, Employee.salary,
Departments.Dept_id, Departments.Dept_Name from Departments join Employee on
Departments.Dept_id = Employee.Dept_id")
print("ID Name Salary Dept_Id Dept_Name")
for row in cur:
print("%d %s %d %d %s"%(row[0], row[1],row[2],row[3],row[4]))
except:
myconn.rollback()
myconn.close()
Output:
ID Name Salary Dept_Id Dept_Name
101 John 25000 201 CS
102 John 25000 201 CS
103 David 25000 202 IT
104 Nick 90000 201 CS
105 Mike 28000 202 IT
23. Python 3 – Sending Mail (SMTP)
Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending an e-mail and
routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object that can be
used to send mails to any Internet machine with an SMTP or ESMTP listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to send an e-
mail-
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Here is the detail of the parameters-
• host: This is the host running your SMTP server. You can specifiy IP address of the
host or a domain name like tutorialspoint.com. This is an optional argument.
• port: If you are providing host argument, then you need to specify a port, where
SMTP server is listening. Usually this port would be 25.
• local_hostname: If your SMTP server is running on your local machine, then you can
specify just localhost as the option.
An SMTP object has an instance method called sendmail, which is typically, used to do the
work of mailing a message. It takes three parameters-
Example
Here is a simple way to send one e-mail using Python script. Try it once-
#!/usr/bin/python3
import smtplib
sender='from@fromdomain.com'
receivers =['to@todomain.com']
Here, you have placed a basic e-mail in message, using a triple quote, taking care to format
the headers correctly. An e-mail requires a From, To, and a Subject header, separated from
the body of the e-mail with a blank line.
To send the mail you use smtpObj to connect to the SMTP server on the local machine.
Then use the sendmail method along with the message, the from address, and the
destination address as parameters (even though the from and to addresses are within the
e-mail itself, these are not always used to route the mail).
If you are not running an SMTP server on your local machine, you can the usesmtplib client
to communicate with a remote SMTP server. Unless you are using a webmail service (such
as gmail or Yahoo! Mail), your e-mail provider must have provided you with the outgoing
mail server details that you can supply them, as follows-
mail=smtplib.SMTP('smtp.gmail.com', 587)
Sending an HTML e-mail using Python
When you send a text message using Python, then all the content is treated as simple text.
Even if you include HTML tags in a text message, it is displayed as simple text and HTML
tags will not be formatted according to the HTML syntax. However, Python provides an
option to send an HTML message as actual HTML message.
While sending an e-mail message, you can specify a Mime version, content type and the
character set to send an HTML e-mail.
Example
Following is an example to send the HTML content as an e-mail. Try it once-
import smtplib
sender_mail = 'Senders Mail'
receivers_mail = ‘Receivers Mail’
message = """From: Sender %s
To: Receiver %s
Subject: Sending SMTP e-mail
This is a test e-mail message."""%(sender_mail,receivers_mail)
try:
password = input('Enter the password');
smtpObj = smtplib.SMTP('smtp.gmail.com',587)
smtpObj.starttls()
smtpObj.login(sender_mail,password)
smtpObj.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
24. Python 3 – Multithreaded Programming
Running several threads is similar to running several different programs concurrently, but
with the following benefits-
• Multiple threads within a process share the same data space with the main thread
and can therefore share information or communicate with each other more easily
than if they were separate processes.
• Threads are sometimes called light-weight processes and they do not require much
memory overhead; they are cheaper than processes.
• kernel thread
• user thread
Kernel Threads are a part of the operating system, while the User-space threads are not
implemented in the kernel.
There are two modules, which support the usage of threads in Python3-
• _thread
• threading
The thread module has been "deprecated" for quite a long time. Users are encouraged to
use the threading module instead. Hence, in Python 3, the module "thread" is not available
anymore. However, it has been renamed to "_thread" for backward compatibilities in
Python3.
module-
The method call returns immediately and the child thread starts and calls function with the
passed list of agrs. When the function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any
arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python3
import _thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
# Create two threads as follows
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")
while 1:
pass
When the above code is executed, it produces the following result-
Although it is very effective for low-level threading, the thread module is very limited
compared to the newer threading module.
The threading module exposes all the methods of the thread module and provides some
additional methods:
In addition to the methods, the threading module has the Thread class that implements
threading. The methods provided by the Thread class are as follows:
Once you have created the new Thread subclass, you can create an instance of it and then
start a new thread by invoking the start(), which in turn calls the run()method.
Example
#!/usr/bin/python3
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__ (self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")
When we run the above program, it produces the following result-
Starting Thread-1
Starting Thread-2
Thread-1: Fri Feb 19 10:00:23 2016
Thread-2: Fri Feb 19 10:00:24 2016
Thread-1: Fri Feb 19 10:00:24 2016
Thread-1: Fri Feb 19 10:00:25 2016
Exiting Thread-1
Thread-2: Fri Feb 19 10:00:26 2016
Thread-2: Fri Feb 19 10:00:28 2016
Thread-2: Fri Feb 19 10:00:30 2016
Exiting Thread-2
Exiting Main Thread
Synchronizing Threads
The threading module provided with Python includes a simple-to-implement locking
mechanism that allows you to synchronize threads. A new lock is created by calling the
Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force the threads to run
synchronously. The optional blocking parameter enables you to control whether the thread
waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be
acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and
wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer
required.
Example
#!/usr/bin/python3
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__ (self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
When the above code is executed, it produces the following result-
Starting Thread-1
Starting Thread-2
Thread-1: Fri Feb 19 10:04:14 2016
Thread-1: Fri Feb 19 10:04:15 2016
Thread-1: Fri Feb 19 10:04:16 2016
Thread-2: Fri Feb 19 10:04:18 2016
Thread-2: Fri Feb 19 10:04:20 2016
Thread-2: Fri Feb 19 10:04:22 2016
Exiting Main Thread
Multithreaded Priority Queue
The Queue module allows you to create a new queue object that can hold a specific number
of items. There are following methods to control the Queue −
• get(): The get() removes and returns an item from the queue.
• put(): The put adds item to a queue.
• qsize() : The qsize() returns the number of items that are currently in the queue.
• empty(): The empty( ) returns True if queue is empty; otherwise, False.
• full(): the full() returns True if queue is full; otherwise, False.
Example
#!/usr/bin/python3
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print ("Starting " + self.name)
process_data(self.name, self.q)
print ("Exiting " + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
Starting Thread-1
Starting Thread-2
Starting Thread-3
25. Python 3 – GUI Programming (Tkinter)
Python provides various options for developing graphical user interfaces (GUIs). The most
important features are listed below.
• Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We
would look at this option in this chapter.
• wxPython: This is an open-source Python interface for wxWidgets GUI toolkit. You
can find a complete tutorial on WxPython here.
• PyQt:This is also a Python interface for a popular cross-platform Qt GUI library.
TutorialsPoint has a very good tutorial on PyQt here.
• JPython: JPython is a Python port for Java, which gives Python scripts seamless
access to the Java class libraries on the local machinehttp://www.jython.org.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides
a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the
following steps −
Example
#!/usr/bin/python3
import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter
in Python 3
top = tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
This would create a following window-
Geometry Management
All Tkinter widgets have access to the 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.
Syntax
widget.pack( pack_options )
Here is the list of possible 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 (default), X (fill only horizontally), Y (fill
only vertically), or BOTH (fill both horizontally and vertically).
• side: Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
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()
When the above code is executed, it produces the following result-
Syntax
widget.grid( grid_options )
Here is the list of possible options-
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
root = Tk( )
b=0
for r in range(6):
for c in range(6):
b=b+1
Button(root, text=str(b), borderwidth=1 ).grid(row=r,column=c)
root.mainloop()
This would produce the following result displaying 12 labels arrayed in a 3 x 4 grid-
Tkinter place() Method
This geometry manager organizes widgets by placing them in a specific position in the
parent widget.
Syntax
widget.place( place_options )
Here is the list of possible 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 (the upper left corner of widget)
• bordermode : INSIDE (the default) to indicate that other options refer to the parent's
inside (ignoring the parent's border); 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
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
top = Tk()
L1 = Label(top, text="Physics")
L1.place(x=10,y=10)
E1 = Entry(top, bd =5)
E1.place(x=60,y=10)
L2=Label(top,text="Maths")
L2.place(x=10,y=50)
E2=Entry(top,bd=5)
E2.place(x=60,y=50)
L3=Label(top,text="Total")
L3.place(x=10,y=150)
E3=Entry(top,bd=5)
E3.place(x=60,y=150)
B = Button(top, text ="Add")
B.place(x=100, y=100)
top.geometry("250x250+10+10")
top.mainloop()
When the above code is executed, it produces the following result-
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-
Operator Description
The Button widget is used to display the buttons in your
Button
application.
The Canvas widget is used to draw shapes, such as lines,
Canvas
ovals, polygons and rectangles, in your application.
The Checkbutton widget is used to display a number of
Checkbutton options as checkboxes. The user can select multiple
options at a time.
The Entry widget is used to display a single-line text field
Entry
for accepting values from a user.
The Frame widget is used as a container widget to
Frame
organize other widgets.
The Label widget is used to provide a single-line caption
Label
for other widgets. It can also contain images.
The Listbox widget is used to provide a list of options toa
Listbox
user.
The Menubutton widget is used to display menus in your
Menubutton
application.
The Menu widget is used to provide various commands to
Menu a user. These commands are contained inside
Menubutton.
The Message widget is used to display multiline text fields
Message
for accepting values from a user.
Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can display
text or images that convey the purpose of the buttons. You can attach a function or a
method to a button which is called automatically when you click the button.
Syntax
Here is the simple syntax to create this widget-
Parameters
• master: This represents the parent window.
• options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
activebackground Background color when the button is under the cursor.
highlightcolor The color of the focus highlight when the widget has focus.
Relief specifies the type of the border. Some of the values are
relief
SUNKEN, RAISED, GROOVE, and RIDGE.
Set this option to DISABLED to gray out the button and make it
state unresponsive. Has the value ACTIVE when the mouse is over it.
Default is NORMAL.
Default is -1, meaning that no character of the text on the button
underline will be underlined. If nonnegative, the corresponding text
character will be underlined.
Width of the button in letters (if displaying text) or pixels (if
width
displaying an image).
If this value is set to a positive number, the text lines will be
wraplength
wrapped to fit within this length.
Methods
Following are commonly used methods for this widget-
Method Description
Causes the button to flash several times between active and normal
flash() colors. Leaves the button in the state it was in originally. Ignored if the
button is disabled.
Calls the button's callback, and returns what that function returns. Hasno
invoke()
effect if the button is disabled or there is no callback.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def helloCallBack():
msg=messagebox.showinfo( "Hello Python", "Hello World")
B = Button(top, text ="Hello", command = helloCallBack)
B.place(x=50,y=50)
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Canvas
The Canvas is a rectangular area intended for drawing pictures or other complex layouts.
You can place graphics, text, widgets or frames on a Canvas.
Syntax
Here is the simple syntax to create this widget-
Parameters
• master: This represents the parent window.
• options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
bd Border width in pixels. Default is 2.
cursor Cursor used in the canvas like arrow, circle, dot etc.
Relief specifies the type of the border. Some of the values are
relief
SUNKEN, RAISED, GROOVE, and RIDGE.
A tuple (w, n, e, s) that defines over how large an area the canvas
scrollregion can be scrolled, where w is the left side, n the top, e the right side,
and s the bottom.
If you set this option to some positive dimension, the canvas can be
xscrollincrement positioned only on multiples of that distance, and the value will be
used for scrolling by scrolling units, such as when the user clicks on
the arrows at the ends of a scrollbar.
arc . Creates an arc item, which can be a chord, a pieslice or a simple arc.
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
C = Canvas(top, bg="blue", height=250, width=300)
coord = 10, 50, 240, 210
arc = C.create_arc(coord, start=0, extent=150, fill="red") line =
C.create_line(10,10,200,200,fill='white')
C.pack()
Top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Checkbutton
The Checkbutton widget is used to display a number of options to a user as toggle buttons.
The user can then select one or more options by clicking the button corresponding to each
option.
Syntax
Here is the simple syntax to create this widget-
Option Description
activebackground Background color when the checkbutton is under the cursor.
The color of the focus highlight when the checkbutton has the
highlightcolor
focus.
If the text contains multiple lines, this option controls how the
justify
text is justified: CENTER, LEFT, or RIGHT.
Normally, a checkbutton's associated control variable will be set to
offvalue 0 when it is cleared (off). You can supply an alternate value forthe
off state by setting offvalue to that value.
Normally, a checkbutton's associated control variable will be set to
onvalue 1 when it is set (on). You can supply an alternate value for theon
state by setting onvalue to that value.
How much space to leave to the left and right of the checkbutton
padx
and text. Default is 1 pixel.
How much space to leave above and below the checkbutton and
pady
text. Default is 1 pixel.
With the default value, relief=FLAT, the checkbutton does not
relief stand out from its background. You may set this option to any of
the other styles
The color of the checkbutton when it is set. Default is
selectcolor
selectcolor="red".
If you set this option to an image, that image will appear in the
selectimage
checkbutton when it is set.
The default is state=NORMAL, but you can use state=DISABLED to
state gray out the control and make it unresponsive. If the cursor is
currently over the checkbutton, the state is ACTIVE.
The label displayed next to the checkbutton. Use newlines ("\n")to
text
display multiple lines of text.
With the default value of -1, none of the characters of the text
underline label are underlined. Set this option to the index of a character in
the text (counting from zero) to underline that character.
The control variable that tracks the current state of the
checkbutton. Normally this variable is an IntVar, and 0 means
variable
cleared and 1 means set, but see the offvalue and onvalue options
above.
The default width of a checkbutton is determined by the size of the
displayed image or text. You can set this option to a number of
width
characters and the checkbutton will always have room for that
many characters.
Normally, lines are not wrapped. You can set this option to a
wraplength number of characters and all lines will be broken into pieces no
longer than that number.
Methods
Following are commonly used methods for this widget-
Method Description
deselect() Clears (turns off) the checkbutton.
Flashes the checkbutton a few times between its active and normal
flash()
colors, but leaves it the way it started.
You can call this method to get the same actions that would occur if
invoke()
the user clicked on the checkbutton to change its state.
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0,
height=5, width = 20, )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2, onvalue = 1, offvalue = 0,
height=5, width = 20)
C1.pack()
C2.pack()
top.mainloop()
When the above code is executed, it produces the following result –
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
• If you want to display multiple lines of text that can be edited, then you should use
the Text widget.
• If you want to display one or more lines of text that cannot be modified by the user,
then you should use the Label widget.
Syntax
Here is the simple syntax to create this widget-
Parameters
• master: This represents the parent window.
• options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Option Description
bg The normal background color displayed behind the label andindicator.
command A procedure to be called every time the user changes the state ofthis
checkbutton.
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
font The font used for the text.
highlightcolor The color of the focus highlight when the checkbutton has the
focus.
justify If the text contains multiple lines, this option controls how the textis
justified: CENTER, LEFT, or RIGHT.
relief With the default value, relief=FLAT, the checkbutton does not stand
out from its background. You may set this option to any of the other
styles
selectbackground The background color to use displaying selected text.
selectborderwidth The width of the border to use around selected text. The default isone
pixel.
selectforeground The foreground (text) color of selected text.
show Normally, the characters that the user types appear in the entry. To
make a .password. entry that echoes each character as an asterisk,
set show="*".
state The default is state=NORMAL, but you can use state=DISABLED to
gray out the control and make it unresponsive. If the cursor is
currently over the checkbutton, the state is ACTIVE.
textvariable In order to be able to retrieve the current text from your entry
widget, you must set this option to an instance of the StringVar class.
width The default width of a checkbutton is determined by the size of the
displayed image or text. You can set this option to a number of
characters and the checkbutton will always have room for that many
characters.
xscrollcommand If you expect that users will often enter more text than the onscreen
size of the widget, you can link your entry widget to a scrollbar.
Methods
Following are commonly used methods for this widget-
Method Description
delete ( first, last=None ) Deletes characters from the widget, starting withthe
one at index first, up to but not including the
character at position last. If the second argument is
omitted, only the single character at position first is
deleted.
get() Returns the entry's current text as a string.
icursor ( index ) Set the insertion cursor just before the characterat
the given index.
index ( index ) Shift the contents of the entry so that the character
at the given index is the leftmost visiblecharacter.
Has no effect if the text fits entirely within the entry.
insert ( index, s ) Inserts string s before the character at the given
index.
select_adjust ( index ) This method is used to make sure that the selection
includes the character at the specifiedindex.
select_clear() Clears the selection. If there isn't currently a
selection, has no effect.
select_from ( index ) Sets the ANCHOR index position to the
characterselected by index, and selects that
character.
select_present() If there is a selection, returns true, else returns
false.
select_range ( start, end ) Sets the selection under program control.
Selects the text starting at the start index, up
to but not including the character at the end
index. The startposition must be before the end
position.
select_to ( index ) Selects all the text from the ANCHOR position
upto but not including the character at the
given index.
xview ( index ) This method is useful in linking the Entry widget
toa horizontal scrollbar.
xview_scroll ( number, what ) Used to scroll the entry horizontally. The what
argument must be either UNITS, to scroll by
character widths, or PAGES, to scroll by chunks
the size of the entry widget. The number is
positive to scroll left to right, negative to scroll
right to left.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Frame
The Frame widget is very important for the process of grouping and organizing other
widgets in a somehow friendly way. It works like a container, which is responsible for
arranging the position of other widgets.
It uses rectangular areas in the screen to organize the layout and to provide padding of
these widgets. A frame can also be used as a foundation class to implement complex
widgets.
Syntax
Here is the simple syntax to create this widget-
Options Description
cursor If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor will change to that pattern when it is over the checkbutton.
height The vertical dimension of the new frame.
highlightbackground Color of the focus highlight when the frame does not have focus.
highlightcolor Color shown in the focus highlight when the frame has the focus.
Relief With the default value, relief=FLAT, the checkbutton does not stand
out from its background. You may set this option to any of the
other styles
Width The default width of a checkbutton is determined by the size of the
displayed image or text. You can set this option to a numberof
characters and the checkbutton will always have room for that
many characters.
Example
Try the following example yourself-
# !/usr/bin/python3
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()
When the above code is executed, it produces the following result-
Tkinter Label
This widget implements a display box where you can place text or images. The text
displayed by this widget can be updated at any time you want.
It is also possible to underline part of the text (like to identify a keyboard shortcut) and
span the text across multiple lines.
Syntax
Here is the simple syntax to create this widget-
bg The normal background color displayed behind the label and indicator.
Set this option equal to a bitmap or image object and the label will
bitmap
display that graphic.
If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor
cursor will change to that pattern when it is over the checkbutton.
If you are displaying text in this label (with the text or textvariable
font
option, the font option specifies in what font that text will be displayed.
If you are displaying text or a bitmap in this label, this option specifiesthe
fg color of the text. If you are displaying a bitmap, this is the color that will
appear at the position of the 1-bits in the bitmap.
Specifies how multiple lines of text will be aligned with respect to each
justify other: LEFT for flush left, CENTER for centered (the default), or RIGHTfor
right-justified.
Extra space added to the left and right of the text within the widget.
padx
Default is 1.
pady Extra space added above and below the text within the widget. Defaultis 1.
To display one or more lines of text in a label widget, set this option to a
text
string containing the text. Internal newlines ("\n") will force a linebreak.
You can display an underline (_) below the nth letter of the text, counting
underline from 0, by setting this option to n. The default is underline=-1, which
means no underlining.
Width of the label in characters (not pixels!). If this option is not set,the
width
label will be sized to fit its contents.
You can limit the number of characters in each line by setting this option
wraplength to the desired number. The default value, 0, means that lines will be
broken only at newlines.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Listbox
The Listbox widget is used to display a list of items from which a user can select a number
of items
Syntax
Here is the simple syntax to create this widget-
Parameters
• master: This represents the parent window.
• options: Here is the list of most commonly used options for this widget. These
options can be used as key-value pairs separated by commas.
Options Description
The normal background color displayed behind the label and
bg
indicator.
cursor The cursor that appears when the mouse is over the listbox.
height Number of lines (not pixels!) shown in the listbox. Default is10.
Color shown in the focus highlight when the widget has the
highlightcolor
focus.
Options Description
activate ( index ) Selects the line specifies by the given index.
curselection() Returns a tuple containing the line numbers of the selected
element or elements, counting from 0. Ifnothing is selected,
returns an empty tuple.
delete ( first, last=None ) Deletes the lines whose indices are in the range [first, last].
If the second argument is omitted, the single linewith index
first is deleted.
get ( first, last=None ) Returns a tuple containing the text of the lines with indices
from first to last, inclusive. If the second argument is
omitted, returns the text of the line closestto first.
index ( i ) If possible, positions the visible part of the listbox so that
the line containing index i is at the top of the widget.
insert ( index, *elements ) Insert one or more new lines into the listbox before theline
specified by index. Use END as the first argument if you
want to add new lines to the end of the listbox.
nearest ( y ) Return the index of the visible line closest to the y-
coordinate y relative to the listbox widget.
see ( index ) Adjust the position of the listbox so that the linereferred to
by index is visible.
size() Returns the number of lines in the listbox.
xview() To make the listbox horizontally scrollable, set the
command option of the associated horizontal scrollbar to
this method.
xview_moveto ( fraction ) Scroll the listbox so that the leftmost fraction of the width
of its longest line is outside the left side of the listbox.
Fraction is in the range [0,1].
xview_scroll ( number, what ) Scrolls the listbox horizontally. For the what argument,use
either UNITS to scroll by characters, or PAGES to scroll by
pages, that is, by the width of the listbox. Thenumber
argument tells how many to scroll.
yview() To make the listbox vertically scrollable, set the command
option of the associated vertical scrollbar to this method.
yview_moveto ( fraction ) Scroll the listbox so that the top fraction of the width ofits
longest line is outside the left side of the listbox. Fraction is
in the range [0,1].
yview_scroll ( number, what ) Scrolls the listbox vertically. For the what argument, use
either UNITS to scroll by lines, or PAGES to scroll by pages,
that is, by the height of the listbox. The number argument
tells how many to scroll.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Menubutton
A menubutton is the part of a drop-down menu that stays on the screen all the time. Every
menubutton is associated with a Menu widget that can display the choices for that
menubutton when the user clicks on it.
Syntax
Here is the simple syntax to create this widget-
Options Description
activebackground The background color when the mouse is over the menubutton.
activeforeground The foreground color when the mouse is over the menubutton.
This options controls where the text is positioned if the widget has
anchor more space than the text needs. The default is anchor=CENTER,
which centers the text.
The normal background color displayed behind the label and
bg
indicator.
To display a bitmap on the menubutton, set this option to a
bitmap
bitmap name.
bd The size of the border around the indicator. Default is 2 pixels.
cursor The cursor that appears when the mouse is over this menubutton.
Set direction=LEFT to display the menu to the left of the button; use
direction direction=RIGHT to display the menu to the right of the button; or
use direction='above' to place the menu above the button.
disabledforeground The foreground color shown on this menubutton when it isdisabled.
The foreground color when the mouse is not over the
fg
menubutton.
The height of the menubutton in lines of text (not pixels!). The
height
default is to fit the menubutton's size to its contents.
highlightcolor Color shown in the focus highlight when the widget has the focus.
image To display an image on this menubutton,
This option controls where the text is located when the text doesn't
fill the menubutton: use justify=LEFT to left-justify the text (this is
justify
the default); use justify=CENTER to center it, or justify=RIGHT to
right-justify.
menu To associate the menubutton with a set of choices, set this optionto
the Menu object containing those choices. That menu object must
have been created by passing the associated menubutton to the
constructor as its first argument.
How much space to leave to the left and right of the text of the
padx
menubutton. Default is 1.
How much space to leave above and below the text of the
pady
menubutton. Default is 1.
Selects three-dimensional border shading effects. The default is
relief
RAISED.
Normally, menubuttons respond to the mouse. Set state=DISABLED
state
to gray out the menubutton and make it unresponsive.
To display text on the menubutton, set this option to the string
text containing the desired text. Newlines ("\n") within the string will
cause line breaks.
You can associate a control variable of class StringVar with this
textvariable menubutton. Setting that control variable will change the displayed
text.
Normally, no underline appears under the text on themenubutton. To
underline underline one of the characters, set this option to the index of that
character.
width The width of the widget in characters. The default is 20.
Normally, lines are not wrapped. You can set this option to a number
wraplength of characters and all lines will be broken into pieces no longer than
that number.
Example
Try the following example yourself-
# !/usr/bin/python3
From tkinter import *
import tkinter
top = Tk()
mb= Menubutton ( top, text="condiments", relief=RAISED )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mayoVar = IntVar() ketchVar = IntVar()
mb.menu.add_checkbutton ( label="mayo", variable=mayoVar )
mb.menu.add_checkbutton ( label="ketchup", variable=ketchVar )
mb.pack()
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Menu
The goal of this widget is to allow us to create all kinds of menus that can be used by our
applications. The core functionality provides ways to create three menu types: pop-up,
toplevel and pull-down.
It is also possible to use other extended widgets to implement new types of menus, such as
the OptionMenu widget, which implements a special type that generates a pop-up list of
items within a selection.
Syntax
Here is the simple syntax to create this widget-
Options Description
The background color that will appear on a choice when it is underthe
activebackground
mouse.
Specifies the width of a border drawn around a choice when it isunder
activeborderwidth
the mouse. Default is 1 pixel.
The foreground color that will appear on a choice when it is underthe
activeforeground
mouse.
bg The background color for choices not under the mouse.
bd The width of the border around all the choices. Default is 1.
The cursor that appears when the mouse is over the choices, butonly
cursor
when the menu has been torn off.
disabledforeground The color of the text for items whose state is DISABLED.
font The default font for textual choices.
fg The foreground color used for choices not under the mouse.
You can set this option to a procedure, and that procedure will becalled
postcommand
every time someone brings up this menu.
relief The default 3-D effect for menus is relief=RAISED.
image To display an image on this menubutton.
Specifies the color displayed in checkbuttons and radiobuttonswhen
selectcolor
they are selected.
Normally, a menu can be torn off, the first position (position 0) inthe
list of choices is occupied by the tear-off element, and the additional
tearoff choices are added starting at position 1. If you set tearoff=0, the
menu will not have a tear-off feature, and choiceswill be added starting
at position 0.
Normally, the title of a tear-off menu window will be the same as the
title text of the menubutton or cascade that lead to this menu. If you want
to change the title of that window, set the title option tothat string.
Methods
These methods are available on Menu objects-
Option Description
add_command (options) Adds a menu item to the menu.
add_radiobutton( options ) Creates a radio button menu item.
add_checkbutton( options ) Creates a check button menu item.
Creates a new hierarchical menu by associating a
add_cascade(options)
given menu to a parent menu
add_separator() Adds a separator line to the menu.
add( type, options ) Adds a specific type of menu item to the menu.
Deletes the menu items ranging from startindex to
delete( startindex [, endindex ])
endindex.
Allows you to modify a menu item, which is identifiedby
entryconfig( index, options )
the index, and change its options.
Returns the index number of the given menu item
index(item)
label.
Insert a new separator at the position specified by
insert_separator ( index )
index.
Calls the command callback associated with the choice
at position index. If a checkbutton, its state istoggled
invoke ( index )
between set and cleared; if a radiobutton, that choice is
set.
Returns the type of the choice specified by index: either
type ( index ) "cascade", "checkbutton", "command", "radiobutton",
"separator", or "tearoff".
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
def donothing():
filewin = Toplevel(root)
button = Button(filewin, text="Do nothing button")
button.pack()
root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_command(label="Save", command=donothing)
filemenu.add_command(label="Save as...", command=donothing)
filemenu.add_command(label="Close", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_separator()
editmenu.add_command(label="Cut", command=donothing)
editmenu.add_command(label="Copy", command=donothing)
editmenu.add_command(label="Paste", command=donothing)
editmenu.add_command(label="Delete", command=donothing)
editmenu.add_command(label="Select All", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Message
This widget provides a multiline and noneditable object that displays texts, automatically
breaking lines and justifying their contents.
Its functionality is very similar to the one provided by the Label widget, except that it can
also automatically wrap the text, maintaining a given width or aspect ratio.
Syntax
Here is the simple syntax to create this widget-
# !/usr/bin/python3
from tkinter import *
root = Tk()
var = StringVar()
label = Message( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Radiobutton
This widget implements a multiple-choice button, which is a way to offer many possible
selections to the user and lets user choose only one of them.
Syntax
Here is the simple syntax to create this widget-
Options Description
activebackground The background color when the mouse is over the radiobutton.
activeforeground The foreground color when the mouse is over the radiobutton.
If the widget inhabits a space larger than it needs, this option
anchor specifies where the radiobutton will sit in that space. The defaultis
anchor=CENTER.
bg The normal background color behind the indicator and label.
To display a monochrome image on a radiobutton, set this
bitmap
option to a bitmap.
The size of the border around the indicator part itself. Default is2
borderwidth
pixels.
A procedure to be called every time the user changes the stateof
command
this radiobutton.
If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor
cursor will change to that pattern when it is over the radiobutton.
font The font used for the text.
fg The color used to render the text.
The number of lines (not pixels) of text on the radiobutton.
height
Default is 1.
The color of the focus highlight when the radiobutton does nothave
highlightbackground
focus.
The color of the focus highlight when the radiobutton has the
highlightcolor
focus.
To display a graphic image instead of text for this radiobutton,set
image
this option to an image object.
If the text contains multiple lines, this option controls how thetext
justify
is justified: CENTER (the default), LEFT, or RIGHT.
How much space to leave to the left and right of the radiobuttonand
padx
text. Default is 1.
How much space to leave above and below the radiobutton andtext.
pady
Default is 1.
Specifies the appearance of a decorative border around thelabel.
relief
The default is FLAT; for other values.
selectcolor The color of the radiobutton when it is set. Default is red.
If you are using the image option to display a graphic instead oftext
when the radiobutton is cleared, you can set the selectimage option
selectimage
to a different image that will be displayed when the radiobutton is
set.
The default is state=NORMAL, but you can set state=DISABLEDto
state gray out the control and make it unresponsive. If the cursor is
currently over the radiobutton, the state is ACTIVE.
The label displayed next to the radiobutton. Use newlines ("\n")to
text
display multiple lines of text.
To slave the text displayed in a label widget to a control variableof
textvariable
class StringVar, set this option to that variable.
You can display an underline (_) below the nth letter of the text,
underline counting from 0, by setting this option to n. The default is
underline=-1, which means no underlining.
When a radiobutton is turned on by the user, its control variableis
set to its current value option. If the control variable isan
value IntVar, give each radiobutton in the group a different integervalue
option. If the control variable is aStringVar, give each radiobutton a
different string value option.
variable The control variable that this radiobutton shares with the other
radiobuttons in the group. This can be either an IntVar or a
StringVar.
Width of the label in characters (not pixels!). If this option is notset,
width
the label will be sized to fit its contents.
You can limit the number of characters in each line by setting this
wraplength option to the desired number. The default value, 0, means that lines
will be broken only at newlines.
Methods
These methods are available.
Methods Description
deselect() Clears (turns off) the radiobutton.
Flashes the radiobutton a few times between its active and normal
flash()
colors, but leaves it the way it started.
You can call this method to get the same actions that would occur ifthe
invoke()
user clicked on the radiobutton to change its state.
select() Sets (turns on) the radiobutton.
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
def sel():
selection = "You selected the option " + str(var.get())
label.config(text = selection)
root = Tk()
var = IntVar()
R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel)
R1.pack( anchor = W )
R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel)
R2.pack( anchor = W )
R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel)
R3.pack( anchor = W)
label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Scale
The Scale widget provides a graphical slider object that allows you to select values from a
specific scale.
Syntax
Here is the simple syntax to create this widget-
Options Description
activebackground The background color when the mouse is over the scale.
The background color of the parts of the widget that are outsidethe
bg
trough.
Width of the 3-d border around the trough and slider. Default is2
bd
pixels.
A procedure to be called every time the slider is moved. This
procedure will be passed one argument, the new scale value. Ifthe
command
slider is moved rapidly, you may not get a callback for everypossible
position, but you'll certainly get a callback when it settles.
If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor
cursor will change to that pattern when it is over the scale.
The way your program reads the current value shown in a scale
widget is through a control variable. The control variable for a scale
digits can be an IntVar, a DoubleVar (float), or a StringVar. If itis a string
variable, the digits option controls how many digits to use when
the numeric scale value is converted to a string.
font The font used for the label and annotations.
fg The color of the text used for the label and annotations.
from_ A float or integer value that defines one end of the scale's range.
The color of the focus highlight when the scale does not have
highlightbackground
focus.
highlightcolor The color of the focus highlight when the scale has the focus.
You can display a label within the scale widget by setting this option
to the label's text. The label appears in the top left cornerif the scale
label
is horizontal, or the top right corner if vertical. The default is no
label.
The length of the scale widget. This is the x dimension if the scale
length
is horizontal, or the y dimension if vertical. The default is 100 pixels.
Set orient=HORIZONTAL if you want the scale to run along the x
orient dimension, or orient=VERTICAL to run parallel to the y-axis.
Default is horizontal.
Specifies the appearance of a decorative border around the
relief
label. The default is FLAT; for other values.
This option controls how long button 1 has to be held down in the
repeatdelay trough before the slider starts moving in that direction repeatedly.
Default is repeatdelay=300, and the units are milliseconds.
Normally, the user will only be able to change the scale in whole
units. Set this option to some other value to change the smallest
resolution increment of the scale's value. For example, if from_=-1.0 and
to=1.0, and you set resolution=0.5, the scale will have 5 possible
values: -1.0, -0.5, 0.0, +0.5, and +1.0.
Normally, the current value of the scale is displayed in text formby
showvalue the slider (above it for horizontal scales, to the left for vertical scales).
Set this option to 0 to suppress that label.
Normally the slider is 30 pixels along the length of the scale. You
sliderlength can change that length by setting the sliderlength option to your
desired length.
Normally, scale widgets respond to mouse events, and when they
state have the focus, also keyboard events. Set state=DISABLEDto make
the widget unresponsive.
Normally, the focus will cycle through scale widgets. Set this
takefocus
option to 0 if you don't want this behavior.
To display periodic scale values, set this option to a number, and
ticks will be displayed on multiples of that value. For example, if
from_=0.0, to=1.0, and tickinterval=0.25, labels will be displayed
tickinterval
along the scale at values 0.0, 0.25, 0.50, 0.75, and 1.00. These
labels appear below the scale if horizontal, to its left if vertical.
Default is 0, which suppresses display of ticks.
A float or integer value that defines one end of the scale's range;the
other end is defined by the from_ option, discussed above. The to
to value can be either greater than or less than the from_ value. For
vertical scales, the to value defines the bottom of the scale; for
horizontal scales, the right end.
troughcolor The color of the trough.
The control variable for this scale, if any. Control variables maybe
variable from class IntVar, DoubleVar (float), or StringVar. In the latter
case, the numerical value will be converted to a string.
The width of the trough part of the widget. This is the x dimension
width for vertical scales and the y dimension if the scale has
orient=HORIZONTAL. Default is 15 pixels.
Methods
Scale objects have these methods-
Methods Description
# !/usr/bin/python3
from tkinter import *
def sel():
selection = "Value = " + str(var.get())
label.config(text = selection)
root = Tk()
var = DoubleVar()
scale = Scale( root, variable = var )
scale.pack(anchor=CENTER)
button = Button(root, text="Get Scale Value", command=sel)
button.pack(anchor=CENTER)
label = Label(root)
label.pack()
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Scrollbar
This widget provides a slide controller that is used to implement vertical scrolled widgets,
such as Listbox, Text and Canvas. Note that you can also create horizontal scrollbars on
Entry widgets.
Syntax
Here is the simple syntax to create this widget-
Options Description
The color of the slider and arrowheads when the mouse is over
activebackground
them.
The color of the slider and arrowheads when the mouse is notover
bg
them.
The width of the 3-d borders around the entire perimeter of the
trough, and also the width of the 3-d effects on the arrowheadsand
bd
slider. Default is no border around the trough, and a 2-pixelborder
around the arrowheads and slider.
command A procedure to be called whenever the scrollbar is moved.
cursor The cursor that appears when the mouse is over the scrollbar.
The width of the borders around the arrowheads and slider. The
elementborderwidth default is elementborderwidth=-1, which means to use the value of
the borderwidth option.
The color of the focus highlight when the scrollbar does not have
highlightbackground
focus.
highlightcolor The color of the focus highlight when the scrollbar has the focus.
The thickness of the focus highlight. Default is 1. Set to 0 to
highlightthickness
suppress display of the focus highlight.
This option controls what happens when a user drags the slider.
Normally (jump=0), every small drag of the slider causes the
jump
command callback to be called. If you set this option to 1, the
callback isn't called until the user releases the mouse button.
Set orient=HORIZONTAL for a horizontal scrollbar,orient=VERTICAL
orient
for a vertical one.
This option controls how long button 1 has to be held down in the
repeatdelay trough before the slider starts moving in that direction repeatedly.
Default is repeatdelay=300, and the units are milliseconds.
repeatinterval Repeat interval
Normally, you can tab the focus through a scrollbar widget. Set
takefocus
takefocus=0 if you don't want this behavior.
troughcolor The color of the trough.
Width of the scrollbar (its y dimension if horizontal, and its x
width
dimension if vertical). Default is 16.
Methods
Scrollbar objects have these methods-
Methods Description
Returns two numbers (a, b) describing the current position of the slider.
The a value gives the position of the left or top edge of the slider, for
get()
horizontal and vertical scrollbars respectively; the b value gives the
position of the right or bottom edge.
To connect a scrollbar to another widget w, set w's xscrollcommand or
set ( first, last ) yscrollcommand to the scrollbar's set() method. The arguments have the
same meaning as the values returned by the get() method.
Example
Try the following example yourself-
# !/usr/bin/python3
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()
When the above code is executed, it produces the following result-
Tkinter Text
Text widgets provide advanced capabilities that allow you to edit a multiline text and format
the way it has to be displayed, such as changing its color and font.
You can also use elegant structures like tabs and marks to locate specific sections of the
text, and apply changes to those areas. Moreover, you can embed windows and images in
the text because this widget was designed to handle both plain and formatted text.
Syntax
Here is the simple syntax to create this widget-
Options Description
bg The default background color of the text widget.
bd The width of the border around the text widget. Default is 2
pixels.
cursor The cursor that will appear when the mouse is over the text
widget.
exportselection Normally, text selected within a text widget is exported to be the
selection in the window manager. Set exportselection=0 if you don't
want that behavior.
font The default font for text inserted into the widget.
fg The color used for text (and bitmaps) within the widget. You can
change the color for tagged regions; this option is just the default.
height The height of the widget in lines (not pixels!), measuredaccording
to the current font size.
highlightbackground The color of the focus highlight when the text widget does nothave
focus.
highlightcolor The color of the focus highlight when the text widget has the
focus.
highlightthickness The thickness of the focus highlight. Default is 1. Set
highlightthickness=0 to suppress display of the focus highlight.
insertbackground The color of the insertion cursor. Default is black.
insertborderwidth Size of the 3-D border around the insertion cursor. Default is 0.
insertofftime The number of milliseconds the insertion cursor is off during its blink
cycle. Set this option to zero to suppress blinking. Default is 300.
insertontime The number of milliseconds the insertion cursor is on during itsblink
cycle. Default is 600.
insertwidth Width of the insertion cursor (its height is determined by the
tallest item in its line). Default is 2 pixels.
padx The size of the internal padding added to the left and right ofthe
text area. Default is one pixel.
pady The size of the internal padding added above and below the textarea.
Default is one pixel.
relief The 3-D appearance of the text widget. Default isrelief=SUNKEN.
selectbackground The background color to use displaying selected text.
selectborderwidth The width of the border to use around selected text.
spacing1 This option specifies how much extra vertical space is put above each
line of text. If a line wraps, this space is added only beforethe first
line it occupies on the display. Default is 0.
spacing2 This option specifies how much extra vertical space to add between
displayed lines of text when a logical line wraps. Default is 0.
spacing3 This option specifies how much extra vertical space is added below
each line of text. If a line wraps, this space is added onlyafter the
last line it occupies on the display. Default is 0.
state Normally, text widgets respond to keyboard and mouse events;set
state=NORMAL to get this behavior. If you set state=DISABLED,
the text widget will not respond, and you won't be able to modify its
contents programmatically either.
tabs This option controls how tab characters position text.
width The width of the widget in characters (not pixels!), measured
according to the current font size.
wrap This option controls the display of lines that are too wide. Set
wrap=WORD and it will break the line after the last word that will
fit. With the default behavior, wrap=CHAR, any line that gets too
long will be broken at any character.
xscrollcommand To make the text widget horizontally scrollable, set this optionto
the set() method of the horizontal scrollbar.
yscrollcommand To make the text widget vertically scrollable, set this option tothe
set() method of the vertical scrollbar.
Methods
Text objects have these methods-
Marks are used to bookmark positions between two characters within a given text. We have
the following methods available when handling marks:
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
text = Text(root)
text.insert(INSERT, "Hello. ")
text.insert(END, "Bye Bye. ")
text.pack()
text.tag_add("here", "1.0", "1.4")
text.tag_add("start", "1.8", "1.13")
text.tag_config("here", background="yellow", foreground="blue")
text.tag_config("start", background="black", foreground="green")
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter Toplevel
Toplevel widgets work as windows that are directly managed by the window manager. They
do not necessarily have a parent widget on top of them.
Syntax
Here is the simple syntax to create this widget-
Options Description
bg The background color of the window.
bd Border width in pixels; default is 0.
cursor The cursor that appears when the mouse is in this window.
Normally, text selected within a text widget is exported to be the
class_ selection in the window manager. Set exportselection=0 if you don't want
that behavior.
font The default font for text inserted into the widget.
The color used for text (and bitmaps) within the widget. You can
fg
change the color for tagged regions; this option is just the default.
height Window height.
Normally, a top-level window will have no 3-d borders around it. To get
relief a shaded border, set the bd option larger that its default value of zero,
and set the relief option to one of the constants.
width The desired width of the window.
Methods
Example
Try following example yourself-
# !/usr/bin/python3
from tkinter import *
root = Tk()
root.title("hello")
top = Toplevel()
top.title("Python")
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter 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.
Syntax
Here is the simple syntax to create this widget-
Options Description
The color of the slider and arrowheads when the mouse is over
activebackground
them.
The color of the slider and arrowheads when the mouse is not
Bg
over them.
The width of the 3-d borders around the entire perimeter of the
trough, and also the width of the 3-d effects on the arrowheads
Bd
and slider. Default is no border around the trough, and a 2-pixel
border around the arrowheads and slider.
command A procedure to be called whenever the scrollbar is moved.
cursor The cursor that appears when the mouse is over the scrollbar.
disabledbackground The background color to use when the widget is disabled.
disabledforeground The text color to use when the widget is disabled.
fg Text color.
font The font to use in this widget.
format Format string. No default value.
The minimum value. Used together with to to limit the spinbox
from_
range.
justify Default is LEFT
relief Default is SUNKEN.
Together with repeatinterval, this option controls button auto-
repeatdelay
repeat. Both values are given in milliseconds.
repeatinterval See repeatdelay.
state One of NORMAL, DISABLED, or "readonly". Default is NORMAL.
textvariable No default value.
to See from.
validate Validation mode. Default is NONE.
validatecommand Validation callback. No default value.
A tuple containing valid values for this widget. Overrides
values
from/to/increment.
vcmd Same as validatecommand.
width Widget width, in character units. Default is 20.
wrap If true, the up and down buttons will wrap around.
Used to connect a spinbox field to a horizontal scrollbar. This option
xscrollcommand
should be set to the set method of the corresponding scrollbar.
Methods
Spinbox objects have these methods-
Each pane contains one widget and each pair of panes is separated by a moveable (via
mouse movements) sash. Moving a sash causes the widgets on either side of the sash to be
resized.
Syntax
Here is the simple syntax to create this widget-
Option Description
The color of the slider and arrowheads when the mouse is not over
bg
them.
The width of the 3-d borders around the entire perimeter of the trough, and
also the width of the 3-d effects on the arrowheads and slider. Default is
bd
no border around the trough, and a 2-pixel border around the arrowheads
and slider.
borderwidth Default is 2.
cursor The cursor that appears when the mouse is over the window.
handlepad Default is 8.
handlesize Default is 8.
height No default value.
orient Default is HORIZONTAL.
relief Default is FLAT.
sashcursor No default value.
sashrelief Default is RAISED.
sashwidth Default is 2.
showhandle No default value
width No default value.
Methods
PanedWindow objects have these methods-
# !/usr/bin/python3
from tkinter import *
m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
left = Entry(m1, bd=5)
m1.add(left)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
top = Scale( m2, orient=HORIZONTAL)
m2.add(top)
bottom = Button(m2, text="OK")
m2.add(bottom)
mainloop()
When the above code is executed, it produces the following result-
Tkinter LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.
This widget has the features of a frame plus the ability to display a label.
Syntax
Here is the simple syntax to create this widget-
Option Description
The normal background color displayed behind the label and
bg
indicator.
bd The size of the border around the indicator. Default is 2 pixels.
If you set this option to a cursor name (arrow, dot etc.), the mouse
cursor
cursor will change to that pattern when it is over the checkbutton.
font The vertical dimension of the new frame.
height The vertical dimension of the new frame.
labelAnchor Specifies where to place the label.
highlightbackground Color of the focus highlight when the frame does not have focus.
highlightcolor Color shown in the focus highlight when the frame has the focus.
highlightthickness Thickness of the focus highlight.
With the default value, relief=FLAT, the checkbutton does not
relief stand out from its background. You may set this option to any of
the other styles
text Specifies a string to be displayed inside the widget.
width Specifies the desired width for the window.
Example
Try the following example yourself. Here is how to create a labelframe widget-
# !/usr/bin/python3
from tkinter import *
root = Tk()
labelframe = LabelFrame(root, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")
left = Label(labelframe, text="Inside the LabelFrame")
left.pack()
root.mainloop()
When the above code is executed, it produces the following result-
Tkinter tkMessageBox
The tkMessageBox module is used to display message boxes in your applications. This
module provides a number of functions that you can use to display an appropriate message.
Syntax
Here is the simple syntax to create this widget-
You could use one of the following functions with dialogue box-
• showinfo()
• showwarning()
• showerror ()
• askquestion()
• askokcancel()
• askyesno ()
• askretrycancel ()
Example
Try the following example yourself-
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
def hello():
messagebox.showinfo("Say Hello", "Hello World")
B1 = Button(top, text = "Say Hello", command = hello)
B1.place(x=35,y=50)
top.mainloop()
When the above code is executed, it produces the following result-
Standard Attributes
Let us look at how some of the common attributes, such as sizes, colors and fonts are
specified.
• Dimensions
• Colors
• Fonts
• Anchors
• Relief styles
• Bitmaps
• Cursors
Tkinter Dimensions
Various lengths, widths, and other dimensions of widgets can be described in many different
units.
Character Description
c Centimeters
i Inches
m Millimeters
p Printer's points (about 1/72")
Length options
Tkinter expresses a length as an integer number of pixels. Here is the list of common length
options-
• borderwidth: Width of the border which gives a three-dimensional look to the widget.
• highlightthickness: Width of the highlight rectangle when the widget has focus .
• padX padY: Extra space the widget requests from its layout manager beyond the
minimum the widget needs to display its contents in the x and y directions.
• selectborderwidth: Width of the three-dimentional border around selected items of
the widget.
• wraplength: Maximum line length for widgets that perform word wrapping.
• height: Desired height of the widget; must be greater than or equal to 1.
• underline: Index of the character to underline in the widget's text (0 is the first
character, 1 the second one, and so on).
• width: Desired width of the widget.
Tkinter Colors
Tkinter represents colors with strings. There are two general ways to specify colors in
Tkinter-
• You can use a string specifying the proportion of red, green and blue in hexadecimal
digits. For example, "#fff" is white, "#000000" is black, "#000fff000" is pure green,
and "#00ffff" is pure cyan (green plus blue).
• You can also use any locally defined standard color name. The colors "white",
"black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be
available.
Color options
The common color options are-
• activebackground: Background color for the widget when the widget is active.
• activeforeground: Foreground color for the widget when the widget is active.
• background: Background color for the widget. This can also be represented as bg.
• disabledforeground: Foreground color for the widget when the widget is disabled.
• foreground: Foreground color for the widget. This can also be represented as fg.
• highlightbackground: Background color of the highlight region when the widget has
focus.
• highlightcolor: Foreground color of the highlight region when the widget has focus.
• selectbackground: Background color for the selected items of the widget.
• selectforeground: Foreground color for the selected items of the widget.
Tkinter Fonts
There may be up to three ways to specify type style.
Example
• ("Helvetica", "16") for a 16-point Helvetica regular.
• ("Times", "24", "bold italic") for a 24-point Times bold italic.
import tkFont
font = tkFont.Font ( option, ... )
Here is the list of options-
Example
helv36 = tkFont.Font(family="Helvetica",size=36,weight="bold")
X Window Fonts
If you are running under the X Window System, you can use any of the X font names.
• NW
• N
• NE
• W
• CENTER
• E
• SW
• S
• SE
For example, if you use CENTER as a text anchor, the text will be centered horizontally and
vertically around the reference point.
Anchor NW will position the text so that the reference point coincides with the northwest
(top left) corner of the box containing the text.
Anchor W will center the text vertically around the reference point, with the left edge of the
text box passing through that point, and so on.
If you create a small widget inside a large frame and use the anchor=SE option, the widget
will be placed in the bottom right corner of the frame. If you used anchor=N instead, the
widget would be centered along the top edge.
Example
The anchor constants are shown in this diagram-
Here is list of possible constants which can be used for relief attribute-
• FLAT
• RAISED
• SUNKEN
• GROOVE
• RIDGE
Example
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1 = Button(top, text ="FLAT", relief=FLAT )
B2 = Button(top, text ="RAISED", relief=RAISED )
B3 = Button(top, text ="SUNKEN", relief=SUNKEN )
B4 = Button(top, text ="GROOVE", relief=GROOVE )
B5 = Button(top, text ="RIDGE", relief=RIDGE )
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Bitmaps
This attribute to displays a bitmap. There are following type of bitmaps available-
• "error"
• "gray75"
• "gray50"
• "gray25"
• "gray12"
• "hourglass"
• "info"
• "questhead"
• "question"
• "warning"
Example
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1 = Button(top, text ="error", relief=RAISED,\ bitmap="error")
B2 = Button(top, text ="hourglass", relief=RAISED,\ bitmap="hourglass")
B3 = Button(top, text ="info", relief=RAISED,\ bitmap="info")
B4 = Button(top, text ="question", relief=RAISED,\ bitmap="question")
B5 = Button(top, text ="warning", relief=RAISED,\ bitmap="warning")
B1.pack()
B2.pack()
B3.pack()
B4.pack()
B5.pack()
top.mainloop()
When the above code is executed, it produces the following result-
Tkinter Cursors
Python Tkinter supports quite a number of different mouse cursors available. The exact
graphic may vary according to your operating system.
• "arrow"
• "circle"
• "clock"
• "cross"
• "dotbox"
• "exchange"
• "fleur"
• "heart"
• "heart"
• "man"
• "mouse"
• "pirate"
• "plus"
• "shuttle"
• "sizing"
• "spider"
• "spraycan"
• "star"
• "target"
• "tcross"
• "trek"
• "watch"
Example
Try the following example by moving cursor on different buttons-
# !/usr/bin/python3
from tkinter import *
import tkinter
top = Tk()
B1 = Button(top, text ="circle", relief=RAISED,\ cursor="circle")
B2 = Button(top, text ="plus", relief=RAISED,\ cursor="plus")
B1.pack()
B2.pack()
top.mainloop()