KEMBAR78
Python DR Abikoye | PDF | Control Flow | Python (Programming Language)
0% found this document useful (0 votes)
12 views65 pages

Python DR Abikoye

Python note

Uploaded by

lovelizzydee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views65 pages

Python DR Abikoye

Python note

Uploaded by

lovelizzydee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

7.

PYTHON
7.1 Basics of Python
 Python is a powerful high-level, object-oriented programming language created by Guido
van Rossum.
 It has simple easy-to-use syntax, making it the perfect language for someone trying to
learn computer programming for the first time.
 Python is a general-purpose language.
 It has wide range of applications from Web development (like: Django and Bottle),
scientific and mathematical computing (Orange, SymPy, NumPy) to desktop graphical
user Interfaces (Pygame, Panda3D).
 The syntax of the language is clean and length of the code is relatively short. It's fun to
work in Python because it allows you to think about the problem rather than focusing on
the syntax.
7.1.1 History of Python
Python is a fairly old language created by Guido Van Rossum. The design began in the late
1980s and was first released in February 1991. In late 1980s, Guido Van Rossum was working
on the Amoeba distributed operating system group. He wanted to use an interpreted language
like ABC (ABC has simple easy-to-understand syntax) that could access the Amoeba system
calls. So, he decided to create a language that was extensible. This led to a design of new
language which was later named Python. The word Python is not a name after a dangerous
snake. Rossum was fan of a comedy series from late seventies. The name "Python" was adopted
from the same series "Monty Python's Flying Circus".
Release Dates of Different Versions
Version Release Data
Python 1.0 (first standard release) January 1994
Python 1.6 (Last minor version) September 5, 2000
Python 2.0 (Introduced list comprehensions) October 16, 2000
Python 2.7 (Last minor version) July 3, 2010
Python 3.0 (Emphasis on removing duplicative constructs and module) December 3, 2008
Python 3.5 (Last updated version) September 13, 2015
7.1.2 Features of Python Programming
1. A simple language which is easier to learn
Python has a very simple and elegant syntax. It's much easier to read and write Python
programs compared to other languages like: C++, Java, C#. Python makes programming
fun and allows you to focus on the solution rather than syntax.

2. Free and open-source


Python can freely be used and distributed, even for commercial use. Not only can you use
and distribute softwares written in it, you can even make changes to the Python's source
code. Python has a large community constantly improving it in each iteration.
3. Portability
You can move Python programs from one platform to another, and run it without any
changes. It runs seamlessly on almost all platforms including Windows, Mac OS X and
Linux.
4. Extensible and Embeddable
Suppose an application requires high performance. You can easily combine pieces of
C/C++ or other languages with Python code. This will give your application high
performance as well as scripting capabilities which other languages may not provide out
of the box.
5. A high-level, interpreted language
Unlike C/C++, you don't have to worry about daunting tasks like memory management,
garbage collection and so on. Likewise, when you run Python code, it automatically
converts your code to the language your computer understands. You don't need to worry
about any lower-level operations.
6. Large standard libraries to solve common tasks
Python has a number of standard libraries which makes life of a programmer much easier
since you don't have to write all the code yourself. For example: Need to connect MySQL
database on a Web server? You can use MySQLdb library using import MySQLdb .
Standard libraries in Python are well tested and used by hundreds of people. So you can
be sure that it won't break your application.
7. Object-oriented
Everything in Python is an object. Object oriented programming (OOP) helps you solve a
complex problem intuitively. With OOP, you are able to divide these complex problems
into smaller sets by creating objects.
7.1.3 Applications of Python
Web Applications
You can create scalable Web Apps using frameworks and CMS (Content Management System)
that are built on Python. Some of the popular platforms for creating Web Apps are: Django,
Flask, Pyramid, Plone, Django CMS.
Sites like Mozilla, Reddit, Instagram and PBS are written in Python.
Scientific and Numeric Computing
There are numerous libraries available in Python for scientific and numeric computing. There are
libraries like: SciPy and NumPy that are used in general purpose computing. And, there are
specific libraries like: EarthPy for earth science, AstroPy for Astronomy and so on.
Also, the language is heavily used in machine learning, data mining and deep learning.
Creating software Prototypes
Python is slow compared to compiled languages like C++ and Java. It might not be a good
choice if resources are limited and efficiency is a must.
However, Python is a great language for creating prototypes. For example: You can use Pygame
(library for creating games) to create your game's prototype first. If you like the prototype, you
can use language like C++ to create the actual game.
Good Language to Teach Programming
Python is used by many companies to teach programming to kids and newbies.
It is a good language with a lot of features and capabilities. Yet, it's one of the easiest language to
learn because of its simple easy-to-use syntax.

7.1.4 4 Reasons to Choose Python as First Language


