Python DR Abikoye
Python DR Abikoye
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.
as Elif if or yield
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
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
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])
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])
# 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}
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))
# Generates error
print("d[2] = ", d[2]);
Output:
<class 'dict'>
d[1] = value
d['key'] = 2
Conversion from float to int will truncate the value (make it closer to zero).
>>> int(10.6)
10
>>> int(-10.6)
-10
a = 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 file is the object where the values are printed and its default value is sys.stdout (screen).
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).
Output:
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])
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:
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']
Arithmetic 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
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
/ 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
# 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)
2. Comparison operators
Comparison operators are used to compare values. It either returns True or False according to
the condition.
Comparision operators in Python
> 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
>= 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
# 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
# Output: x or y is True
print('x or y is',x or y)
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
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
= 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
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
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
# 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
# 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.
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
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisions, Identity, Membership operators
Or Logical OR
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)
Output:
512
64
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
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.
3 is a positive number
This is always printed
This is also always printed.
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.
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.
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.
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.
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
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
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
The sum is 48
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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
def function(args):
pass
class example:
pass
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):
The sum is 55
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!
while True:
input("Press enter to roll the dice")
# 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
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
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Example of return
Output
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.
In user-defined function a function can be defined and called. Otherwise, the function call will
result into an error.
Output
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):
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?")
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?")
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.
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.
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.
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
def double(x):
return x * 2
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.
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.
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.
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.
Here, we have defined a function add() inside a module named example. The function takes in
two numbers and returns their sum.
There are various ways to import modules. They are listed 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.
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
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'>
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.
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']