Learn Python Tutorial [All in 1 Guide for Beginners]

Python Tutorial [All in 1] guide is simple and easy to understand for the beginners who want to learn Python programming language from basic to advanced level. The topics can be selected from table of contents.

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). This tutorial gives enough understanding on Python programming language.

Table of Contents

Audience to learn Python

This tutorial is designed for software programmers who need to learn Python programming language from scratch.

Prerequisites for Python Tutorial

You should have a basic understanding of Computer Programming terminologies. A basic understanding of any of the programming languages is a plus.

Overview of Python Language

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

  • Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.
  • Python is a Beginner’s Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
  • Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.
  • Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

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

Python’s features include

  • Scalable − Python provides a better structure and support for large programs than shell scripting.
  • Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.
  • Easy-to-maintain − Python’s source code is fairly easy-to-maintain.
  • Easy-to-read − Python code is more clearly defined and visible to the eyes.
  • 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.
  • A broad standard library − Python’s bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
  • Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms.
  • Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.
  • 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.
  • It supports functional and structured programming methods as well as OOP.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
  • It supports automatic garbage collection.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.

Python Programming: Environment Setup

Python is available on a wide variety of platforms including Linux and Mac OS X. Let’s understand how to set up our Python environment.

Local Environment Setup

Open a terminal window and type “python” to find out if it is already installed and which version is installed.

  • Acorn/RISC OS
  • Amiga
  • BeOS
  • DOS (multiple versions)
  • Macintosh (Intel, PPC, 68K)
  • Nokia mobile phones
  • OS/2
  • PalmOS
  • Python has also been ported to the Java and .NET virtual machines
  • Psion
  • QNX
  • VMS/OpenVMS
  • VxWorks
  • Win 95/98/XP/NT/2000/Vista/7/8/8.1/10
  • Windows CE

Download Python

Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.

If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation.

Here is a quick overview of installing Python on various platforms:

Linux & Unix Installation

Here are the simple steps to install Python on Unix/Linux machine.

  • Open a Web browser and go to https://www.python.org/downloads/.
  • Follow the link to download zipped source code available for Unix/Linux.
  • Download and extract files.
  • Editing the Modules/Setup file if you want to customize some options.
  • run ./configure script
  • make
  • make install

This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.

Windows Installation

Here are the steps to install Python on Windows machine.

  • Open a Web browser and go to https://www.python.org/downloads/
  • Follow the link for the Windows installer python-XYZ.msi file where XYZ is the version you need to install.
  • To use this installer python-XYZ.msi, the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run it to find out if your machine supports MSI.
  • Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is finished, and you are done.

Macintosh Installation

Recent Macs come with Python installed, but it may be several years out of date. See http://www.python.org/download/mac/ for instructions on getting the current version along with extra tools to support development on the Mac. For older Mac OS’s before Mac OS X 10.3 (released in 2003), MacPython is available.

Jack Jansen maintains it and you can have full access to the entire documentation at his website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation details for Mac OS installation.

Setting up PATH variable

Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for executables.

The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the command shell and other programs.

The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).

In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux

To add the Python directory to the path for a particular session in Unix

  • In the csh shell − type setenv PATH “$PATH:/usr/local/bin/python” and press Enter.
  • In the bash shell (Linux) − type export PATH=”$PATH:/usr/local/bin/python” and press Enter.
  • In the sh or ksh shell − type PATH=”$PATH:/usr/local/bin/python” and press Enter.
  • Note − /usr/local/bin/python is the path of the Python directory

Setting path at Windows

To add the Python directory to the path for a particular session in Windows:

At the command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory

Python Environment Variables

Here are important environment variables, which can be recognized by Python:

Serial No. Variable & Description
1. PYTHONCASEOK
It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.
2. PYTHONPATH
It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.
3. PYTHONSTARTUP
It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.
4. PYTHONHOME
It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Running Python

There are three different ways to start Python:

Interactive Interpreter

You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.

Enter python the command line.

Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS

Here is the list of all the available command line options:

Serial No. Option & Description
1. -O
It generates optimized bytecode (resulting in .pyo files).
2. -d
It provides debug output.
3. -X
disable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.
4. -S
Do not run import site to look for Python paths on startup.
5. -v
verbose output (detailed trace on import statements).
6. file
run Python script from given file
7. -c cmd
run Python script sent in as cmd string

Script from the Command-line

A Python script can be executed at command line by invoking the interpreter on your application, as in the following:

$python script.py # Unix/Linux

or

python% script.py # Unix/Linux

or 

C: >python script.py # Windows/DOS

Note − Be sure the file permission mode allows execution.

Integrated Development Environment

You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.

  • Unix − IDLE is the very first Unix IDE for Python.
  • Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex’d files.
  • Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.

If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up and working perfectly fine.

Note − All the examples given in subsequent chapters are executed with Python 2.4.3 version available on CentOS flavor of Linux.

We already have set up Python Programming environment online, so that you can execute all the available examples online at the same time when you are learning theory. Feel free to modify any example and execute it online.

Basic Syntax of Python

The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

First Python Program

Let us execute programs in different modes of programming.

Interactive Mode Programming

Invoking the interpreter without passing a script file as a parameter brings up the following prompt:

$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

Type the following text at the Python prompt and press the Enter:

>>> print "Hello, Python!"