1. Simple Elegant Syntax
Programming in Python is fun. It's easier to understand and write Python code. The
syntax feels natural. Take this source code for an example:
a = 2
b = 3
sum = a + b
print(sum)
Even if you have never programmed before, you can easily guess that this program adds
two numbers and prints it.
2. Not overly strict
You don't need to define the type of a variable in Python. Also, it's not necessary to add
semicolon at the end of the statement.
Python enforces you to follow good practices (like proper indentation). These small
things can make learning much easier for beginners.
3. Expressiveness of the language
Python allows you to write programs having greater functionality with fewer lines of
code.
4. Great Community and Support
Python has a large supporting community.
7.1.5 Install and Run Python in Windows
1. Go to Download Python page on the official site and click Download Python 3.6.0 (You
may see different version name).
2. When the download is completed, double-click the file and follow the instructions to
install it.
When Python is installed, a program called IDLE is also installed along with it. It
provides graphical user interface to work with Python.
3. Open IDLE, copy the following code below and press enter.
4. print("Hello, World!")
5. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
6. Write Python code (you can copy the code below for now) and save (Shortcut: Ctrl+S)
with .py file extension like: hello.py or your-first-program.py
print("Hello, World!")
7. Go to Run > Run module (Shortcut: F5) and you can see the output. Congratulations,
you've successfully run your first Python program.

7.2 Introduction to Python Programming


7.2.1 Python Keywords & Identifier
Python keywords
 Keywords are the reserved words in Python.
 Keywords cannot be used as variable name , Function name or any other identifier. They
are used to define the syntax and structure of the Python language.
 In Python, keywords are case sensitive.
 There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
 All the keywords except True, False and None are in lowercase and they must be written
as it is. The list of all the keywords are given below.
Keywords in Python programming language

False Class finally is return

None Continue for lambda try

True Def from nonlocal while

and Del global not with

as Elif if or yield

assert Else import pass

break Except in raise

Python Identifiers
Identifier is the name given to entities like class, functions, variables etc. in Python, it helps to
differentiate one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore (_). Names like myClass, var_1 and print_this_to_screen,
all are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
>>> global = 1
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

>>> a@ = 0
File "<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax
5. Identifier can be of any length.

Python is a case-sensitive language. This means, Variable and variable are not the same. Always
name identifiers that make sense.
While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier
to figure out what it does even when you look at your code after a long gap.
Multiple words can be separated using an underscore, this_is_a_long_variable.
We can also use camel-case style of writing, i.e., capitalize every first letter of the word except
the initial word without any spaces. For example: camelCaseExample

7.2.2 Python Statement, Indentation and Comments


Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an
assignment statement. if statement, for statement, while statement etc. are other kinds of
statements which will be discussed later.
Multi-line statement
In Python, end of a statement is marked by a newline character. But we can make a statement
extend over multiple lines with the line continuation character (\). For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ] and braces { }. For instance, we can implement the above multi-line statement as
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ]
and { }. For example:
colors = ['red',
'blue',
'green']
We could also put multiple statements in a single line using semicolons, as follows
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of code.
Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and
ends with the first unindented line. The amount of indentation is up to you, but it must be
consistent throughout that block.
Generally four whitespaces are used for indentation and is preferred over tabs. Here is an
example.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results into
Python programs that look similar and consistent. Indentation can be ignored in line
continuation. But it's a good idea to always indent. It makes the code more readable. For
example:
if True:
print('Hello')
a = 5
and
if True: print('Hello'); a = 5
both are valid and do the same thing. But the former style is clearer. Incorrect indentation will
result into IndentationError.
Python Comments
Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month's time. So taking time
to explain these concepts in form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment. It extends up to the newline
character. Comments are for programmers for better understanding of a program. Python
Interpreter ignores comment.
#This is a comment
#print out Hello
print('Hello')

Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""

Docstring in Python
Docstring is short for documentation string. It is a string that occurs as the first statement in a
module, function, class, or method definition. We must write what a function/class does in the
docstring. Triple quotes are used while writing docstrings. For example:

def double(num):
"""Function to double the value"""
return 2*num

Docstring is available to us as the attribute __doc__ of the function

7.2.3 Python Variables and Data Types


Python Variables
A variable is a location in memory used to store some data (value). They are given unique names
to differentiate between different memory locations. The rules for writing a variable name is
same as the rules for writing identifiers in Python.
We don't need to declare a variable before using it. In Python, we simply assign a value to a
variable and it will exist. We don't even have to declare the type of the variable. This is handled
internally according to the type of value we assign to the variable.
Variable assignment
We use the assignment operator (=) to assign values to a variable. Any type of value can be
assigned to any valid variable.
a = 5
b = 3.2
c = "Hello"
Here, we have three assignment statements. 5 is an integer assigned to the variable a.
Similarly, 3.2 is a floating point number and "Hello" is a string (sequence of characters)
assigned to the variables b and c respectively.
Multiple assignments
In Python, multiple assignments can be made in a single statement as follows:
a, b, c = 5, 3.2, "Hello"
If we want to assign the same value to multiple variables at once, we can do this as
x = y = z = "same"
This assigns the "same" string to all the three variables.
Data types in Python
Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.There are various
data types in Python. Some of the important types are listed below.
1. Python Numbers
Integers, floating point numbers and complex numbers falls under Python numbers category.
They are defined as int, float and complex class in Python.
We can use the type() function to know which class a variable or a value belongs to and the
isinstance() function to check if an object belongs to a particular class.

