Phyton 3 (1)
Phyton 3 (1)
Python 3.0 was released in 2008. Although this version is supposed to be backward
incompatibles, later on many of its important features have been backported to be
compatible with the version 2.7. This tutorial gives enough understanding on Python 3
version programming language. Please refer to this link for our Python 2 tutorial.
Audience
This tutorial is designed for software programmers who want to upgrade their Python skills
to Python 3. This tutorial can also be used to learn Python programming language from
scratch.
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
Try the following example using Try it option available at the top right corner of the below
sample code box −
#!/usr/bin/python3
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Python 3
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Execute Python Programs ................................................................................................................................ i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
ii
Python 3
8. Python 3 – Loops..................................................................................................................................... 51
while Loop Statements .................................................................................................................................. 52
for Loop Statements ...................................................................................................................................... 56
Nested loops .................................................................................................................................................. 59
Loop Control Statements ............................................................................................................................... 60
break statement ............................................................................................................................................ 61
continue Statement ....................................................................................................................................... 63
pass Statement .............................................................................................................................................. 65
Iterator and Generator .................................................................................................................................. 66
iii
Python 3
iv
Python 3
v
Python 3
vi
Python 3
vii
Python 3
viii
Python 3
ix
Python 3
x
Python 3
xi
Python 3
xii
Python 3
1
1. Python 3 – What is New? Python 3
For example, if we want Python 3.x's integer division behavior in Python 2, add the
following import statement.
The print() function inserts a new line at the end, by default. In Python 2, it can be
suppressed by putting ',' at the end. In Python 3, "end=' '" appends space instead of
newline.
In Python 2
>>> x=input('something:')
something:10 #entered data is treated as number
>>> x
10
>>> x=input('something:')
something:'10' #eentered data is treated as string
2
Python 3
>>> x
'10'
>>> x=raw_input("something:")
something:10 #entered data is treated as string even without ''
>>> x
'10'
>>> x=raw_input("something:")
something:'10' #entered data treated as string including ''
>>> x
"'10'"
In Python 3
>>> x=input("something:")
something:10
>>> x
'10'
>>> x=input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
>>> x=raw_input("something:") # will result NameError
Traceback (most recent call last):
File "", line 1, in
x=raw_input("something:")
NameError: name 'raw_input' is not defined
Integer Division
In Python 2, the result of division of two integers is rounded to the nearest integer. As a
result, 3/2 will show 1. In order to obtain a floating-point division, numerator or
denominator must be explicitly used as float. Hence, either 3.0/2 or 3/2.0 or 3.0/2.0 will
result in 1.5
Python 3 evaluates 3 / 2 as 1.5 by default, which is more intuitive for new programmers.
Unicode Representation
Python 2 requires you to mark a string with a u if you want to store it as Unicode.
Python 3 stores strings as Unicode, by default. We have Unicode (utf-8) strings, and 2
byte classes: byte and byte arrays.
3
Python 3
In Python 3, the range() function is removed, and xrange() has been renamed as range().
In addition, the range() object supports slicing in Python 3.2 and later .
raise exceprion
Python 2 accepts both notations, the 'old' and the 'new' syntax; Python 3 raises a
SyntaxError if we do not enclose the exception argument in parenthesis.
Arguments in Exceptions
In Python 3, arguments to exception should be declared with 'as' keyword.
2to3 Utility
Along with Python 3 interpreter, 2to3.py script is usually installed in tools/scripts folder.
It reads Python 2.x source code and applies a series of fixers to transform it into a valid
Python 3.x code.
a=area(10)
print "area",a
To convert into Python 3 version:
$2to3 -w area.py
Converted code :
def area(x,y=3.14): # formal parameters
a=y*x*x
print (a)
return a
a=area(10)
print("area",a)
5
2. Python 3 – Overview Python 3
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 1.0 was released in November 1994. In 2000, Python 2.0 was released.
Python 2.7.11 is the latest edition of Python 2.
Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible
with Python 2. The emphasis in Python 3 had been on the removal of duplicate
programming constructs and modules so that "There should be one -- and
preferably only one -- obvious way to do it." Python 3.5.1 is the latest version of
Python 3.
6
Python 3
Python Features
Python's features include-
Easy-to-learn: Python has few keywords, simple structure, and a clearly defined
syntax. This allows a student to pick up the language quickly.
Easy-to-read: Python code is more clearly defined and visible to the eyes.
A broad standard library: Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable: Python provides a better structure and support for large programs than
shell scripting.
Apart from the above-mentioned features, Python has a big list of good features. A few
are listed below-
It provides very high-level dynamic data types and supports dynamic type
checking.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
7
3. Python 3 – Environment Setup Python 3
Try the following example using our online compiler available at CodingGround
#!/usr/bin/python3
print ("Hello, Python!")
For most of the examples given in this tutorial, you will find a Try it option on our website
code sections, at the top right corner that will take you to the online compiler. Just use it
and enjoy your learning.
Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating
system. Even though Python 2 is available for many other OSs, Python 3 support either
has not been made available for them or has been dropped.
Getting Python
Windows platform
Binaries of latest version of Python 3 (Python 3.5.1) are available on this download page
Note:In order to install Python 3.5.1, minimum OS requirements are Windows 7 with SP1.
For versions 3.0 to 3.4.x, Windows XP is acceptable.
8
Python 3
Linux platform
Different flavors of Linux use different package managers for installation of new packages.
On Ubuntu Linux, Python 3 is installed using the following command from the terminal.
Mac OS
Download Mac OS installers from this URL:https://www.python.org/downloads/mac-osx/
Double click this package file and follow the wizard instructions to install.
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python:
You can download Python documentation from the following site. The documentation is
available in HTML, PDF and PostScript formats.
Setting up PATH
Programs and other executable files can be in many directories. Hence, the operating
systems provide a search path that lists the directories that it searches for executables.
9
Python 3
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.
Variable Description
10
Python 3
Running Python
There are three different ways to start Python-
$python # Unix/Linux
or
python% # Unix/Linux
or
C:>python # Windows/DOS
Option Description
11
Python 3
Windows: PythonWin is the first Windows interface for Python and is an IDE with
a GUI.
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.
If you are not able to set up the environment properly, then you can take the help of 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 3.4.1
version available on Windows 7 and Ubuntu Linux.
We have already set up Python Programming environment online, so that you can execute
all the available examples online while you are learning theory. Feel free to modify any
example and execute it online.
12
4. Python 3 – Basic Syntax Python 3
The Python language has many similarities to Perl, C, and Java. However, there are some
definite differences between the languages.
$ python
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
On Windows:
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
>>>
Type the following text at the Python prompt and press Enter-
If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result-
Hello, Python!
Let us write a simple Python program in a script. Python files have the extension.py. Type
the following source code in a test.py file-
13
Python 3
We assume that you have the Python interpreter set in PATH variable. Now, try to run
this program as follows-
On Linux
$ python test.py
Hello, Python!
On Windows
C:\Python34>Python test.py
Hello, Python!
Let us try another way to execute a Python script in Linux. Here is the modified test.py
file-
#!/usr/bin/python3
print ("Hello, Python!")
We assume that you have Python interpreter available in the /usr/bin directory. Now, try
to run this program as follows-
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.
Python is a case sensitive programming language. Thus, Manpower and manpower are
two different identifiers in Python.
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier
is private.
14
Python 3
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot
use them as constants or variables or any other identifier names. All the Python keywords
contain lowercase letters only.
as finally or
continue if return
del in while
elif is with
except
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example-
15
Python 3
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with the 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 the various blocks even if they are without braces.
#!/usr/bin/python3
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 = input("Enter filename: ")
if len(file_name) == 0:
print ("Next time please enter something")
16
Python 3
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, however, allows the use of
the line continuation character (\) to denote that the line should continue. For example-
total = item_one + \
item_two + \
item_three
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example-
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the
following are legal-
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All
characters after the #, up to the end of the physical line, are part of the comment and the
Python interpreter ignores them.
#!/usr/bin/python3
17
Python 3
# First comment
print ("Hello, Python!") # second comment
Hello, Python!
You can type a comment on the same line after a statement or expression-
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows-
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
In an interactive interpreter session, you must enter an empty physical line to terminate
a multiline statement.
#!/usr/bin/python3
input("\n\nPress the enter key to exit.")
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the
user presses the key, the program ends. This is a nice trick to keep a console window open
until the user is done with an application.
18
Python 3
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
$ 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 advance topic. Let us understand it.
The Python sys module provides access to any command-line arguments via
the sys.argv. This serves two purposes-
19
Python 3
Example
Consider the following script test.py-
#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
NOTE: As mentioned above, the first argument is always the script name and it is also
being counted in number of arguments.
getopt.getopt method
This method parses the command line options and parameter list. Following is a simple
syntax for this method-
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 (:).
This method returns a value consisting of two elements- the first is a list
of (option, value) pairs, the second is a list of program arguments left after the
option list was stripped.
20
Python 3
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
Suppose 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-
#!/usr/bin/python3
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:])
21
Python 3
$ 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 -o outputfile
Input file is " inputfile
Output file is " outputfile
22
5. Python 3 – Variable Types Python 3
Variables are nothing but reserved memory locations to store values. It means that when
you create a variable, you reserve some space in the 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 the
variables, you can store integers, decimals or characters in these variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example-
#!/usr/bin/python3
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and
name variables, respectively. This produces the following result −
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example-
a = b = c = 1
Here, an integer object is created with the value 1, and all the three variables are assigned
to the same memory location. You can also assign multiple objects to multiple variables.
23
Python 3
For example-
a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example-
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del 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
24
Python 3
All integers in Python 3 are represented as long integers. Hence, there is no separate
number type as long.
Examples
Here are some examples of numbers-
10 0.0 3.14j
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows either pair of single or double quotes. Subsets of strings
can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example-
#!/usr/bin/python3
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
25
Python 3
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Python Lists
Lists are the most versatile of Python's compound data types. A list contains items
separated by commas and enclosed within square brackets ([]). To some extent, lists are
similar to arrays in C. One of the differences between them is that all the items belonging
to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus
(+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example-
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
26
Python 3
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
parenthesis.
The main difference between lists and tuples is- 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/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −
#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
Python Dictionary
Python's dictionaries are kind of hash-table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.
27
Python 3
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]). For example-
#!/usr/bin/python3
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Dictionaries have no concept of order among the elements. It is incorrect to say that the
elements are "out of order"; they are simply unordered.
There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.
Function Description
28
Python 3
29
6. Python 3 – Basic Operators Python 3
Operators are the constructs, which can manipulate the value of operands. Consider the
expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called the operator.
Types of Operator
Python language supports the following types of operators-
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
30
Python 3
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print ("Line 2 - Value of c is ", c )
c = a * b
print ("Line 3 - Value of c is ", c)
c = a / b
print ("Line 4 - Value of c is ", c )
c = a % b
print ("Line 5 - Value of c is ", c)
a = 2
b = 3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b = 5
c = a//b
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 11
31
Python 3
Assume variable a holds the value 10 and variable b holds the value 20, then-
(a == b)
If the values of two operands are equal, then the condition
== is not
becomes true.
true.
If the value of left operand is greater than the value of right (a > b) is
>
operand, then condition becomes true. not true.
If the value of left operand is less than the value of right (a < b) is
<
operand, then condition becomes true. true.
(a >= b)
If the value of left operand is greater than or equal to the
>= is not
value of right operand, then condition becomes true.
true.
If the value of left operand is less than or equal to the value (a <= b)
<=
of right operand, then condition becomes true. is true.
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
32
Python 3
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")
if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")
if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")
When you execute the above program, it produces the following result-
33
Python 3
//= Floor Division It performs floor division on operators and c //= a is equivalent
assign value to the left operand to c = c // a
Example
Assume variable a holds 10 and variable b holds 20, then-
#!/usr/bin/python3
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
34
Python 3
c /= a
print ("Line 4 - Value of c is ", c )
c = 2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result-
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
Pyhton's built-in function bin() can be used to obtain binary representation of an integer
number.
35
Python 3
& Binary AND Operator copies a bit to the result, if it (a & b) (means 0000
exists in both operands 1100)
~ Binary Ones It is unary and has the effect of 'flipping' (~a ) = -61 (means
Complement bits. 1100 0011 in 2's
complement form
due to a signed
binary number.
<< Binary Left Shift The left operand’s value is moved left by a << = 240 (means
the number of bits specified by the right 1111 0000)
operand.
>> Binary Right Shift The left operand’s value is moved right a >> = 15 (means
by the number of bits specified by the 0000 1111)
right operand.
Example
#!/usr/bin/python3
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0
c = a | b; # 61 = 0011 1101
print ("result of OR is ", c,':',bin(c))
36
Python 3
c = a ^ b; # 49 = 0011 0001
print ("result of EXOR is ", c,':',bin(c))
When you execute the above program, it produces the following result-
a= 60 : 0b111100 b= 13 : 0b1101
result of AND is 12 : 0b1100
result of OR is 61 : 0b111101
result of EXOR is 49 : 0b110001
result of COMPLEMENT is -61 : -0b111101
result of LEFT SHIFT is 240 : 0b11110000
result of RIGHT SHIFT is 15 : 0b111
and Logical If both the operands are true then condition (a and b) is
AND becomes true. False.
not Logical NOT Used to reverse the logical state of its operand. Not(a and b)
is True.
37
Python 3
Example
#!/usr/bin/python3
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
print ("Line 2 - b is available in the given list")
c=b/a
if ( c in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
38
Python 3
When you execute the above program, it produces the following result-
Example
#!/usr/bin/python3
a = 20
b = 20
print ('Line 1','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is b ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
39
Python 3
b = 30
print ('Line 4','a=',a,':',id(a), 'b=',b,':',id(b))
if ( a is not b ):
print ("Line 5 - a and b do not have same identity")
else:
print ("Line 5 - a and b have same identity")
When you execute the above program, it produces the following result-
Operator Description
40
Python 3
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because the operator * has
higher precedence than +, so it first multiplies 3*2 and then is added to 7.
Here, the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.
Example
#!/usr/bin/python3
a = 20
b = 10
c = 15
d = 5
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-
41
Python 3
42
7. Python 3 – Decision Making Python 3
Decision structures evaluate multiple expressions, which produce TRUE or FALSE as the
outcome. You need to determine which action to take and which statements to execute if
the outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages-
Python programming language assumes any non-zero and non-null values as TRUE, and
any zero or null values as FALSE value.
Statement Description
43
Python 3
IF Statement
The IF statement is similar to that of other languages. The if statement contains a logical
expression using which the data is compared and a decision is made based on the result
of the comparison.
Syntax
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. In Python, statements in a block are uniformly indented after the
: symbol. If boolean expression evaluates to FALSE, then the first set of code after the
end of block is executed.
Flow Diagram
Example
#!/usr/bin/python3
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
44
Python 3
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
IF...ELIF...ELSE Statements
An else statement can be combined with an if statement. An else statement contains a
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 the most only
one else statement following if.
Syntax
The syntax of the if...else statement is-
if expression:
statement(s)
else:
statement(s)
45
Python 3
Flow Diagram
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)
In the above example, discount is calculated on the input amount. Rate of discount is 5%,
if the amount is less than 1000, and 10% if it is above 10000. When the above code is
executed, it produces the following result-
Similar to the else, the elif statement is optional. However, unlike else, for which there
can be at the most one statement, there can be an arbitrary number of elif statements
following an if.
Syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Core Python does not provide switch or case statements as in other languages, but we can
use if..elif...statements to simulate switch case as follows-
Example
#!/usr/bin/python3
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)
print ("Net payable:",amount-discount)
47
Python 3
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.
Syntax
The syntax of the nested if...elif...else construct may be-
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Example
# !/usr/bin/python3
num=int(input("enter number"))
48
Python 3
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
enter number5
not Divisible by 2 not divisible by 3
#!/usr/bin/python3
var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")
50
8. Python 3 – Loops Python 3
Programming languages provide various control structures that allow more complicated
execution paths.
Python programming language provides the following types of loops to handle looping
requirements.
51
Python 3
nested loops You can use one or more loop inside any another while, or
for loop.
Syntax
The syntax of a while loop in Python programming language is-
while expression:
statement(s)
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
52
Python 3
Here, a key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.
Example
#!/usr/bin/python3
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
53
Python 3
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.
An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.
#!/usr/bin/python3
var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")
54
Python 3
The above example goes in an infinite loop and you need to use CTRL+C to exit the
program.
If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
The following example illustrates the combination of an else statement with a while
statement that prints a number as long as it is less than 5, otherwise the else statement
gets executed.
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
#!/usr/bin/python3
flag = 1
while (flag): print ('Given flag is really true!')
print ("Good bye!")
The above example goes into an infinite loop and you need to press CTRL+C keys to exit.
55
Python 3
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
56
Python 3
>>> range(5)
range(0, 5)
>>> list(range(5))
[0, 1, 2, 3, 4]
range() generates an iterator to progress integers starting with 0 upto n-1. To obtain a
list object of the sequence, it is typecasted to list(). Now this list can be iterated using the
for statement.
0
1
2
3
4
Example
#!/usr/bin/python3
for letter in 'Python': # traversal of a string sequence
print ('Current Letter :', letter)
print()
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)
Current Letter : P
Current Letter : y
57
Python 3
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
#!/usr/bin/python3
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print ("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.
If the else statement is used with a for loop, the else block is executed only if for
loops terminates normally (and not by encountering break statement).
If the else statement is used with a while loop, the else statement is executed
when the condition becomes false.
58
Python 3
The following example illustrates the combination of an else statement with a for
statement that searches for even number in given list.
#!/usr/bin/python3
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list doesnot contain even number')
Nested loops
Python programming language allows the use of one loop inside another loop. The
following section shows a 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 any other type of
loop. For example a for loop can be inside a while loop or vice versa.
Example
The following program uses a nested-for loop to display multiplication tables from 1-10.
#!/usr/bin/python3
import sys
59
Python 3
for i in range(1,11):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()
The print() function inner loop has end=' ' which appends a space instead of default
newline. Hence, the numbers will appear in one row.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
60
Python 3
break statement
The break statement is used for premature termination of the current loop. After
abandoning the loop, execution at the next statement is resumed, just like the traditional
break statement in C.
The most common use of break is when some external condition is triggered requiring a
hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost
loop and starts executing the next line of the code after the block.
Syntax
The syntax for a break statement in Python is as follows-
break
Flow Diagram
61
Python 3
Example
#!/usr/bin/python3
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
Current Letter : P
Current Letter : y
Current Letter : t
62
Python 3
The following program demonstrates the use of break in a for loop iterating over a list.
User inputs a number, which is searched in the list. If it is found, then the loop terminates
with the 'found' message.
#!/usr/bin/python3
no=int(input('any number: '))
numbers=[11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num==no:
print ('number found in list')
break
else:
print ('number not found in list')
any number: 33
number found in list
any number: 5
number not found in list
continue Statement
The continue statement in Python returns the control to the beginning of the current loop.
When encountered, the loop starts next iteration without executing the remaining
statements in the current iteration.
The continue statement can be used in both while and for loops.
Syntax
continue
63
Python 3
Flow Diagram
Example
#!/usr/bin/python3
Current Letter : P
64
Python 3
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
pass Statement
It is used when a statement is required syntactically but you do not want any command
or code to execute.
The pass statement is a null operation; nothing happens when it executes. The
pass statement is also useful in places where your code will eventually go, but has not
been written yet i.e. in stubs).
Syntax
pass
Example
#!/usr/bin/python3
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
list=[1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
Iterator object can be traversed using regular for statement
!usr/bin/python3
for x in it:
print (x, end=" ")
or using next() function
while True:
try:
print (next(it))
except StopIteration:
sys.exit() #you have to import sys module for this
A generator is a function that produces or yields a sequence of values using yield method.
When a generator function is called, it returns a generator object without even beginning
execution of the function. When the next() method is called for the first time, the function
starts executing, until it reaches the yield statement, which returns the yielded value. The
yield keeps track i.e. remembers the last execution and the second next() call continues
from previous value.
The following example defines a generator, which generates an iterator for all the Fibonacci
numbers.
!usr/bin/python3
66
Python 3
import sys
def fibonacci(n): #generator function
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5) #f is iterator object
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
67
9. Python 3 – Numbers Python 3
Number data types store numeric values. They are immutable data types. This means,
changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example-
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The
syntax of the del statement is −
del 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
int (signed integers): They are often called just integers or ints. They are
positive or negative whole numbers with no decimal point. Integers in Python 3 are
of unlimited size. Python 2 has two integer types - int and long. There is no 'long
integer' in Python 3 anymore.
float (floating point real values) : Also called floats, they represent real
numbers and are written with a decimal point dividing the integer and the fractional
parts. Floats may also be in scientific notation, with E or e indicating the power of
10 (2.5e2 = 2.5 x 102 = 250).
complex (complex numbers) : are of the form a + bJ, where a and b are floats
and J (or j) represents the square root of -1 (which is an imaginary number). The
real part of the number is a, and the imaginary part is b. Complex numbers are not
used much in Python programming.
68