If you are running new version of Python, then you would need to use print statement with parenthesis as in print (“Hello, Python!”);. However in Python version 2.4.3, this produces the following result:

 Hello, Python! 

Script Mode Programming

Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.

Let us write a simple Python program in a script. Python files have extension .py. Type the following source code in a test.py file:

print "Hello, Python!"

We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows:

 $ python test.py 

This produces the following result:

 Hello, Python! 

Let us try another way to execute a Python script. Here is the modified test.py file:

#!/usr/bin/python

print "Hello, Python!"

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows :

 $ chmod +x test.py     # This is to make file executable 
 $./test.py 

This produces the following result :

 Hello, Python! 

Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers:

  • Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
  • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
  • Starting an identifier with two leading underscores indicates a strongly private identifier.
  • Starting an identifier with a single leading underscore indicates that the identifier is private.

Reserved Words

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

and assert break
class continuedef
delelifelse
exceptexecfinally
forfromglobal
ifimportin
islambdanot
orpassprint
raisereturntry
whilewithyield

Lines and Indentation

Python provides no 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"

However, the following block generates an error:

if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks.

Note − Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.

#!/usr/bin/python

import sys

try:
   # open file stream
   file = open(file_name, "w")
except IOError:
   print "There was an error writing to", file_name
   sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
   file_text = raw_input("Enter text: ")
   if file_text == file_finish:
      # close the file
      file.close
      break
   file.write(file_text)
   file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
   print "Next time please enter something"
   sys.exit()
try:
   file = open(file_name, "r")
except IOError:
   print "There was an error reading file"
   sys.exit()
file_text = file.read()
file.close()
print file_text

Multi-Line Statements

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example:

total = item_one + \
        item_two + \
        item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example:

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

Quotation in Python

Python accepts single (‘), double (“) and triple (”’ or “””) quotes to denote string literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal:

word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Comments in Python

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them.

#!/usr/bin/python

# First comment
print "Hello, Python!" # second comment

This produces the following result:

 Hello, Python! 

You can type a comment on the same line after a statement or expression:

name = "Madisetti" # This is again comment

You can comment multiple lines as follows:

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

'''
This is a multiline
comment.
'''

Using Blank Lines

A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

Waiting for the User

The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action:

#!/usr/bin/python

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

Multiple Statements on a Single Line

The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the semicolon:

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites

A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.

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

Command Line Arguments

Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h

 $ python -h usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... Options and arguments (and corresponding environment variables): 
-c cmd : program passed in as string (terminates option list) 
-d     : debug output from parser (also PYTHONDEBUG=x) 
-E     : ignore environment variables (such as PYTHONPATH) 
-h     : print this help message and exit [ etc. ] 

You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic.

Python provides a getopt module that helps you parse command-line options and arguments.

 $ python test.py arg1 arg2 arg3 

The Python sys module provides access to any command-line arguments via the sys.argv. This serves two purposes:

  • sys.argv is the list of command-line arguments.
  • len(sys.argv) is the number of command-line arguments.

Here sys.argv[0] is the program ie. script name.

Example

Consider the following script test.py

#!/usr/bin/python

import sys

print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

Now run above script as follows:

 $ python test.py arg1 arg2 arg3 

This produce following result:

 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3'] 

NOTE − As mentioned above, first argument is always script name and it is also being counted in number of arguments.

Parsing Command-Line Arguments

Python provided a getopt module that helps you parse command-line options and arguments. This module provides two functions and an exception to enable command-line argument parsing.

getopt.getopt method

This method parses command-line options and parameter list. Following is simple syntax for this method:

getopt.getopt(args, options, [long_options])

Here is the detail of the parameters:

  • args − This is the argument list to be parsed.
  • options − This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).
  • long_options − This is an optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign (‘=’). To accept only long options, options should be an empty string.
  • This method returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped.
  • Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g., ‘-x’) or two hyphens for long options (e.g., ‘–long-option’).

Exception getopt.GetoptError

This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none.

The argument to the exception is a string indicating the cause of the error. The attributes msg and opt give the error message and related option.

Example

Consider we want to pass two file names through command line and we also want to give an option to check the usage of the script. Usage of the script is as follows:

 usage: test.py -i <inputfile> -o <outputfile> 

Here is the following script to test.py

#!/usr/bin/python

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])

Now, run above script as follows:

 $ test.py -h 
usage: test.py -i <inputfile> -o <outputfile> 

$ test.py -i BMP -o 
usage: test.py -i <inputfile> -o <outputfile> 

$ test.py -i inputfile 
Input file is " inputfile 
Output file is " 

Variable Types in Python

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.

Assigning Values to Variables

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example:

#!/usr/bin/python

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 three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

a,b,c = 1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value “john” is assigned to the variable c.

Standard Data Types

The data stored in memory can be of many types. For example, a person’s age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.

Python has five standard data types:

  • 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 var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example:

del var
del var_a, var_b

Python supports four different numerical types:

  • int (signed integers)
  • complex (complex numbers)
  • float (floating point real values)
  • long (long integers, they can also be represented in octal and hexadecimal)

Examples

Here are some examples of numbers:

intlongfloatcomplex
10 51924361L 0.03.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
  • A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

Python Strings

Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs 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 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example:

#!/usr/bin/python

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string

This will produce the following result:

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 difference 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/python

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 produce the following result:

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Python Tuples

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example:

#!/usr/bin/python

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple           # Prints complete list
print tuple[0]        # Prints first element of the list
print tuple[1:3]      # Prints elements starting from 2nd till 3rd 
print tuple[2:]       # Prints elements starting from 3rd element
print tinytuple * 2   # Prints list two times
print tuple + tinytuple # Prints concatenated lists

This produce the following result:

('abcd', 786, 2.23, 'john', 70.2) 
abcd 
(786, 2.23) 
(2.23, 'john', 70.2) 
(123, 'john', 123, 'john') 
('abcd', 786, 2.23, 'john', 70.2, 123, 'john') 

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/python

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/python

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 produce the following result:

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 elements. It is incorrect to say that the elements are “out of order”; they are simply unordered.

Data Type Conversion

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function.

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.


Serial No.
Function & Description
1. oct(x)
Converts an integer to an octal string.
2. hex(x)
Converts an integer to a hexadecimal string.
3. ord(x)
Converts a single character to its integer value.
4. unichr(x)
Converts an integer to a Unicode character.
5. chr(x)
Converts an integer to a character.
6. frozenset(s)
Converts s to a frozen set.
7. dict(d)
Creates a dictionary. d must be a sequence of (key,value) tuples.
8. set(s)
Converts s to a set.
9. list(s)
Converts s to a list.
10. tuple(s)
Converts s to a tuple.
11. eval(str)
Evaluates a string and returns an object.
12. repr(x)
Converts object x to an expression string.
13. str(x)
Converts object x to a string representation.
14. complex(real [,imag])
Creates a complex number.
15. float(x)
Converts x to a floating-point number.
16. long(x [,base] )
Converts x to a long integer. base specifies the base if x is a string.
17. int(x [,base])
Converts x to an integer. base specifies the base if x is a string.

Basic Operators in Python

Operators are the constructs which can manipulate the value of operands.

Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.

  • Identity Operators
  • Membership Operators
  • Bitwise Operators
  • Logical Operators
  • Assignment Operators
  • Comparison (Relational) Operators
  • Arithmetic Operators

Let us have a look on all operators one by one.

Python Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then

#!/usr/bin/python

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
Line 5 - Value of c is 1 
Line 6 - Value of c is 8 
Line 7 - Value of c is 2 
OperatorDescriptionExample
+ Addition Adds values on either side
of the operator.
a + b = 30
– Subtraction Subtracts right hand operand
from left hand operand.
a – b = -10
* Multiplication Multiplies values on either
side of the operator
a * b = 200
/ Division Divides left hand operand by
right hand operand
b / a = 2
% Modulus Divides left hand operand by
right hand operand and
returns remainder
b % a = 0
** Exponent Performs exponential
(power) calculation on
operators
a**b =10 to the power 20
// Floor Division – The division
of operands where the result
is the quotient in which the
digits after the decimal point
are removed. But if one of
the operands is negative, the result
is floored, i.e., rounded away
from zero (towards negative
infinity)
9//2 = 4 and 9.0//2.0 = 4.0,
-11//3 = -4, -11.0//3 = -4.0

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators.

Example

Assume variable a holds 10 and variable b holds 20, then:

#!/usr/bin/python

a = 21
b = 10
c = 0

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 not equal to b"
else:
   print "Line 3 - a is equal to b"

if ( a < b ):
   print "Line 4 - a is less than b" 
else:
   print "Line 4 - a is not less than b"

if ( a > b ):
   print "Line 5 - a is greater than b"
else:
   print "Line 5 - a is not greater than b"

a = 5;
b = 20;
if ( a <= b ):
   print "Line 6 - a is either less than or equal to  b"
else:
   print "Line 6 - a is neither less than nor equal to  b"

if ( b >= a ):
   print "Line 7 - b is either greater than  or equal to b"
else:
   print "Line 7 - b is neither greater than  nor equal to b"

When you execute the above program it produces the following result:

Line 1 - a is not equal to b 
Line 2 - a is not equal to b 
Line 3 - a is not equal to b 
Line 4 - a is not less than b 
Line 5 - a is greater than b 
Line 6 - a is either less than or equal to b 
Line 7 - b is either greater than or equal to b 
OperatorDescriptionExample
== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!= If values of two operands are not equal, then condition becomes true. (a != b) is true.
<> If values of two operands are not equal, then condition becomes true. (a > b) is not true.
>If the value of left operand is greater than the value of right operand, then condition becomes true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
=<If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.

Python Assignment Operators

Example:

Assume variable a holds 10 and variable b holds 20, then

#!/usr/bin/python

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 
Line 5 - Value of c is 2 
Line 6 - Value of c is 2097152 
Line 7 - Value of c is 99864 
OperatorDescriptionExample
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c – a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

Example:

There are following Bitwise operators supported by Python language:

#!/usr/bin/python

a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0

c = a & b;        # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b;        # 61 = 0011 1101 
print "Line 2 - Value of c is ", c

c = a ^ b;        # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a;           # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2;       # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2;       # 15 = 0000 1111
print "Line 6 - Value of c is ", c

When you execute the above program it produces the following result:

Line 1 - Value of c is 12 
Line 2 - Value of c is 61 
Line 3 - Value of c is 49 
Line 4 - Value of c is -61 
Line 5 - Value of c is 240 
Line 6 - Value of c is 15 
OperatorDescriptionExample
& Binary AND Operator copies a bit to the result if it exists in both operands (a & b) (means 0000 1100)
| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
~ Binary Ones Complement It is unary and has the effect of ‘flipping’ bits. (~a ) = -61 (means 1100 0011 in 2’s complement form due to a signed binary number.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand. a << 2 = 240 (means 1111 0000)
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand. a >> 2 = 15 (means 0000 1111)

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then:

OperatorDescriptionExample
and Logical AND If both the operands are true then condition becomes true. (a and b) is true.
or Logical OR If any of the two operands are non-zero then condition becomes true. (a or b) is true.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is false.

Used to reverse the logical state of its operand.

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:

OperatorDescriptionExample
inEvaluates to true if it finds a variable in the specified sequence and false otherwise. x in y, here in results in a 1 if x is a member of sequence y.
not inEvaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators explained below:

Example:

#!/usr/bin/python

a = 20
b = 20

if ( a is b ):
   print "Line 1 - a and b have same identity"
else:
   print "Line 1 - a and b do not have same identity"

if ( id(a) == id(b) ):
   print "Line 2 - a and b have same identity"
else:
   print "Line 2 - a and b do not have same identity"

b = 30
if ( a is b ):
   print "Line 3 - a and b have same identity"
else:
   print "Line 3 - a and b do not have same identity"

if ( a is not b ):
   print "Line 4 - a and b do not have same identity"
else:
   print "Line 4 - a and b have same identity"

When you execute the above program it produces the following result:

Line 1 - a and b have same identity 
Line 2 - a and b have same identity 
Line 3 - a and b do not have same identity 
Line 4 - a and b do not have same identity 
OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise. x is not y, here is not results in 1 if id(x) is not equal to id(y).

Python Operators Precedence

The following table lists all operators from highest precedence to lowest.

Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

Example:

#!/usr/bin/python

a = 20
b = 10
c = 15
d = 5
e = 0

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:

Value of (a + b) * c / d is 90 
Value of ((a + b) * c) / d is 90 
Value of (a + b) * (c / d) is 90 
Value of a + (b * c) / d is 50 
Serial No. Operator & Description
1 **
Exponentiation (raise to the power)
2 ~ + –
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 + –
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise ‘AND’
7 ^ |
Bitwise exclusive `OR’ and regular `OR’
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators

Decision Making in Python

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the programming languages

decision_making

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

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

Serial No. Statement & Description
1 if statements:
An if statement consists of a boolean expression followed by one or more statements.
2 if…else statements
An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).

Python if statement

It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison.

Syntax

if expression:
   statement(s)

If the boolean expression evaluates to TRUE, then the block of the statement(s) inside the if the statement is executed. If boolean expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.

Flow Diagram

if_statement

Example

#!/usr/bin/python

var1 = 100
if var1:
   print "1 - Got a true expression value"
   print var1

var2 = 0
if var2:
   print "2 - Got a true expression value"
   print var2
print "Good bye!"

When the above code is executed, it produces the following result:

1 - Got a true expression value 
100 
Good bye! 

Single Statement Suites

If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

Here is an example of a one-line if clause:

#!/usr/bin/python

var = 100
if ( var == 100 ) : print "Value of expression is 100"
print "Good bye!"

When the above code is executed, it produces the following result:

Value of expression is 100 
Good bye! 

Python if..else statements

An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at 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

if_else_statement

Example

#!/usr/bin/python

var1 = 100
if var1:
   print "1 - Got a true expression value"
   print var1
else:
   print "1 - Got a false expression value"
   print var1

var2 = 0
if var2:
   print "2 - Got a true expression value"
   print var2
else:
   print "2 - Got a false expression value"
   print var2

print "Good bye!"

When the above code is executed, it produces the following result:

1 - Got a true expression value 
100 
2 - Got a false expression value 
0 
Good bye! 

The elif Statement

The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.

Similar to the else, the elif statement is optional. However, unlike else, for which there can be at 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/python

var = 100
if var == 200:
   print "1 - Got a true expression value"
   print var
elif var == 150:
   print "2 - Got a true expression value"
   print var
elif var == 100:
   print "3 - Got a true expression value"
   print var
else:
   print "4 - Got a false expression value"
   print var

print "Good bye!"

When the above code is executed, it produces the following result:

3 - Got a true expression value
100 
Good bye! 

Python 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)
   elif expression4:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

Example

#!/usr/bin/python

var = 100
if var < 200:
   print "Expression value is less than 200"
   if var == 150:
      print "Which is 150"
   elif var == 100:
      print "Which is 100"
   elif var == 50:
      print "Which is 50"
   elif var < 50:
      print "Expression value is less than 50"
else:
   print "Could not find true expression"

print "Good bye!"

When the above code is executed, it produces following result:

Expression value is less than 200 
Which is 100 
Good bye! 

Loops in Python

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement

loop_architecture

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

Serial No.Loop Type & Description
1while loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
2for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3nested loops
You can use one or more loop inside any another while, for or do..while loop.

Python for loop statements

Loop 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

python_for_loop

Example

#!/usr/bin/python

for letter in 'Python':     # First Example
   print 'Current Letter :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # Second Example
   print 'Current fruit :', fruit

print "Good bye!"

When the above code is executed, it produces the following result:

Current Letter : P 
Current Letter : y 
Current Letter : t 
Current Letter : h 
Current Letter : o 
Current Letter : n 
Current fruit : banana 
Current fruit : apple 
Current fruit : mango 
Good bye! 

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/python

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print 'Current fruit :', fruits[index]

print "Good bye!"

When the above code is executed, it produces the following result:

Current fruit : banana 
Current fruit : apple 
Current fruit : mango 
Good bye! 

Here, we took the assistance of the len() built-in function, which provides the total number of elements in the tuple as well as the range() built-in function to give us the actual sequence to iterate over.

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.

#!/usr/bin/python

for num in range(10,20):     #to iterate between 10 to 20
   for i in range(2,num):    #to iterate on the factors of the number
      if num%i == 0:         #to determine the first factor
         j=num/i             #to calculate the second factor
         print '%d equals %d * %d' % (num,i,j)
         break #to move to the next number, the #first FOR
   else:                  # else part of the loop
      print num, 'is a prime number'

When the above code is executed, it produces the following result:

10 equals 2 * 5 
11 is a prime number 
12 equals 2 * 6 
13 is a prime number 
14 equals 2 * 7 
15 equals 3 * 5 
16 equals 2 * 8 
17 is a prime number 
18 equals 2 * 9 
19 is a prime number 

Python while Loop Statements

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in Python programming language is

while expression:
   statement(s)

Here, statement(s) may be a single statement or a block of statements. 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

python_while_loop

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

#!/usr/bin/python

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Good bye!"

When the above code is executed, it produces the following result:

The count is: 0 
The count is: 1 
The count is: 2 
The count is: 3 
The count is: 4 
The count is: 5 
The count is: 6 
The count is: 7 
The count is: 8 
Good bye! 

The block here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1.

The infinite loop

A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

#!/usr/bin/python

var = 1
while var == 1 :  # This constructs an infinite loop
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"

When the above code is executed, it produces the following result:

Enter a number  :20
You entered:  20
Enter a number  :29
You entered:  29
Enter a number  :3
You entered:  3
Enter a number between :Traceback (most recent call last):
   File "test.py", line 5, in <module>
      num = raw_input("Enter a number :")
KeyboardInterrupt

Above example goes in an infinite loop and you need to use CTRL+C to exit the program.

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement.

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5, otherwise else statement gets executed.

#!/usr/bin/python

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

When the above code is executed, it produces the following result:

0 is less than 5
1 is less than 5 
2 is less than 5 
3 is less than 5 
4 is less than 5 
5 is not less than 5 

Single Statement Suites

Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause

#!/usr/bin/python

flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"

It is better not try above example because it goes into infinite loop and you need to press CTRL+C keys to exit.

Python Nested Loops

Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.

Syntax

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

The syntax for a nested while loop statement in Python programming language is as follows:

while expression:
   while expression:
      statement(s)
   statement(s)

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100

#!/usr/bin/python

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " is prime"
   i = i + 1

print "Good bye!"

When the above code is executed, it produces following result:

2 is prime 
3 is prime 
5 is prime 
7 is prime 
11 is prime 
13 is prime 
17 is prime 
19 is prime 
23 is prime 
29 is prime 
31 is prime 
37 is prime 
41 is prime 
43 is prime 
47 is prime 
53 is prime 
59 is prime 
61 is prime 
67 is prime 
71 is prime 
73 is prime 
79 is prime 
83 is prime 
89 is prime 
97 is prime 
Good bye! 

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail.

Let us go through the loop control statements briefly:

Serial No. Control Statement & Description
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

Python break Statement

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

Syntax

The syntax for a break statement in Python is as follows:

break

Flow Diagram

cpp_break_statement

Example

#!/usr/bin/python

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"

When the above code is executed, it produces the following result:

Current Letter : P 
Current Letter : y 
Current Letter : t 
Current variable value : 10 
Current variable value : 9 
Current variable value : 8 
Current variable value : 7 
Current variable value : 6 
Good bye! 

Python continue Statement

It returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

Syntax

continue

Flow Diagram

cpp_continue_statement

Example

#!/usr/bin/python

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! 

Python 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 is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example)

Syntax

pass

Example

#!/usr/bin/python

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

Numbers in Python

Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.

Number objects are created when you assign a value to them. For example:

var1 = 1
var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax of the del statement is:

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example:

del var
del var_a, var_b

Python supports four different numerical types:

  • long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
  • int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
  • 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.
  • float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).

Examples

Here are some examples of numbers

longintcomplexfloat
51924361L 10 3.14j 0.0
-0x19323L 100 45.j 15.20
0122L -786 9.322e-36j -21.9
0xDEFABCECBDAECBFBAEL 080 .876j 32.3+e18
535633629843L -0490 -.6545+0J -90.
-052318172735L -0x260 3e+26J -32.54e100
-4721885298529L 0x69 4.53e-7j 70.2-E12
  • A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.
  • Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.

Number Type Conversion

Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

  • Type int(x) to convert x to a plain integer.
  • Type long(x) to convert x to a long integer.
  • Type float(x) to convert x to a floating-point number.
  • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
  • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

Mathematical Functions

Python includes following functions that perform mathematical calculations.