a = 5
print(a, "is of type", type(a))

a = 2.0
print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output:
5 is of type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is complex number? True

Integers can be of any length, it is only limited by the memory available. A floating point
number is accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number. Complex numbers are written in the form, x +
yj, where x is the real part and y is the imaginary part. Here are some examples.
>>> a = 1234567890123456789
>>> a
1234567890123456789
>>> b = 0.1234567890123456789
>>> b
0.12345678901234568
>>> c = 1+2j
>>> c
(1+2j)
Notice that the float variable b got truncated.
2. Python List
List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type. Declaring a list is pretty
straight forward. Items separated by commas are enclosed within brackets [ ].
>>> a = [1, 2.2, 'python']
We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.
a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]


print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]


print("a[5:] = ", a[5:])

Output:
a[2] = 15
a[0:3] = [5, 10, 15]
a[5:] = [30, 35, 40]
Lists are mutable, meaning, value of elements of a list can be altered.
>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]

3. Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and
are usually faster than list as it cannot change dynamically. It is defined within parentheses ()
where items are separated by commas.
>>> t = (5,'program', 1+3j)
We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))


print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10

4. Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, ''' or """.
>>> s = "This is a string"
>>> s = '''a multiline

Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.

s = 'Hello world!'

# s[4] = 'o'
print("s[4] = ", s[4])

# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])
# Generates error
# Strings are immutable in Python
s[5] ='d'

Output:
s[4] = o
s[6:11] = world

5. Python Set
Set is an unordered collection of unique items. Set is defined by values separated by comma
inside braces { }. Items in a set are not ordered.
a = {5,2,3,1,4}

# printing set variable


print("a = ", a)

# data type of variable a


print(type(a))

Output:
a = {1, 2, 3, 4, 5}
<class 'set'>

We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates.
>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does
not work.
>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: 'set' object does not support indexing

6. Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a
huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to
retrieve the value. In Python, dictionaries are defined within braces {} with each item being a
pair in the form key:value. Key and value can be of any type.
>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>

We use key to retrieve the respective value. But not the other way around.
d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error
print("d[2] = ", d[2]);

Output:
<class 'dict'>
d[1] = value
d['key'] = 2

Traceback (most recent call last):


File "<stdin>", line 9, in <module>
print("d[2] = ", d[2]);
KeyError: 2

Conversion between data types


We can convert between different data types by using different type conversion functions like
int(), float(), str() etc.
>>> float(5)
5.0

Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10

Conversion to and from string must contain compatible values.


>>> float('2.5')
2.5
>>> str(25)
'25'
>>> int('1p')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.


>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair


>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

7.2.4 Python Input, Output and Import


Python provides numerous built-in functions that are readily available to us at the Python
prompt. Some of the functions like input() and print() are widely used for standard input and
output operations respectively.
Python Output Using print() function
We use the print() function to output data to the standard output device (screen). We can also
output data to a file. An example use is given below.
print('This sentence is output to the screen')
# Output: This sentence is output to the screen

a = 5

print('The value of a is', a)


# Output: The value of a is 5

Output:
This sentence is output to the screen
The value of a is 5

In the second print() statement, we can notice that a space was added between the string and the
value of variable a. This is by default, but we can change it.

The actual syntax of the print() function is


print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed. The sep separator is used between the values. It
defaults into a space character. After all values are printed, end is printed. It defaults into a new
line.

The file is the object where the values are printed and its default value is sys.stdout (screen).

Here are an example to illustrate this.


print(1,2,3,4)
# Output: 1 2 3 4

print(1,2,3,4,sep='*')
# Output: 1*2*3*4

print(1,2,3,4,sep='#',end='&')
# Output: 1#2#3#4&

Output:

1 2 3 4
1*2*3*4
1#2#3#4&

Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the order in which it is printed
by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))


# Output: I love bread and butter

print('I love {1} and {0}'.format('bread','butter'))


# Output: I love butter and bread

Output:

I love bread and butter


I love butter and bread
We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name =


'John'))
Hello John, Goodmorning

We can even format strings like the old sprintf() style used in C programming language. We
use the % operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

Python Input

Up till now, our programs were static. The value of variables were defined or hard coded into the
source code. To allow flexibility we might want to take the input from the user. In Python, we
have the input() function to allow this. The syntax for input() is

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')


Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a
number we can use int() or float() functions.

>>> int('10')
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But it takes it further. It can
evaluate even expressions, provided the input is a string
>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5
Python Import
When our program grows bigger, it is a good idea to break it into different modules. A module is
a file containing Python definitions and statements. Python modules have a filename and end
with the extension .py. Definitions inside a module can be imported to another module or the
interactive interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing in import math.

import math
print(math.pi)

Output:
3.141592653589793

Now all the definitions inside math module are available in our scope. We can also import some
specific attributes and functions only, using the from keyword. For example:

>>> from math import pi


>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list of
directory locations.
>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

7.2.5 Python Operators


Operators are special symbols in Python that carry out arithmetic or logical computation. The
value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation. Python has a number of operators which are classified below.
Type of operators in Python

Arithmetic operators

Comparison (Relational) operators

Logical (Boolean) operators

Bitwise operators

Assignment operators

Special operators

1. Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.
Arithmetic operators in Python

Operator Meaning Example

x+y
+ Add two operands or unary plus
+2

x-y
- Subtract right operand from the left or unary minus
-2

* Multiply two operands x*y

/ Divide left operand by the right one (always results into float) x/y

x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)

Floor division - division that results into whole number adjusted to the
// x // y
left in the number line

x**y (x to the power


** Exponent - left operand raised to the power of right
y)

Example #1: Arithmetic operators in Python


x = 15
y = 4

# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)

When you run the program, the output will be:


x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

2. Comparison operators
Comparison operators are used to compare values. It either returns True or False according to
the condition.
Comparision operators in Python

Operator Meaning Example

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y

<= Less than or equal to - True if left operand is less than or equal to the right x <= y

Example #2: Comparison operators in Python


x = 10
y = 12

# Output: x > y is False


print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

# Output: x == y is False
print('x == y is',x==y)

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)

Output:
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True

3. Logical operators
Logical operators are the and, or, not operators.
Logical operators in Python

Operator Meaning Example

And True if both the operands are true x and y

Or True if either of the operands is true x or y

Not True if operand is false (complements the operand) not x

Example #3: Logical Operators in Python


x = True
y = False

# Output: x and y is False


print('x and y is',x and y)

# Output: x or y is True
print('x or y is',x or y)

# Output: not x is False


print('not x is',not x)
Output:
x and y is False
x or y is True
not x is False

4. Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit,
hence the name. For example, 2 is 10 in binary and 7 is 111.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Bitwise operators in Python

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 42 (0010 1000)

5. Assignment operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and later
assigns the same. It is equivalent to a = a + 5.
Assignment operators in Python

Operator Example Equivatent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5
%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

&= x &= 5 x=x&5

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

6. Special operators
Python language offers some special type of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values (or

variables) are located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
Identity operators in Python

Operator Meaning Example

Is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True

Example #4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)

Output:
False
True
False

Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical.
Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable (can be changed),
interpreter locates them separately in memory although they are equal.

Membership operators
in and not in are the membership operators in Python. They are used to test whether a value or

variable is found in a sequence (string, list, tuple, set and dictionary). In a dictionary we can only
test for presence of key, not the value.
Operator Meaning Example

In True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

Example #5: Membership operators in Python


x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)

Output:
True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive). Similary,
1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.

7.2.6 Precedence and Associativity of Operators in Python


Precedence of Python Operators
The combination of values, variables, operators and function calls is termed as an expression.
Python interpreter can evaluate a valid expression.
For example:
>>> 5 - 7
-2
Here 5 - 7 is an expression. There can be more than one operator in an expression. To evaluate
these type of expressions there is a rule of precedence in Python. It guides the order in which
operation are carried out.
For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence


# than subtraction
# Output: 2
10 - 4 * 2

Output:
Out[1]: 2

But we can change this order using parentheses () as it has higher precedence.
# Parentheses () has higher precendence
# Output: 12
(10 - 4) * 2

Output:
Out[1]: 12

The operator precedence in Python are listed in the following table. It is in descending order,
upper group has higher precedence than the lower ones.
Operator precedence rule in Python

Operators Meaning

() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators

Not Logical NOT

And Logical AND

Or Logical OR

Associativity of Python Operators


We can see in the above table that more than one operator exists in the same group. These
operators have the same precedence. When two operators have the same precedence,
associativity helps to determine which the order of operations.