Serial No. Function & Returns ( description )
1 abs(x)
The absolute value of x: the (positive) distance between x and zero.
2 ceil(x)
The ceiling of x: the smallest integer not less than x
3 cmp(x, y)
-1 if x < y, 0 if x == y, or 1 if x > y
4 exp(x)
The exponential of x: ex
5 fabs(x)
The absolute value of x.
6 floor(x)
The floor of x: the largest integer not greater than x
7 log(x)
The natural logarithm of x, for x> 0
8 log10(x)
The base-10 logarithm of x for x> 0.
9 max(x1, x2,…)
The largest of its arguments: the value closest to positive infinity
10 min(x1, x2,…)
The smallest of its arguments: the value closest to negative infinity
11 modf(x)
The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.
12 pow(x, y)
The value of x**y.
13 round(x [,n])
x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.
14 sqrt(x)
The square root of x for x > 0

Python Number abs() Method

The method abs() returns absolute value of x – the (positive) distance between x and zero.

Syntax

Following is the syntax for abs() method:

abs( x )

Parameters

x − This is a numeric expression.

Return Value

This method returns absolute value of x.

Example

The following example shows the usage of abs() method.

#!/usr/bin/python

print "abs(-45) : ", abs(-45)
print "abs(100.12) : ", abs(100.12)
print "abs(119L) : ", abs(119L)

When we run above program, it produces following result:

abs(-45) :  45 
abs(100.12) :  100.12 
abs(119L) :  119 

Python Number ceil() Method

The method ceil() returns ceiling value of x – the smallest integer not less than x.

Syntax

Following is the syntax for 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 math static object.

Parameters

x − This is a numeric expression.

Return Value

This method returns smallest integer not less than x.

Example

The following example shows the usage of ceil() method.

#!/usr/bin/python
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(119L) : ", math.ceil(119L)
print "math.ceil(math.pi) : ", math.ceil(math.pi)

When we run above program, it produces following result:

math.ceil(-45.17) :  -45.0 
math.ceil(100.12) :  101.0 
math.ceil(100.72) :  101.0
math.ceil(119L) :  119.0 
math.ceil(math.pi) : 4.0 

Python Number cmp() Method

The method cmp() returns the sign of the difference of two numbers : -1 if x < y, 0 if x == y, or 1 if x > y.

Syntax

Following is the syntax for cmp() method:

cmp( x, y )

Parameters

  • x − This is a numeric expression.
  • y − This is also a numeric expression.

Return Value

This method returns -1 if x < y, returns 0 if x == y and 1 if x > y

Example

The following example shows the usage of cmp() method.

#!/usr/bin/python

print "cmp(80, 100) : ", cmp(80, 100)
print "cmp(180, 100) : ", cmp(180, 100)
print "cmp(-80, 100) : ", cmp(-80, 100)
print "cmp(80, -100) : ", cmp(80, -100)

When we run above program, it produces following result:

cmp(80, 100) :  -1 
cmp(180, 100) :  1 
cmp(-80, 100) :  -1 
cmp(80, -100) :  1 

Python Number exp() Method

The method exp() returns returns exponential of x: ex.

Syntax

Following is the syntax for exp() method