Associativity is the order in which an expression is evaluated that has multiple operator of the
same precedence. Almost all the operators have left-to-right associativity.
For example, multiplication and floor division have the same precedence. Hence, if both of them
are present in an expression, left one is evaluated first.
# Left-right associativity
# Output: 3
print(5 * 2 // 3)

# Shows left-right associativity


# Output: 0
print(5 * (2 // 3))
Output:
3
0

Exponent operator ** has right-to-left associativity in Python.


# Right-left associativity of ** exponent operator
# Output: 512
print(2 ** 3 ** 2)

# Shows the right-left associativity


# of **
# Output: 64
print((2 ** 3) ** 2)

Output:
512
64

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).


Non associative operators
Some operators like assignment operators and comparison operators do not have associativity in
Python. There are separate rules for sequences of this kind of operator and cannot be expressed
as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y < z). x < y < z is
equivalent to x < y and y < z, and is evaluates from left-to-right.
Furthermore, while chaining of assignments like x = y = z is perfectly valid, x = y += z will
result into error.

7.3 Python Flow control

7.3.1 Python if...else Statement


There are many ways to create decisions in a Python program using different forms of if..else statement.
Decision making is required when we want to execute a code only if a certain condition is
satisfied.

The if…elif…else statement is used in Python for decision making.

7.3.2 Python if Statement Syntax

if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.

If the text expression is False, the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. Body starts with an
indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart


Example: Python if Statement

When you run the program, the output will be:

3 is a positive number
This is always printed
This is also always printed.

In the above example, num > 0 is the test expression.

The body of if is executed only if this evaluates to True.

When variable num is equal to 3, test expression is true and body inside body of if is executed.

If variable num is equal to -1, test expression is false and body inside body of if is skipped.

The print() statement falls outside of the if block (unindented). Hence, it is executed
regardless of the test expression.

7.3.4 Python if...else Statement

Syntax of if...else
if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only when
test condition is True.

If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Python if..else Flowchart

Example of if...else

In the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.
If num is equal to -5, the test expression is false and body of else is executed and body of if is
skipped.

If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.

7.3.5 Python if...elif...else

Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple expressions.

If the condition for if is False, it checks the condition of the next elif block and so on.

If all the conditions are False, body of else is executed.

Only one block among the several if...elif...else blocks is executed according to the
condition.

The if block can have only one else block. But it can have multiple elif blocks.

Flowchart of if...elif...else
Example of if...elif...else

When variable num is positive, Positive number is printed.


If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed

7.3.6 Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This


is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to
figure out the level of nesting. This can get confusing, so must be avoided if we can.

Python Nested if Example


# In this program, we input a number
# check if the number is positive or
# negative or zero and display
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1

Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number

Output 3

Enter a number: 0
Zero

7.3.6 Python for Loop


The for loop in Python is used to iterate over a sequence (list, tuple, String) or other iterable
objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:


Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Flowchart of for Loop

Example: Python for Loop

when you run the program, the output will be:

The sum is 48

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start,stop,step size). step size
defaults to 1 if not provided.
This function does not store all the values in memory, it would be inefficient. So it remembers
the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().

The following example will clarify this.

We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an
example.
When you run the program, the output will be:

I like pop
I like rock
I
​ like jazz
for loop with else
A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.
Hence, a for loop's else part runs if no break occurs.
Here is an example to illustrate this.

When you run the program, the output will be:

0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it
executes the block of code in the else and prints

No items left.

7.3.7 Python while Loop


Loops are used in programming to repeat a specific block of code.

The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

We generally use this loop when we don't know beforehand, the number of times to iterate.

Syntax of while Loop in Python

while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked again.
This process continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through indentation.

Body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Flowchart of while Loop

Example: Python while Loop


When you run the program, the output will be:

Enter n: 10
The sum is 55

In the above program, the test expression will be True as long as our counter variable i is less
than or equal to n (10 in our program).

We need to increase the value of counter variable in the body of the loop. This is very important
(and mostly forgotten). Failing to do so will result in an infinite loop (never ending loop).

Finally the result is displayed.

while loop with else

Same as that of for loop, we can have an optional else block with while loop as well.

The else part is executed if the condition in the while loop evaluates to False. The while loop
can be terminated with a break statement.

In such case, the else part is ignored. Hence, a while loop's else part runs if no break occurs
and the condition is false.

Here is an example to illustrate this.


Output

Inside loop
Inside loop
Inside loop
Inside else

Here, we use a counter variable to print the string Inside loop three times.

On the forth iteration, the condition in while becomes False. Hence, the else part is executed.

7.3.8 Python break and continue


In Python, break and continue statements can alter the flow of a normal loop. Loops iterate over
a block of code until test expression is false, but sometimes we wish to terminate the current
iteration or even the whole loop without checking test expression. The break and continue
statements are used in these cases.

Python break statement


The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop. If break statement is inside a nested loop (loop
inside another loop), break will terminate the innermost loop.

Syntax of break
break

Flowchart of break
The working of break statement in for loop and while loop shown below.
Example: Python break

Output

s
t
r
The end

In this program, we iterate through the "string" sequence. We check if the letter is "i", upon
which we break from the loop. Hence, we see in our output that all the letters up till "i" gets
printed. After that, the loop terminates.
Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration
only. Loop does not terminate but continues on with the next iteration.

Syntax of Continue
continue

Flowchart of continue

The working of continue statement in for and while loop is shown below.
Example: Python continue

Output

s
t
r
n
g
The end

This program is same as the above example except the break statement has been replaced with
continue.

We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we see
in our output that all the letters except "i" gets printed.

7.4 Python pass statement


Pass statement. It is used as a placeholder for future implementation of functions, loops, etc.
In Python programming, pass is a null statement. The difference between a comment and Pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.

However, nothing happens when pass is executed. It results into no operation (NOP).

Syntax of pass

pass
We generally use it as a placeholder. Suppose we have a loop or a function that is not
implemented yet, but we want to implement it in the future. They cannot have an empty body.
The interpreter would complain. So, we use the pass statement to construct a body that does
nothing.

Example: pass Statement

We can do the same thing in an empty function or class as well.

def function(args):
pass
class example:
pass

7.5 Python Looping Techniques


Python programming offers two kinds of loop, the for loop and the while loop. Using these loops
along with loop control statements like break and continue, we can create various forms of loop.
7.5.1 The infinite loop
We can create an infinite loop using while statement. If the condition of while loop is always
True, we get an infinite loop.

Example #1: Infinite loop using while


# An example of infinite loop
# press Ctrl + c to exit from the loop

while True:
num = int(input("Enter an integer: "))
print("The double of",num,"is",2 * num)

Output

Enter an integer: 3
The double of 3 is 6
Enter an integer: 5
The double of 5 is 10
Enter an integer: 6
The double of 6 is 12
Enter an integer:
Traceback (most recent call last):

7.5.2 Loop with condition at the top


This is a normal while loop without break statements. The condition of the while loop is at the
top and the loop terminates when this condition is False.

Flowchart of Loop With Condition at Top


Example #2: Loop with condition at the top

When you run the program, the output will be:

The sum is 55

7.5.3 Loop with condition in the middle


This kind of loop can be implemented using an infinite loop along with a conditional break in
between the body of the loop.

Flowchart of Loop with Condition in Middle


Example #3: Loop with condition in the middle
# Program to illustrate a loop with condition in the middle.
# Take input from the user untill a vowel is entered

vowels = "aeiouAEIOU"

# infinite loop
while True:
v = input("Enter a vowel: ")
# condition in the middle
if v in vowels:
break
print("That is not a vowel. Try again!")

print("Thank you!")

Output

Enter a vowel: r
That is not a vowel. Try again!
Enter a vowel: 6
That is not a vowel. Try again!
Enter a vowel: ,
That is not a vowel. Try again!
Enter a vowel: u
Thank you!

7.5.4 Loop with condition at the bottom


This kind of loop ensures that the body of the loop is executed at least once. It can be
implemented using an infinite loop along with a conditional break at the end. This is similar to
the do...while loop in C.

Flowchart of Loop with Condition at Bottom

Example #4: Loop with condition at the bottom


# Python program to illustrate a loop with condition at the bottom
# Roll a dice untill user chooses to exit

# import random module


import random

while True:
input("Press enter to roll the dice")

# get a number between 1 to 6


num = random.randint(1,6)
print("You got",num)
option = input("Roll again?(y/n) ")

# condition
if option == 'n':
break

Output
Press enter to roll the dice
You got 1
Roll again?(y/n) y
Press enter to roll the dice
You got 5
Roll again?(y/n) n

7.6 Python Function

In Python, function is a group of related statements that perform a specific task. Functions help
break our program into smaller and modular chunks. As our program grows larger and larger,
functions make it more organized and manageable. Furthermore, it avoids repetition and makes
code reusable.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)
Above shown is a function definition which consists of following components.
1. Keyword def marks the start of function header.
2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example of a function
7.6.1 Function Call
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
Hello, Paul. Good morning!

Note: Try running the above code into the Python shell to see the output.

7.6.3 Docstring
The first string after the function header is called the docstring and is short for documentation
string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember
what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally
use triple quotes so that docstring can extend up to multiple lines. This string is available to us as
__doc__ attribute of the function.

For example:

Try running the following into the Python shell to see the output.

>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter

7.6.4 The return statement


The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function,
then the function will return the None object.

For example:

>>> print(greet("May"))
Hello, May. Good morning!
None

Here, None is the returned value.

Example of return

How Function works in Python?

7.6.5 Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes. They are destroyed
once we return from the function. Hence, a function does not remember the value of a variable
from its previous calls.
Here is an example to illustrate the scope of a variable inside a function.

Output

Value inside function: 10


Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function my_func() changed
the value of x to 10, it did not effect the value outside the function. This is because the variable x
inside the function is different (local to the function) from the one outside. Although they have
same names, they are two different variables with different scope.