import math
math.exp( 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 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/python
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(119L) : ", math.exp(119L)
print "math.exp(math.pi) : ", math.exp(math.pi)

When we run above program, it produces following result

math.exp(-45.17) :  2.41500621326e-20 
math.exp(100.12) :  3.03084361407e+43 
math.exp(100.72) :  5.52255713025e+43 
math.exp(119L) :  4.7978133273e+51 
math.exp(math.pi) :  23.1406926328 

Python Number fabs() Method

The method fabs() returns the absolute value of x.

Syntax

Following is the syntax for fabs() method.

import math
math.fabs( 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 is a numeric value.

Return Value

This method returns absolute value of x.

Example

The following example shows the usage of fabs() method.

#!/usr/bin/python
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(119L) : ", math.fabs(119L)
print "math.fabs(math.pi) : ", math.fabs(math.pi)

When we run above program, it produces following result:

math.fabs(-45.17) :  45.17 
math.fabs(100.12) :  100.12 
math.fabs(100.72) :  100.72 
math.fabs(119L) :  119.0 
math.fabs(math.pi) :  3.14159265359 

Python Number log() Method

The method log() returns natural logarithm of x, for x > 0.

Syntax

Following is the syntax for log() method

import math

math.log( 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 is a numeric expression.

Return Value

This method returns natural logarithm of x, for x > 0.

Example

The following example shows the usage of log() method.

#!/usr/bin/python
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(119L) : ", math.log(119L)
print "math.log(math.pi) : ", math.log(math.pi)

When we run above program, it produces following result

math.log(100.12) :  4.60636946656 
math.log(100.72) :  4.61234438974 
math.log(119L) :  4.77912349311 
math.log(math.pi) :  1.14472988585 

Python Number log10() Method

The method log10() returns base-10 logarithm of x for x > 0.

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 math module and then we need to call this function using math static object.

Parameters

x − This is a numeric expression.

Return Value

This method returns base-10 logarithm of x for x > 0.

Example

The following example shows the usage of log10() method.

#!/usr/bin/python
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(119L) : ", math.log10(119L)
print "math.log10(math.pi) : ", math.log10(math.pi)

When we run above program, it produces following result

math.log10(100.12) :  2.00052084094 
math.log10(100.72) :  2.0031157171 
math.log10(119L) :  2.07554696139 
math.log10(math.pi) :  0.497149872694 

Python Number min() Method

The method min() returns the smallest of its arguments: the value closest to negative infinity.

Syntax

Following is the syntax for 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 smallest of its arguments.

Example

The following example shows the usage of min() method.

#!/usr/bin/python

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 above program, it produces following result

min(80, 100, 1000) :  80 
min(-20, 100, 400) :  -20 
min(-80, -20, -10) :  -80 
min(0, 100, -400) :  -400 

Random Number Functions

Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

Serial No.Function & Description
1 choice(seq)
A random item from a list, tuple, or string.
2 randrange ([start,] stop [,step])
A randomly selected element from range(start, stop, step)
3 random()
A random float r, such that 0 is less than or equal to r and r is less than 1
4 seed([x])
Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.
5 shuffle(lst)
Randomizes the items of a list in place. Returns None.
6 uniform(x, y)
A random float r, such that x is less than or equal to r and r is less than y

Trigonometric Functions

Python includes following functions that perform trigonometric calculations.

Serial No. Function & Description
1 acos(x)
Return the arc cosine of x, in radians.
2 asin(x)
Return the arc sine of x, in radians.
3 atan(x)
Return the arc tangent of x, in radians.
4 atan2(y, x)
Return atan(y / x), in radians.
5 cos(x)
Return the cosine of x radians.
6 hypot(x, y)
Return the Euclidean norm, sqrt(x*x + y*y).
7 sin(x)
Return the sine of x radians.
8 tan(x)
Return the tangent of x radians.
9 degrees(x)
Converts angle x from radians to degrees.
10 radians(x)
Converts angle x from degrees to radians.

Mathematical Constants

Serial No. Constants & Description
1 pi
The mathematical constant pi.
2 e
The mathematical constant e.

Strings in Python

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:

var1 = 'Hello World!'
var2 = "Python Programming"

Accessing Values in Strings

Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example:

#!/usr/bin/python

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/python

var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'

When the above code is executed, it produces the following result

Updated String :-  Hello Python

Escape Characters

Following table is a list of escape or non-printable characters that can be represented with backslash notation.

An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash notation Hexadecimal character Description
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
\nnn Octal notation,
where n is in the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
\xnn Hexadecimal notation,
where n is in the range 0.9, a.f, or A.F

String Special Operators

Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then

Operator Description Example
+Concatenation – Adds values
on either side of the operator
a + b will give HelloPython
*Repetition – Creates new
strings, concatenating multiple copies of the same string
a*2 will give -HelloHello
[] Slice – Gives the character from
the given index
a[1] will give e
[ : ] Range Slice – Gives the
characters from the given range
a[1:4] will give ell
in Membership – Returns true
if a character exists in the
given string
H in a will give 1
not in Membership – Returns true
if a character does not exist
in the given string
M not in a will give 1
r/R Raw String – Suppresses actual
meaning of Escape characters.
The syntax for raw strings is
exactly the same as for normal
strings with the exception of
the 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.
print r’\n’ prints \n and print R’\n’prints \n
% Format – Performs String formatting See at next section

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/python

print "My name is %s and weight is %d kg!" % ('Zara', 21)

When the above code is executed, it produces the following result:

 My name is Zara and weight is 21 kg! 

Here is the list of complete set of symbols which can be used along with %.

Format SymbolConversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase ‘e’)
%E exponential notation (with UPPERcase ‘E’)
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

Other supported symbols and functionality are listed in the following table:

SymbolFunctionality
* argument specifies width or precision
left justification
+ display the sign
<sp> leave a blank space before a positive number
# add the octal leading zero ( ‘0’ ) or hexadecimal leading ‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were used.
0 pad from left with zeros (instead of spaces)
% ‘%%’ leaves you with a single literal ‘%’
(var) mapping variable (dictionary arguments)
m.n. m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

Triple Quotes

Python’s triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.

The syntax for triple quotes consists of three consecutive single or double quotes.

#!/usr/bin/python

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)

this is a long string that is made up of
several lines and non-printable characters such as
TAB (    ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like
this within the brackets [
 ], or just a NEWLINE within
the variable assignment will also show up.

Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it.

#!/usr/bin/python

print 'C:\\nowhere'

When the above code is executed, it produces the following result:

 C:\nowhere 

Now let’s make use of raw string. We would put expression in r’expression’ as follows:

#!/usr/bin/python

print r'C:\\nowhere'

When the above code is executed, it produces the following result.

 C:\\nowhere 

Unicode String

Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I’ll restrict my treatment of Unicode strings to the following:

#!/usr/bin/python

print u'Hello, world!'

When the above code is executed, it produces the following result:

 Hello, world! 

As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.

Built-in String Methods

Python includes the following built-in methods to manipulate strings.

Serial No. Methods with Description
1 capitalize()
Capitalizes first letter of string
2 center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
3 count(str, beg= 0,end=len(string))
Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
4 decode(encoding=’UTF-8′,errors=’strict’)
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.
5 encode(encoding=’UTF-8′,errors=’strict’)
Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’.
6 endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.
7 expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
8 find(str, beg=0 end=len(string))
Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
9 index(str, beg=0, end=len(string))
Same as find(), but raises an exception if str not found.
10 isalnum()
Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
11 isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
12 isdigit()
Returns true if string contains only digits and false otherwise.
13 islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
14 isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
15 isspace()
Returns true if string contains only whitespace characters and false otherwise.
16 istitle()
Returns true if string is properly “titlecased” and false otherwise.
17 isupper()
Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
18 join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.
19 len(string)
Returns the length of the string
20 ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total of width columns.
21 lower()
Converts all uppercase letters in string to lowercase.
22 lstrip()
Removes all leading whitespace in string.
23 maketrans()
Returns a translation table to be used in translate function.
24 max(str)
Returns the max alphabetical character from the string str.
25 min(str)
Returns the min alphabetical character from the string str.
26 replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences if max given.
27 rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
28 rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string.
29 rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
30 rstrip()
Removes all trailing whitespace of string.
31 split(str=””, num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.
32 splitlines( num=string.count(‘\n’))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
33 startswith(str, beg=0,end=len(string))
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.
34 strip([chars])
Performs both lstrip() and rstrip() on string.
35 swapcase()
Inverts case for all letters in string.
36 title()
Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
37 translate(table, deletechars=””)
Translates string according to translation table str(256 chars), removing those in the del string.
38 upper()
Converts lowercase letters in string to uppercase.
39 zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).
40 isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.

Lists in Python

The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number – its position or index. The first index is zero, the second index is one, and so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

Python Lists

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets. For example:

list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]

Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Accessing Values in Lists

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

#!/usr/bin/python

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:

list1[0]:  physics
list2[1:5]:  [2, 3, 4, 5]

Updating Lists

You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example:

#!/usr/bin/python

list = ['physics', 'chemistry', 1997, 2000];
print "Value available at index 2 : "
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

Note − append() method is discussed in subsequent section.

When the above code is executed, it produces the following result:

Value available at index 2 : 
1997 
New value available at index 2 : 
2001 

Delete List Elements

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example:

#!/usr/bin/python

list1 = ['physics', 'chemistry', 1997, 2000];
print list1
del list1[2];
print "After deleting value at index 2 : "
print list1

When the above code is executed, it produces following result:

['physics', 'chemistry', 1997, 2000] 
After deleting value at index 2 : 
['physics', 'chemistry', 2000] 

Note − remove() method is discussed in subsequent section.

Basic List Operations

Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.

In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

Assuming following input

L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description
L[2] SPAM! Offsets start at zero
L[-2] Spam Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

Built-in List Functions & Methods

Python includes the following list functions:

Serial No. Function with Description
1 cmp(list1, list2)
Compares elements of both lists.
2 len(list)
Gives the total length of the list.
3 max(list)
Returns item from the list with max value.
4 min(list)
Returns item from the list with min value.
5 list(seq)
Converts a tuple into list.

Python includes following list methods:

Sr. No. Methods with Description
1 list.append(obj)
Appends object obj to list
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.extend(seq)
Appends the contents of seq to list
4 list.index(obj)
Returns the lowest index in list that obj appears
5 list.insert(index, obj)
Inserts object obj into list at offset index
6 list.pop(obj=list[-1])
Removes and returns last object or obj from list
7 list.remove(obj)
Removes object obj from list
8 list.reverse()
Reverses objects of list in place
9 list.sort([func])
Sorts objects of list, use compare func if given

Tuples in Python

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

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example:

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing.

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.

Accessing Values in Tuples

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

#!/usr/bin/python

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 existing tuples to create new tuples as the following example demonstrates.

#!/usr/bin/python

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.

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example:

#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more.

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter.

Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
(‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 1 2 3 Iteration

Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input:

L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

No Enclosing Delimiters

Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples:

#!/usr/bin/python

print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;

When the above code is executed, it produces the following result:

abc -4.24e+93 (18+6.6j) xyz 
Value of x , y : 1 2 

Built-in Tuple Functions

Python includes the following tuple functions:

Serial No. Function with Description
1 cmp(tuple1, tuple2)
Compares elements of both tuples.
2 len(tuple)
Gives the total length of the tuple.
3 max(tuple)
Returns item from the tuple with max value.
4 min(tuple)
Returns item from the tuple with min value.
5 tuple(seq)
Converts a list into tuple.

Dictionary in Python

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example:

#!/usr/bin/python

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 part of the dictionary, we get an error as follows:

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

When the above code is executed, it produces the following result:

dict['Alice']:
Traceback (most recent call last):
   File "test.py", line 4, in 
      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 below in the simple example:

#!/usr/bin/python

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:

dict['Age']:  8
dict['School']:  DPS School

Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is a simple example

#!/usr/bin/python

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 that an exception is raised because after del dict dictionary does not exist any more:

dict['Age']:
Traceback (most recent call last):
   File "test.py", line 8, in 
      print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable

Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys

Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys −

(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during the assignment, the last assignment wins. For example:

#!/usr/bin/python

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. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key’] is not allowed. Following is a simple example:

#!/usr/bin/python

dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']

When the above code is executed, it produces the following result

Traceback (most recent call last):
   File "test.py", line 3, in 
      dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions:

Serial No. Function with Description
1 cmp(dict1, dict2)
Compares elements of both dict.
3 len(dict)
Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.
4 str(dict)
Produces a printable string representation of a dictionary
5 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

Python includes following dictionary methods

Serial No. Methods with Description
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict‘s (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict’s keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary dict2‘s key-values pairs to dict
10 dict.values()
Returns list of dictionary dict‘s values