On the other hand, variables outside of the function are visible from inside. They have a global
scope. We can read these values from inside the function but cannot change (write) them. In
order to modify the value of variables outside the function, they must be declared as global
variables using the keyword global.

7.6.6 Types of Functions


Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

7.6.7 Python Function Arguments

In user-defined function a function can be defined and called. Otherwise, the function call will
result into an error.

Output

Hello Monica, Good morning!

Here, the function greet() has two parameters.


Since, we have called this function with two arguments, it runs smoothly and we do not get any
error. If we call it with different number of arguments, the interpreter will complain. Below is a
call to this function with one and no arguments along with their respective error messages.

>>> greet("Monica") # only one argument


TypeError: greet() missing 1 required positional argument: 'msg'
>>> greet() # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'
Variable Function Arguments
Up until now functions had fixed number of arguments. In Python there are other ways to define
a function which can take variable number of arguments. Three different forms of this type are
described below.

a. Python Default Arguments


Function arguments can have default values in Python. We can provide a default value to an
argument by using the assignment operator (=).

Here is an example.

In this function, the parameter name does not have a default value and is required (mandatory)
during a call. On the other hand, the parameter msg has a default value of "Good morning!". So,
it is optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For example, if we
had defined the function header above as:
def greet(msg = "Good morning!", name):

We would get an error as:

SyntaxError: non-default argument follows default argument


b. Python Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according
to their position.
For example, in the above function greet(), when we called it as greet("Bruce","How do
you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do you

do?" to msg.

Python allows functions to be called using keyword arguments. When we call functions in this
way, the order (position) of the arguments can be changed. Following calls to the above function
are all valid and produce the same result.
>>> # 2 keyword arguments
>>> greet(name = "Bruce",msg = "How do you do?")

>>> # 2 keyword arguments (out of order)


>>> greet(msg = "How do you do?",name = "Bruce")

>>> # 1 positional, 1 keyword argument


>>> greet("Bruce",msg = "How do you do?")

As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments.
Having a positional argument after keyword arguments will result into errors. For example the
function call as follows:
greet(name="Bruce","How do you do?")

Will result into error as:

SyntaxError: non-keyword arg after keyword arg

c. Python Arbitrary Arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls with arbitrary
number of arguments. In the function definition we use an asterisk (*) before the parameter name
to denote this kind of argument. Here is an example.
Output

Hello Monica
Hello Luke
Hello Steve
Hello John

Here, we have called the function with multiple arguments. These arguments get wrapped up into
a tuple before being passed into the function. Inside the function, we use a for loop to retrieve
all the arguments back.

7.7 Python Recursion

A recursive function is a function that calls itself.

Recursion is the process of defining something in terms of itself. A physical world example
would be to place two parallel mirrors facing each other. Any object in between them would be
reflected recursively.

7.7.1 Python Recursive Function


We know that in Python, a function can call other functions. It is even possible for the function
to call itself. These type of construct are termed as recursive functions.
Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the
factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Example of recursive function

In the above example, calc_factorial() is a recursive functions as it calls itself. When we call
this function with a positive integer, it will recursively call itself by decreasing the number. Each
function call multiples the number with the factorial of number 1 until the number is equal to
one. This recursive call can be explained in the following steps.
calc_factorial(4) # 1st call with 4
4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
4 * 3 * 2 # return from 3rd call
4 * 6 # return from 2nd call
24 # return from 1st call

Our recursion ends when the number reduces to 1. This is called the base condition. Every
recursive function must have a base condition that stops the recursion or else the function calls
itself infinitely.
Advantages of recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
7.7.2 Python Anonymous/Lambda Function
In Python, anonymous function is a function that is defined without a name. While normal
functions are defined using the def keyword, in Python anonymous functions are defined using
the lambda keyword. Hence, anonymous functions are also called lambda functions.
Lambda Functions
A lambda function has the following syntax.
Syntax of Lambda Function
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.

Example of Lambda Function


Here is an example of lambda function that doubles the input value.

In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x *
2 is the expression that gets evaluated and returned. This function has no name. It returns a

function object which is assigned to the identifier double. We can now call it as a normal
function. The statement
double = lambda x: x * 2

is nearly the same as

def double(x):
return x * 2

Use of Lambda Function


We use lambda functions when we require a nameless function for a short period of time.
In Python, we generally use it as an argument to a higher-order function (a function that takes in
other functions as arguments). Lambda functions are used along with built-in functions like
filter(), map() etc.

Example use with filter()

The filter() function in Python takes in a function and a list as arguments. The function is
called with all the items in the list and a new list is returned which contains items for which the
function evaluates to True.

Here is an example use of filter() function to filter out only even numbers from a list.

Example use with map()

The map() function in Python takes in a function and a list. The function is called with all the
items in the list and a new list is returned which contains items returned by that function for each
item.

Here is an example use of map() function to double all the items in a list.

7.8 Python Package


We don't usually store all of our files in our computer in the same location. We use a well-
organized hierarchy of directories for easier access. Similar files are kept in the same directory,
for example, we may keep all the songs in the "music" directory. Analogous to this, Python has
packages for directories and modules for files.

As our application program grows larger in size with a lot of modules, we place similar modules
in one package and different modules in different packages. This makes a project (program) easy
to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a
Python package can have sub-packages and modules.

A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.

Here is an example. Suppose we are developing a game, one possible organization of packages
and modules could be as shown below.

Importing module from a package


We can import modules from packages using the dot (.) operator. For example, if want to import
the start module in the above example, it is done as follows.
import Game.Level.start
Now if this module contains a function named select_difficulty(), we must use the full
name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module
within a package would be as follows.
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion
and prevents two same identifier names from colliding. While importing packages, Python looks
in the list of directories defined in sys.path, similar as for module search path.

7.9 Python Modules

Modules refer to a file containing Python statements and definitions. A file containing Python
code, for e.g.: example.py, is called a module and its module name would be example. We use
modules to break down large programs into small manageable and organized files. Furthermore,
modules provide reusability of code. We can define our most used functions in a module and
import it, instead of copying their definitions into different programs.

Let us create a module. Type the following and save it as example.py.

# Python Module example

def add(a, b):


"""This program adds two
numbers and return the result"""
result = a + b
return result

Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.

How to import modules in Python?


We can import the definitions inside a module to another module or the interactive interpreter in
Python. We use the import keyword to do this. To import our previously defined module
example we type the following in the Python prompt.
>>> import example
This does not enter the names of the functions defined in example directly in the current symbol
table. It only enters the module name example there.
Using the module name we can access the function using dot (.) operation. For example:
>>> example.add(4,5.5)
9.5
Python has a ton of standard modules available. You can check out the full list of Python
standard modules and what they are for. These files are in the Lib directory inside the location
where you installed Python. Standard modules can be imported the same way as we import our
user-defined modules.

There are various ways to import modules. They are listed as follows.

7.9.1 Python import statement


We can import a module using import statement and access the definitions inside it using the dot
operator as described above. Here is an example.

When you run the program, the output will be:

The value of pi is 3.141592653589793

7.9.2 Import with renaming


We can import a module by renaming it as follows.

We have renamed the math module as m. This can save us typing time in some cases. Note that
the name math is not recognized in our scope. Hence, math.pi is invalid, m.pi is the correct
implementation.

7.9.3 Python from...import statement


We can import specific names form a module without importing the module as a whole. Here is
an example.

We imported only the attribute pi form the module. In such case we don't use the dot operator.
We could have imported multiple attributes as follows.
>>> from math import pi, e
>>> pi
3.141592653589793
>>> e
2.718281828459045

7.9.4 Import all names


We can import all names(definitions) form a module using the following construct.
We imported all the definitions from the math module. This makes all names except those
beginning with an underscore, visible in our scope. Importing everything with the asterisk (*)
symbol is not a good programming practice. This can lead to duplicate definitions for an
identifier. It also hampers the readability of our code.

7.9.5 Python Module Search Path


While importing a module, Python looks at several places. Interpreter first looks for a built-in
module then (if not found) into a list of directories defined in sys.path. The search is in this
order.

 The current directory.


 PYTHONPATH (an environment variable with a list of directory).
 The installation-dependent default directory.

>>> import sys


>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

We can add modify this list to add our own path.

7.9.6 Reloading a module


The Python interpreter imports a module only once during a session. This makes things more
efficient. Here is an example to show how this works.

Suppose we have the following code in a module named my_module.


# This module shows the effect of
# multiple imports and reload

print("This code got executed")

Now we see the effect of multiple imports.

>>> import my_module


This code got executed
>>> import my_module
>>> import my_module

We can see that our code got executed only once. This goes to say that our module was imported
only once. Now if our module changed during the course of the program, we would have to
reload it. One way to do this is to restart the interpreter. But this does not help much. Python
provides a neat way of doing this. We can use the reload() function inside the imp module to
reload a module. This is how its done.
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>

7.9.10 The dir() built-in function

We can use the dir() function to find out names that are defined inside a module. For example,
we have defined a function add() in the module example that we had in the beginning.

>>> dir(example)
['__builtins__',
'__cached__',
'__doc__',
'__file__',
'__initializing__',
'__loader__',
'__name__',
'__package__',
'add']

Here, we can see a sorted list of names (along with add). All other names that begin with an
underscore are default Python attributes associated with the module.

For example, the __name__ attribute contains the name of the module.

>>> import example


>>> example.__name__
'example'

All the names defined in our current namespace can be found out using the dir() function
without any arguments.

>>> a = 1
>>> b = "hello"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'b', 'math', 'pyscripter']

You might also like