PYTHON PROGRAMMING
Python Introduction
Release
Basic of Python : a Introduction of
Basic Python
May 2024
Unit – I
Introduction: What is a program, Running python, Arithmetic operators, Value and Types. Variables,
Assignments and Statements: Assignment statements, Script mode, Order of operations, string operations,
comments. Functions: Function calls, Math functions, Composition, Adding new Functions, Definitions
and Uses, Flow of Execution, Parameters and Arguments, Variables and Parameters are local, Stack
diagrams, Fruitful Functions and Void Functions, Why Functions.
Unit – II
Case study: The turtle module, Simple Repetition, Encapsulation, Generalization, Interface design,
Refactoring, docstring. Conditionals and Recursion: floor division and modulus, Boolean expressions,
Logical operators, Conditional execution, Alternative execution, Chained conditionals, Nested
conditionals, Recursion, Infinite Recursion, Keyboard input. Fruitful Functions: Return values,
Incremental development, Composition, Boolean functions, More recursion, Leap of Faith, Checking
types.
Unit – III
Iteration: Reassignment, Updating variables, The while statement, Break, Square roots, Algorithms.
Strings: A string is a sequence, len, Traversal with a for loop, String slices, Strings are immutable,
Searching, Looping and Counting, String methods, The in operator, String comparison. Case Study:
Reading word lists, Search, Looping with indices. Lists: List is a sequence, Lists are mutable, Traversing
a list, List operations, List slices, List methods, Map filter and reduce, Deleting elements, Lists and
Strings, Objects and values, Aliasing, List arguments.
Unit – IV
Dictionaries: A dictionary is a mapping, Dictionary as a collection of counters, Looping and dictionaries,
Reverse
Lookup, Dictionaries and lists, Memos, Global Variables. Tuples: Tuples are immutable, Tuple
Assignment, Tuple as Return values, Variable-length argument tuples, Lists and tuples, Dictionaries and
tuples, Sequences of sequences.
Files: Persistence, Reading and writing, Format operator, Filename and paths, Catching exceptions,
Databases, Pickling, Pipes, Writing modules. Classes and Objects: Programmer-defined types, Attributes,
Instances as Return values, Objects are mutable, Copying.
Unit – V
Classes and Functions: Time, Pure functions, Modifiers, Prototyping versus Planning Classes and
Methods: Object oriented features, Printing objects, The init method, The str method, Operator
overloading, Type-based Dispatch,
Polymorphism, Interface and Implementation Inheritance: Card objects, Class attributes, Comparing
cards, decks, Printing the Deck, Add Remove shuffle and sort, Inheritance, Class diagrams, Data
encapsulation. The Goodies: Conditional expressions, List comprehensions, Generator expressions, any
and all, Sets, Counters, defaultdict, Named tuples, Gathering keyword Args,
Unit 1
Chapter-1
INTRODUCTION
What Is a Program
A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations or finding the
roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a
document or something graphical, like processing an image or playing a video.
few basic instructions appear in just about every
language: input:
Get data from the keyboard, a file, the network, or some other
device. output:
Display data on the screen, save it in a file, send it over the network, etc.
math:
Perform basic mathematical operations like addition and
multiplication. conditional execution:
Check for certain conditions and run the appropriate
code. repetition:
Perform some action repeatedly, usually with some variation.
Install and Run Python:
Installing Python
Download the latest version of Python.
Run the installer file and follow the steps to install Python During the
install process, check Add Python to environment variables. This will add Python to environment
variables, and you can run Python from any part of the computer. Also, you can choose the path
where Python is installed.
Installing Python on the computer
Once you finish the installation process, you can run Python.
1. Run Python in Immediate mode
Once Python is installed, typing python in the command line will invoke the
interpreter in immediate mode. We can directly type in Python code, and press
Enter to get the output. Try typing in 1 + 1 and press enter. We get 2 as the
output. This prompt can be used as a calculator. To exit this mode, type quit()
and press enter.
Running Python on the Command Line
2. Run Python in the Integrated Development Environment (IDE)
IDE is a piece of software that provides useful features like code hinting, syntax
highlighting and checking, file explorers, etc. to the programmer for application
development.
By the way, when you install Python, an IDE named IDLE is also installed. You
can use it to run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.
Python IDLE
Now you can create a new file and save it with .py extension.
For example, hello.py
Write Python code in the file and save it.
To run the file, go to Run > Run Module or simply click F5.
Running a Python program
in IDLE The First
Program:
>>> print('Hello, World!')
This is an example of a print
statement the result is the
words Hello, World!
The quotation marks in the program mark the beginning and end of
the text to be displayed; they don’t appear in the result. The
parentheses indicate that print is a function.
Operators:
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical
Operators
Bitwise
Operators
Membership
Operators
Identity Operators
Let us have a look on all operators one by one.
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then –
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
*
Multiplicatio
n
Multiplies values on either side of the operator a * b = 200
/ Division Divides left hand operand by right hand operand b / a = 2
% Modulus Divides left hand operand by right hand operand and
returns remainder
b % a = 0
** Exponent Performs exponential (power) calculation on
operators
a**b =10 to the
power 20
// Floor Division - The division of operands where the
result is the quotient in which the digits after the
decimal point are removed. But if one of the
operands is negative, the result is floored, i.e.,
rounded away from zero (towards negative infinity)
−
9//2 = 4 and
9.0//2.0 =
4.0,
-11//3 = -4,
-11.0//3 = -4.0
Values and Types
A value is one of the basic things a program works with, like a letter or a number.
Some values we have seen so far are 2, 42.0, and 'Hello, World!'
These values belong to different types: 2 is an integer, 42.0 is a floating-point
number and 'Hello, World!' is a string
If you are not sure what type a value has, the interpreter can tell you:
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
In these results, the word “class” is used in the sense of a category; a type is
a category of values.
What about values like '2' and '42.0'? They look like numbers, but they are in
quotation marks like strings:
>>> type('2')
<class 'str'>
>>>
type('42.
0') <class
'str'>
Therefore they’re strings.
Chapter-2
Variables, Assignments and Statements
1.An assignment statement creates a new variable and gives it a value:
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.141592653589793
This example makes three assignments.
The first assigns a string to a new variable named message; the second gives the
integer 17 to n; the third assigns the (approximate) value of π to pi
Variable Names
Programmers generally choose names for their variables that are meaningful Variable
names can be as long as you like. Rules for naming : They can contain both letters and
numbers,but they can’t begin with a number. Can use both lower and uppercase
letters.The underscore character, _, can appear in a name. Keywords should not use as a
variable name.
Note: If you give a variable an illegal name, you get a syntax error:
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax b’ coz it begins with a
number >>> more@ = 1000000
SyntaxError: invalid syntax b’ coz it contains illegal
character @. >>> class = 'Adanced Theoretical
Zymurgy' Keywords in Python:
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.
Expressions and Statements:
An expression is a combination of values, variables, and operators. A value all by itself is
considered an expression, and so is a variable, so the following are all legal expressions:
>> 42
42
>>> n
17
>
>
>
n
+
2
5
4
2
When you type an expression at the prompt, the interpreter evaluates it,
which means that it finds the value of the expression. In this example, n
has the value 17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or
displaying a value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print
statement that displays the value of n.
2. Script Mode:
Inscript mode type code in a file called a script and savefile with .py extention. script
mode to execute the script. By convention, Python scripts have names that end with .py.
for ex: if you type the following code into a script and run it, you get no output at all. Why
because but it
doesn’t display the value unless you tell it to. But it displays in
interactive mode. miles = 26.2 miles * 1.61 Sol is:
miles =
26.2
print(mile
s * 1.61)
3. Order of perations:
When an expression contains more than one operator, the order of evaluation depends
on the order of operations.For mathematical operators, Python follows order
PEMDAS.
P-parentheses,
E- Exponentiation,
M- Multiplication
D-Division
A-Addition,
S- Substraction
• Parentheses have the highest precedence.
For ex in the following expressions in parentheses are
evaluated first, Ex:1. 2 * (3-1) is 4, and Ex: 2.
(1+1)**(5-2) is 8.
• Exponentiation has the next highest precedence,
For ex: 1 + 2**3 is 9,
not 27, and 2 * 3**2
is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction.
For ex: 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Note: Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first and
the result is multiplied by pi.
4. Operations on strings:
Note : Mathematical operations on strings are not allowed so the following are
illegal: '2'-'1' 'eggs'/'easy' 'third'*'a charm'
How to Create Strings in Python?
Creating strings is easy as you only need to enclose the characters either in single or
double-quotes.
In the following example, we are providing different ways to initialize strings.To share an
important note that you can also use triple quotes to create strings. However, programmers use
them to mark multi-line strings and docstrings.
# Python string examples - all assignments are identical.
String_var = 'Python'
String_var = "Python"
String_var =
"""Python"""
# with Triple quotes Strings can extend to multiple lines
String_var = """ This document will help you to explore all the concepts of
Python Strings!!! """
# Replace "document" with "tutorial" and store in
another variable substr_var =
String_var.replace("document", "tutorial") print
(substr_var)
String Operators in Python
Concatenation (+):It combines two
strings into one.
#
ex
a
m
pl
e
va
r1
=
'P
yt
ho
n'
va
r2
=
'St
rin
g'
print (var1+var2) # PythonString Repetition (*):This operator creates a new string
by repeating it a given number of times.
#
e
x
a
m
p
l
e
v
a
r
1
=
'
P
y
t
h
o
n'
p
ri
n
t
(
v
a
r
1
*
3
)
# PythonPythonPython
Slicing [ ]:The slice operator prints the character at a given index.
#
examp
le
var1
=
'Pytho
n'
print (var1[2]) # t
Range Slicing [x:y]
It prints the characters present in the given range.
#
example
var1 =
'Python'
print
(var1[2:
5]) # tho
Membership (in):This operator returns ‘True’ value if the character is present in the given
String.
#
example
var1 =
'Python'
print ('n' in
var1) #
True
Membersh
ip (not in):
:
It returns ‘True’ value if the character is not present in the given String.
#
exampl
e var1
=
'Python
' print
('N' not
in var1)
# True
Iterating (for): With this operator, we can iterate through all the characters of a string.
# example for var in var1:
print (var, end ="") # Python
Raw String (r/R):We can use it to ignore the actual meaning of Escape characters
inside a string. For this, we add ‘r’ or ‘R’ in front of the String.
# example
print
(r'n')
# n
print
(R'n')
# n
Unicode String support in Python
egular Strings stores as the 8-bit ASCII value, whereas Unicode String follows the 16-bit
ASCII standard. This extension allows the strings to include characters from the different
languages of the world. In Python, the letter ‘u’ works as a prefix to distinguish between
Unicode and usual strings. print (u' Hello Python!!')
OUTPUT:
#Hello Python
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
center()
Returns a centered string
count()
Returns the number of times a specified value occurs in a string
encode()
Returns an encoded version of the string
endswith()
Returns true if the string ends with the specified value
expandtabs()
Sets the tab size of the string
find()
Searches the string for a specified value and returns the position of where it was found
format()
Formats specified values in a string
format_map()
Formats specified values in a string
index()
Searches the string for a specified value and returns the position of where it was found
isalnum()
Returns True if all characters in the string are alphanumeric
isalpha()
Returns True if all characters in the string are in the alphabet
isdecimal()
Returns True if all characters in the string are decimals
isdigit()
Returns True if all characters in the string are digits
isidentifier()
Returns True if the string is an identifier
islower()
Returns True if all characters in the string are lower case
isnumeric()
Returns True if all characters in the string are numeric
isprintable()
Returns True if all characters in the string are printable
isspace()
Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper()
Returns True if all characters in the string are upper case
join()
Joins the elements of an iterable to the end of the string
ljust()
Returns a left justified version of the string
lower()
Converts a string into lower case
lstrip()
Returns a left trim version of the string
maketrans()
Returns a translation table to be used in translations
partition()
Returns a tuple where the string is parted into three parts
replace()
Returns a string where a specified value is replaced with a specified value
rfind()
Searches the string for a specified value and returns the last position of where it was
found
rindex()
Searches the string for a specified value and returns the last position of where it was
found
rjust()
Returns a right justified version of the string
rpartition()
Returns a tuple where the string is parted into three parts
rsplit()
Splits the string at the specified separator, and returns a list
rstrip()
Returns a right trim version of the string
But there are two exceptions, +
and *. The + operator performs
string concatenation, For
example:
>>> first = 'throat'
split()
Splits the string at the specified separator, and returns a list
splitlines()
Splits the string at line breaks and returns a list
startswith()
Returns true if the string starts with the specified value
strip()
Returns a trimmed version of the string
swapcase()
Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate()
Returns a translated string
upper()
Converts a string into upper case
zfill()
Fills the string with a specified number of 0 values at the beginning
>>>
second =
'warbler'
>>> first
+ second
throatwar
bler
The * operator also works on strings; it performs repetition.
For example, 'Spam'*3 is 'SpamSpamSpam'.
EXAMPLE1:
var1 = 'Hello
World!' var2 =
"Python
Programming"
print "var1[0]: ",
var1[0] print
"var2[1:5]: ",
var2[1:5]
When the above code is executed, it produces the following
result − var1[0]: H
var2[1:5]: ytho
EXAMPLE2:
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] +
'Python'
When the above code is executed, it produces the following
result − Updated String :- Hello Python
5. Comments:
Comments are of two types .
Single-line comments
Multi line Comments
Single-line comments are created simply by beginning a line with the hash
(#) character, and they are automatically terminated by the end of line. For
Ex: #This would be a comment in Python
Multi Line Comments that span multiple lines and are created by adding a
delimiter (“””) on each end of the comment For Ex:
"""
This would be a multiline comment in Python that spans several lines and describes
your code, your day, or anything you want it to """
Chapter-3 Functions
What is a Function in Python?
A Function in Python is used to utilize the code in more than one place in a
program. It is also called method or procedures. Python provides you many
inbuilt functions like print(), but it also gives freedom to create your own
functions.
Functions:
A function is a named sequence of statements that performs a computation.
How to define and call a function in Python
Function in Python is defined by the "def " statement followed by the
function name and parentheses ( () ) Example:
Let us define a function by using the command " def func1():" and call the
function. The output of the function will be "I am learning Python function"
The function print func1() calls our def func1(): and print the command " I am
learning Python function None."There are set of rules in Python to define a
function.Any args or input parameters should be placed within these
parentheses.The function first statement can be an optional statement- docstring
or the documentation string of the function The code within every function starts
with a colon (:) and should be indented (space) The statement return
(expression) exits a function, optionally passing back a value to the caller. A
return statement with no args is the same as return None. Significance of
Indentation (Space) in Python:
Before we get familiarize with Python functions, it is important that we
understand the indentation rule to declare Python functions and these rules are
applicable to other elements of Python as well like declaring conditions, loops or
variable.
Python follows a particular style of indentation to define the code, since Python
functions don't have any explicit begin or end like curly braces to indicate the
start and stop for the function, they have to rely on this indentation. Here we
take a simple example with "print" command. When we write "print" function
right below the def func 1 (): It will show an "indentation error: expected an
indented block".
Now, when you add the indent (space) in front of "print" function, it should print as
expected.
How Function Return Value?
Return command in Python specifies what value to give back to the caller of the function.
Let's understand this with the following example
Step 1) Here - we see when function is not "return". For example, we want the
square of 4, and it should give answer "16" when the code is executed. Which it
gives when we simply use "print x*x" code, but when you call function "print
square" it gives "None" as an output. This is because when you call the function,
recursion does not happen and fall off the end of the function. Python returns
"None" for failing off the end of the function.
Step 2) To make this clearer we replace the print command with assignment
command. Let's check the output.
When you run the command "print square (4)" it actually returns the value of the
object since we don't have any specific function to run over here it returns "None".
Step 3) Now, here we will see how to retrieve the output using "return" command.
When you use the "return" function and execute the code, it will give the output
"16."
Step 4) Functions in Python are themselves an object, and an object has some
value. We will here see how Python treats an object. When you run the
command "print square" it returns the value of the object. Since we have not
passed any argument, we don't have any specific function to run over here it
returns a default value (0x021B2D30) which is the location of the object. In
practical Python program, you probably won't ever need to do this.
Arguments in Functions
The argument is a value that is passed to the function when it's called.In other words on
the calling side, it is an argument and on the function side it is a parameter. Let see how
Python Args works - Step 1) Arguments are declared in the function definition. While
calling the function, you can pass the values for that args as shown below
Step 2) To declare a default value of an argument, assign it a value at function definition.
Example: x has no default values. Default values of y=0. When we supply only
one argument while calling multiply function, Python assigns the supplied value
to x while keeping the value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value y=0,
and it will return the output as (4x2)=8.
Step 4) You can also change the order in which the arguments can be passed in
Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Step 5) Multiple Arguments can also be passed as an array. Here in the example
we call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the
(*args) function; it prints out the output as (1,2,3,4,5)
Rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).Any input parameters or arguments should be placed within
these parentheses. You can also define parameters inside these parentheses.The
code block within every function starts with a colon (:) and is indented. The
statement return [expression] exits a function, but it is optional
Syntax:
def functionname( parameters ):
functio
n_suite
return
[expres
sion]
Creati
ng a
Functi
on
In Python a function is defined using the
def keyword: Example def
my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed
by parenthesis: Example def my_function():
print("Hello from a function")
my_function() #calling function
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 are not visible from outside
the function. Hence, they have a local scope.
The 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.
def my_func():
x = 10
print("Value inside function:",x)
x =
20
my
_fu
nc()
print("Value outside
function:",x)
Output
Value inside
function: 10
Value
outside
function: 20
2. Math Functions:
Python has a math module that provides mathematical functions. A module is a
file that contains a collection of related functions.Before we can use the
functions in a module, we have to import it with an import statement:
>>> import math
Note: The module object contains the functions and variables defined in
the module. To access one of the functions, you have to specify the name
of the module and the name of the function, separated by a dot (also
known as a period). This format is called dot notation.
For ex:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)
Some Constants
These constants are used to put them into our calculations.
Sr.No. Constants & Description
1 pi - Return the value of pi: 3.141592
4 inf - Returns the infinite
5 nan - Not a number type.
Numbers and Numeric Representation
These functions are used to represent numbers in different forms. The methods are
like below −
Sr.No. Function & Description
1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number
x.
3 fabs(x)
Returns the absolute value of x.
4 factorial(x)
Returns factorial of x. where x ≥ 0
5 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.
6 fsum(iterable)
Find sum of the elements in an iterable object
7 gcd(x, y)
Returns the Greatest Common Divisor of x and y
8 isfinite(x)
Checks whether x is neither an infinity nor nan.
9 isinf(x)
Checks whether x is infinity
10 isnan(x)
Checks whether x is not a number.
11 remainder(x, y)
Find remainder after dividing x by y
Example program:
import math
print(math.ceil(23.56) )
my_list = [12, 4.25, 89, 3.02, -65.23, -7.2, 6.3]
print(math.fsum(my_list))
print('The GCD of 24 and 56 : ' +
str(math.gcd(24, 56))) x = float('nan') if
math.isnan(x):
print('It is not a number')
x =
float('i
nf')
y = 45
if
math.i
sinf(x)
:
print('
It is
Infinit
y')
print(math.isfinite(x)) #x is not a finite number
print(math.isfinite(y)) #y is a finite number
O/P:
24
42.13999999999999
The GCD of 24 and 56 : 8
It is not a number
It is Infinity
False
True
>>>
Power and Logarithmic Functions
These functions are used to calculate different power related and logarithmic related
tasks.
Sr.No. Function & Description
1 pow(x, y)
Return the x to the power y value.
2 sqrt(x)
Finds the square root of x
3 exp(x)
Finds xe, where e = 2.718281
4 log(x[, base])
Returns the Log of x, where base is given. The default base is e
5 log2(x)
Returns the Log of x, where base is 2
6 log10(x)
Returns the Log of x, where base is 10
Example
Code
import
math
print('The value of 5^8: ' + str(math.pow(5, 8)))
print('Square root of 400: ' + str(math.sqrt(400)))
print('The value of 5^e: ' + str(math.exp(5)))
print('The value of Log(625), base 5: ' +
str(math.log(625, 5))) print('The value of Log(1024),
base 2: ' + str(math.log2(1024))) print('The value of
Log(1024), base 10: ' + str(math.log10(1024)))
Output
The value of 5^8: 390625.0
Square root of 400: 20.0
The value of 5^e: 148.4131591025766
The value of Log(625), base 5: 4.0
The value of Log(1024), base 2: 10.0
The value of Log(1024), base 10: 3.010299956639812
Trigonometric & Angular Conversion Functions
These functions are used to calculate different trigonometric operations.
Sr.No. Function & Description
1 sin(x)
Return the sine of x in radians
2 cos(x)
Return the cosine of x in radians
3 tan(x)
Return the tangent of x in radians
4 asin(x)
This is the inverse operation of the sine, there are acos, atan
also.
5 degrees(x)
Convert angle x from radian to degrees
6 radians(x)
Convert angle x from degrees to radian
Example
Code
import
math
print('The value of Sin(60 degree): ' +
str(math.sin(math.radians(60)))) print('The value of
cos(pi): ' + str(math.cos(math.pi))) print('The value of
tan(90 degree): ' + str(math.tan(math.pi/2)))
print('The angle of sin(0.8660254037844386): ' +
str(math.degrees(math.asin(0.8660254037844386))))
Output
The value of Sin(60 degree): 0.8660254037844386
The value of cos(pi): -1.0
The value of tan(90 degree): 1.633123935319537e+16
The angle of sin(0.8660254037844386): 59.99999999999999
3. Composition:
So far, we have looked at the elements of a program—variables, expressions, and
statements—in isolation, without talking about how to combine(Composition)
them.For example, the argument of a function can be any kind of expression, including
arithmetic operators: x = math.sin(degrees / 360.0 * 2 * math.pi) And even function
calls:
x = math.exp(math.log(x+1))
4. Adding new functions:
Pass by reference vs value:All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a function, the change also
reflects back in the calling function. For example −
#!/usr/bin/python
# Function
definition is here
def changeme(
mylist ):
"This changes a passed list into this
function" mylist.append([1,2,3,4]);
print "Values inside the function: ",
mylist return
# Now you can call changeme function
mylist =
[10,20,30];
changeme( mylist
);
print "Values outside the function: ",
mylist
Here, we are maintaining reference of the passed object and appending
values in the same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
Scope of Variables:All variables in a program may not be accessible at all
locations in that program. This depends on where you have declared a
variable.The scope of a variable determines the portion of the program where
you can access a particular identifier. There are two basic scopes of variables
in Python −
Global
variables
Local
variables
Global vs. Local variables:Variables that are defined inside a function body have a
local scope, and those defined outside have a global scope.This means that local
variables can be accessed only inside the function in which they are declared,
whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into
scope. Following is a simple example −
#!/usr/bin/python
total = 0; # This is
global variable. #
Function definition is
here def sum( arg1,
arg2 ):
# Add both the parameters and
return them." total = arg1 + arg2; #
Here total is local variable. print
"Inside the function local total : ",
total return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global
total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
The import Statement
You can use any Python source file as a module by executing an import statement in
some other Python source file. The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path. A search path is a list of directories that
the interpreter searches before importing a module. For example, to import the
module support.py, you need to put the following command at the top of the
script − #!/usr/bin/python
# Import module
support import
support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following
result − Hello : Zara
5. Flow of Execution
The order in which statements are executed is called the
flow of execution Execution always begins at the first
statement of the program.
Statements are executed one at a time, in order, from top to
bottom.
Function definitions do not alter the flow of execution of the program, but
remember that statements inside the function are not executed until the function
is called.
Function calls are like a bypass in the flow of execution. Instead of going to
the next statement, the flow jumps to the first line of the called function,
executes all the statements there, and then comes back to pick up where it left
off.
6. Parameters and Arguments:
Parameter: The terms parameter and argument can be used for the same thing:
information that are passed into a function.From a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called. Arguments
You can call a function by using the following types of formal arguments
– 1.Required arguments
2.Keyword arguments
3.Default arguments
4.Variable-
length
arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional
order. Here, the number of arguments in the function call should match exactly
with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it
gives a syntax error as follows −
#!/usr/bin/python
# Function
definition is here
def printme( str ):
"This prints a passed string into this
function" print str
retur
n;
# Now you can call printme
function printme()
When the above code is executed, it produces the following
result − Traceback (most recent call last):
File "test.py", line 11, in
<module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments
in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with
parameters. You can also make keyword calls to the printme() function in the
following ways − #!/usr/bin/python
# Function
definition is here
def printme( str ):
"This prints a passed string into
this function" print str return;
# Now you can call printme
function printme( str = "My
string")
When the above code is executed, it produces the
following result − My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
#!/usr/bin/python
# Function
definition is here
def printinfo(
name, age ):
"This prints a passed info into this
function"
print "Name:
", name print
"Age ", age
retur
n;
# Now you can call printinfo
function printinfo( age=50,
name="miki" )
When the above code is executed, it produces the following
result − Name: miki
Age 50
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an
idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python
# Function
definition is here
def printinfo(
name, age = 35 ):
"This prints a passed info into this
function"
print "Name:
", name print
"Age ", age
retur
n;
# Now you can call printinfo
function printinfo( age=50,
name="miki" ) printinfo(
name="miki" )
When the above code is executed, it produces the following
result − Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and
default arguments.Syntax for a function with non- keyword variable arguments
is this − def functionname([formal_args,] *var_args_tuple ):
"functi
on_doc
string"
functio
n_suite
return
[expres
sion]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple example
−
#!/usr/bin/python
# Function
definition is here
def printinfo(
arg1, *vartuple ):
"This prints a variable passed
arguments"
print
"Out
put
is: "
print
arg1
for
var in
vartu
ple:
print
var
retur
n;
# Now you can call printinfo function
printinfo(
10 )
printinfo(
70, 60, 50
)
When the above code is executed, it produces the following
result − Output is:
10
Output is:
70
60
50
Example
def
my_functio
n(fname):
print(fname + " krishna") my_function("Rama") my_function("Siva")
my_function("Hari") o/p: Ramakrishna Sivakrishna
Harikrishna.
Parameters Vs Arguments
A parameter is the variable listed inside the parentheses in the function
definition. An argument is the value that is sent to the function when it
is called.
Number of Arguments
A function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2
arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Srinu", "vasulu")
Arbitrary Arguments( *args)
If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the
items accordingly:
Example
If the number of arguments is unknown, add a * before the
parameter name: def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("raju", "somu", "vijay) O/p: vijay
Default Parameter Value:
When we call the function without argument, it uses the default value:
Example
def my_function(country = "Norway"): #default value is Norway
print("I am from " + country) my_function("Sweden")
my_function("India") my_function() #o/p:
Norway my_function("Brazil")
Passing a List as an Argument:
You can send any data types of argument to a function (string, number, list,
dictionary etc.) E.g. if you send a List as an argument, it will still be a List
when it reaches the function: Example def my_function(food):
for x in
food:
prin
t(x)
fruits =
my_function(fruits)
Return Values:
To return a value, we use the return statement:
Example def my_function(x):
["apple", "banana", "cherry"]
return 5 * x
print(my_function(3)) # o/p: 15
print(my_function(5)) # o/p: 25
print(my_function(9)) # o/p: 45
The pass Statement function definitions cannot be empty, but if you for
some reason have a function definition with no content, put in the pass
statement to avoid getting an error. Example def myfunction(): pass
7. Variables and Parameters Are Local
When you create a variable inside a function, it is local, which means that
it only exists inside the function.
For example:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
line1 =
'Bing
tiddle '
line2 =
'tiddle
bang.'
cat_twice(
line1,
line2)
print(cat)
#error
here cat_twice terminates, the variable cat is destroyed. If we try to
print it, we get an exception:
>>> NameError: name 'cat' is not defined
8. Stack Diagrams:
Stack diagram used to keep track of which variables can be used which
function. For ex, consider the following code:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)
line1 =
'Bing
tiddle '
line2 =
'tiddle
bang.'
cat_twic
e(line1,
line2)
Stack diagram for above code is:
Here each function is represented by a frame. A frame is a box with the name of a
function beside it and the parameters and variables of the function inside it.
The frames are arranged in a stack that indicates which function called which,
and so on. In this example, print_twice was called by cat_twice, and cat_twice
was called by main , which is a special name for the topmost frame. When you
create a variable outside of any function, it belongs to main .
9. Fruitful Functions and Void Functions
The function that returns a value is called fruitful function.
The function that does not returns any value is called void function.
Fruitful Functions:
Ex :def add(x,y):
return (x+y)
Z
=
a
d
d
(
1
,
2
)
p
r
i
n
t
(
z
)
void
Functions:
Ex : def
add(x,y):
print(x+y)
10.Why Functions?
There are several reasons for why functions:
• improves readability: Creating a new function gives you
an opportunity to name a group of statements, which makes
your program easier to read and debug.
• debugging easy : Functions can make a program smaller
by eliminating repetitive code. Later, if you make a change,
you only have to make it in one place.
• modularity: Dividing a long program into functions
allows you to debug the parts one at a time and then
assemble them into a working whole.
• reusability : Well-designed functions are often useful for
many programs. Once you write and debug one, you can
reuse it.
Unit-2 Chapter-1 Case Study
1. Turtle Module: in python turtle is a module, which allows you to create
images using turtle graphics
How to use turtle module:
To work with turtle we
follow the below steps
Import the turtle
module Create a turtle
to control. Draw
around using the turtle
methods. Run
Import the turtle module:
To make use of the turtle methods and functionalities, we
need to import turtle. from turtle import *
# or
import turtle
Create a turtle to control:
After importing the turtle library and making all the turtle functionalities
available to us, we need to create a new drawing board(window) and a
turtle. Let’s call the window as wn and the turtle as skk. So we code as:
wn =
turtle.Scree
n()
wn.bgcolor
("light
green")
wn.title("Tu
rtle")
skk = turtle.Turtle()
Draw around using the turtle methods:
METHOD PARAMETER DESCRIPTION
Turtle() None It creates and returns a new turtle object
forward() Amount It moves the turtle forward by the specified amount
backward() Amount It moves the turtle backward by the specified amount
right() Angle It turns the turtle clockwise
left() Angle It turns the turtle counter clockwise
penup() None It picks up the turtle’s Pen
pendown() None Puts down the turtle’s Pen
up() None Picks up the turtle’s Pen
down() None Puts down the turtle’s Pen
color() Color name Changes the color of the turtle’s pen
fillcolor() Color name Changes the color of the turtle will use to fill a polygon
heading() None It returns the current heading
position() None It returns the current position
goto() x, y It moves the turtle to position x,y
begin_fill() None Remember the starting point for a filled polygon
end_fill() None It closes the polygon and fills with the current fill color
dot() None Leaves the dot at the current position
stamp() None Leaves an impression of a turtle shape at the current location
shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’
Example code
# import
turtle
library
import
turtle
my_windo
w =
turtle.Screen()
my_window.bgcolor("blue") # creates a graphics
window my_pen =
turtle.Turtle()
my_pen.forward(150)
my_pen.left(90)
my_pen.forward(75)
my_pen.color("white")
my_pen.pensize(12)
Output
Run :
To run the turtle we call the method turtle.done().
2. Simple Repetition:
Performing the same action repeatedly is called simple repetition.
For ex let’s consider a square or rectangle to draw. The following steps to
be performed repeatedly. bob.fd(100) bob.lt(90)
bob.fd(100)
bob.lt(90)
bob.fd(1
00)
bob.lt(90
)
the above steps can be reduced using simple repetition statement for
as follows. for i in range(4):
bob.fd(100)
bob.lt(90)
3.Encapsulation :
Wrapping a piece of code up in a function is called encapsulation. The
benefits of encapsulation are,it attaches a name to the code.We can
reuse the code, (i.e we can call a function instead of copy and paste the
body)
For ex: code to
drawing the
square def
square(t): for i in
range(4):
t.fd(100)
t.lt(90)
bob =
turtle.Turtle()
square(bob)
4.Generalization:
Adding a parameter to a function is called generalization. because it
makes the function more general: in the previous version, the square is
always the same size; in this version it can be any size.
def square(t, length):
for i in
range(4):
t.fd(length)
t.lt(90)
bob = turtle.Turtle()
square(bob, 100)
the following one also a generalization. Instead of drawing squares,
polygon draws regular polygons with any number of sides. Here is a
solution:
def polygon(t, n, length):
angle = 360 / n
for i
in
range(n):
t.fd(length)
t.lt(angle)
bob = turtle.Turtle()
polygon(bob, 7, 70)
5. Interface Design:
The interface of a function is a summary of how it is used: what are the
parameters? What does the function do? And what is the return value? An
interface is “clean” if it allows the caller to do what they want without
dealing with unnecessary details.
For ex: write circle, which takes a radius, r, as a
parameter. Here is a simple solution that uses
polygon to draw a 50-sided polygon: import
math
def circle(t, r):
circumference = 2 *
math.pi * r n = 50
length = circumference / n
polygon(t, n, length)
The first line computes the circumference of a circle with radius r
using the formula 2πr. n is the number of line segments in our
approximation of a circle, so length is the length of each segment.
Thus, polygon draws a 50-sided polygon that approximates a circle
with radius r.
One limitation of this solution is that n is a constant, which means that
for very big circles, the line segments are too long, and for small circles,
we waste time drawing very small segments. One solution would be to
generalize the function by taking n as a parameter.
def circle(t, r):
circumference = 2 *
math.pi * r n =
int(circumference /
3) + 1 length =
circumference / n
polygon(t, n,
length)
6. Refactoring:
process of rearranging a program to improve interfaces and facilitate code reuse is called
refactoring for ex: Lets take above discussion , When we write circle, we can able to
reuse polygon because a many-sided polygon is a good approximation of a circle. But
arc is not as cooperative; we can’t use polygon or circle to draw an arc.One alternative
is to start with a copy of polygon and transform it into arc. The result might look like
this:
def polygon(t, n, length):
angle = 360.0 / n
polyline(t, n,
length, angle)
def arc(t, r, angle):
arc_length = 2 * math.pi * r *
angle / 360 n = int(arc_length / 3)
+ 1 step_length =
arc_length / n
step_angle =
float(angle) / n
polyline(t,
n,
step_length,
step_angle)
Finally, we can rewrite circle
to use arc: def circle(t, r):
arc(t, r, 360)
7. Docstring:
docstring is a string at the beginning of a function that
explains the interface (“doc”is short for “documentation”).
Here is an example:
def polyline(t, n, length, angle):
"""Draws n line segments with the given length and angle (in degrees)
between them. t is a turtle.
"""
for
i in
ran
ge(
n):
t.f
d(l
en
gth
)
t.lt(angle)
By convention, all docstrings are triple-quoted strings, also known as
multiline strings because the triple quotes allow the string to span more
than one line.
Chapter-2 Conditionals and Recursion
1. floor division and modulus: The floor division operator ’ //’
divides two numbers and rounds down to an integer. For
example:
Conventional division returns a floating-point number as follows
>>> minutes = 105
>>>
m
i
n
u
t
e
s
/
6
0
1
.
7
5
But Floor division returns the integer number of hours, dropping the
fraction part: >>> minutes = 105
>>> hours = minutes // 60
>> > ho urs 1 modulus operator, %, which divides two
numbers and returns the remainder:
>>> remainder = minutes % 60
>
>
>
r
e
m
a
i
n
d
e
r
4
5
2. Boolean Expressions:
A boolean expression is an expression that is either true or false.The
following examples use the operator ==, which compares two operands
and produces True if they are equal and False otherwise:
>>> 5 == 5
True
>>
> 5
==
6
Fal
se
True and False are special values that belong to the type bool; they are
not strings: >>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
The == operator is one of the relational operators;
the others are: x != y # x is not equal to y x > y # x
is greater than y x < y # x is less than y
x >= y # x is
greater than or
equal to y x <= y
# x is less than or
equal to y
3.Logical Operators:
There are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English.
For example:
x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either or both of the conditions is true, that is,
if the number is divisible by 2 or 3.
not : operator negates a boolean expression, not (x > y) is true ,if x > y is
false, that is, if x is less than or equal to y. In Python, Any
nonzero number is interpreted as True:
>>> 42
a
n
d
T
r
u
e
T
r
u
e
4.Conditional Execution:
In order to write useful programs, we almost always need the ability to
check conditions and change the behavior of the program accordingly.Conditional
statements give us this ability. if statement: if test expression:
statement(s)
Here, the program and will execute statement(s) only if
evaluates the expression the test is True. If the test
expression is False, the statement(s) is not
executed.
F
o
r
e
x
:
n
u
m
=
3
test
expression
if num > 0:
print(num, "is a
positive
number.")
print("This
is
always printed.")
5.Alternative Execution: A second form of the if statement is “alternative execution”, in
which there are two possibilities and the condition determines which one runs. The syntax
looks like this:
Synta
x of
if...els
e if
te
st
e
x
p
r
e
s
si
o
n
:
Bo
dy
of
if
else:
Body of
else
and will execute the if only when the h evaluates body of e
test True.
conditio is False, the body of else is executed. Indentation is used to separate
n is If the the condition blocks.
if..elseT statement test
expression
For ex:
if num >= 0:
print("Positive
or Zero") else:
print("Negative
number")
6. Chained Conditionals
Sometimes there are more than two possibilities and we need more than two
branches. One way to express a computation like that is a chained conditional:
to implement chained conditional we use keyword “elif”.
Syntax of
if...eli
f...els
e if
test
expre
ssion:
Body of if
elif
test
expre
ssion:
Bo
d
y of
e
l
i
f
e
l
s
e
:
Body of
else
elif
If the condiitfion, it checks
the condition of for is , the next block
and so on.
Fals
e
Fals
e
If all the conditions are the body of else is executed.
For Ex:
x
=
1
0
y
=
2
0
i
f
x
<
y
:
print('x is
less than y')
elif x > y:
print('x is
greater than
y') else:
print('x and
y are
equal')
7.Nested Conditionals
One conditional can also be nested within
another. For ex: if x == y: print('x and y are
equal') else: if x < y: print('x is less than y')
else:
print('x is greater than y')
8.Recursion
Recursion means a function to call itself. For example:
def countdown(n):
i
f
n
<
=
0
:
p
r
i
n
t
(
'
B
l
a
s
t
o
f
f
!
'
)
e
l
s
e
:
p
r
i
n
t
(
n
)
c
o
u
n
t
d
o
w
n
(
n
-
1
)
countdown(3)
The output looks like this:
3
2
1
B
l
a
s
t
o
f
f
!
9. Infinite Recursion:
If a recursion never reaches a base case, it goes on making recursive calls
forever, and the program never terminates. This is known as infinite
recursion.Here is a minimal program with an infinite recursion:
def recurse():
recurse()
10.Keyboard Input:
Python provides a built-in function called input() to read a value from
key board. For ex
print('Enter Your x
print('Hello, ' + x)
Definition and Usage
The input() function allows user input.
Syntax input(prompt) Parameter Values
Parameter Description
prompt A String, representing a default message before the input.
Example
Use the prompt parameter to write a message before the input:
x= input('Enter your name:') print('Hello, ' + x)
Note: input() function always reads string input. There to read int or
float input values we should convert string input to the respective types
using functions int(), float() ect..
For ex:
str_a = input(enter value)'
b = 10
c = int(str_a) + b print ("The value of c = ",c)
o/p:
enter value:
42
The value of c =52
Chapter-3
Fruitful Functions
1. Return values:
The return keyword is to exit a function and return a value.
Syntax:
Return or return value:
For ex :
def
myfunction():
return 3+3
print("Hello, World!")
pr
in
t(
m
yf
u
n
ct
io
n(
))
o
ut
p
ut
:
6.
2. Incremental Development:
incremental development is to avoid long debugging sessions by
adding and testing only a small amount of code at a time(i.e. develop
complex programs step by step).
For ex develop a program to find distance between two points
In Step1 we just define function with empty body as
follows def distance(x1, y1, x2, y2):
return 0.0
To test the new function, call it with sample arguments:
>>> distance(1, 2, 4, 6)
The output is 0.0 as there is no code to compute distance.
At this point we have confirmed that the function is syntactically
correct, and we can start adding code to the body.
So in step 2 it is to find the differences x2 − x1 and y2 − y1.
The next version stores those values in temporary variables and
prints them: def distance(x1, y1, x2, y2): dx = x2 - x1 dy = y2
- y1 print('dx is', dx) print('dy is', dy) return 0.0 in step 3 we
compute the sum of squares of dx and dy: def distance(x1, y1,
x2, y2): dx = x2 - x1 dy =
y
2
-
y
1
dsquared
= dx**2 +
dy**2
print('dsq
uared is: ',
dsquared)
return
0.0
Again, you would run the program at this stage and check the output
(which should be 25).
Finally in step 4, you can use math.sqrt to
compute and return the result: def distance(x1,
y1, x2, y2): dx =
x
2
-
x
1
d
y
=
y
2
-
y
1
dsquared = dx**2 +
dy**2 result =
math.sqrt(ds
quared)
return result
The key aspects of the process are:
1. Start with a working program and make small incremental changes. At any
point, if there is an error, you should have a good idea where it is.
2. Use variables to hold intermediate values so you can display and check
them.
3. Once the program is working, you might want to remove some of the
scaffolding or consolidate multiple statements into compound expressions,
but only if it does not make the program difficult to read.
3. Composition:
A complex program developed in small functions separately and write function calls to
them in proper sequence to achieve the functionality of complex program is called
composition.
For ex: we want a function to compute the area of the circle.
Assume that the center point is stored in the variables xc and yc, and the perimeter
point is in xp and yp.
The first step is to find the radius of the circle, which is the distance between
the two points. We just wrote a function, distance, that does that: radius =
distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that radius; we just wrote that, too:
result = area(radius)
Encapsulating these steps in a
function, we get: def
circle_area(xc, yc, xp, yp):
radius =
distance(xc, yc,
xp, yp)
result =
area(radius)
return result
The temporary variables radius and result are useful for development
and debugging, but once the program is working, we can make it more
concise by composing the function calls: def circle_area(xc, yc, xp,
yp): return area(distance(xc, yc, xp, yp))
4.Boolean Functions
Functions can return Booleans. For
example: def is_divisible(x, y):
if x % y == 0:
r
e
t
u
r
n
T
r
u
e
e
l
s
e
:
return False
>>>
is_divisible(6,
4) False
>>>
is_divisible(6,
3) True
5.More Recursion:
The function calls it self is called recursion . For ex consider factorial of a number.
The definition of factorial says that the factorial of 0 is 1, and the factorial of
any other value n is, n multiplied by the factorial of n-1.
de
f
fa
ct
or
ial
(n
):
if
n
=
=
0:
r e
t
u
r
n
1
e
l
s
e
:
recurse =
factorial(n-1)
result = n
* recurse
return
result
6.Leap of Faith:
Leap of Faith means when you come to a function call, instead of
following the flow of execution, you assume that the function
works correctly and returns the right result.
For example built in functions .i.e. When you call math.cos or math.exp, you
don’t examine the bodies of those functions.
7.Checking Types
What happens if we call factorial and give it 1.5 as an argument?
>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded Why because In the
first recursive call, the value of n is 0.5. In the next, it is -0.5. From there, it
gets smaller (more negative), but it will never be 0.
To avoid this situation we have to check input type.using the built-in function
isinstance to verify the type of the argument.
For ex:
def factorial (n):
if not isinstance(n,
int): print('Factorial
is only defined for
integers.') return
None elif n < 0:
print('Factorial is not
defined for negative
integers.') return None elif n
== 0: r e t
u
r
n
1
e
l
s
e
:
return n * factorial(n-1)
The first base case handles nonintegers; the second handles negative
integers. In both cases, the program prints an error message and returns
None to indicate that something went wrong: Checking Types | 69
>>> factorial('fred')
Factorial is only defined for integers. None
>>> factorial(-2)
Factorial is not defined for negative integers. None
If we get past both checks, we know that n is positive or zero, so we
can prove that the recursion terminates.This program demonstrates
a pattern sometimes called a guardian. The first two conditionals
act as guardians, protecting the code that follows from values that
might cause an error. The guardians make it possible to prove the
correctness of the code.
UNIT 3
Chapte
r-1
Iterati
on
1. Re Assignment:
In python it is legal to make more than one assignment to the same variable.
A new assignment makes an existing variable refer to a new value (and
stop referring to the old value).
>>> x = 5
>
>
>
x
5
>>> x = 7
>
>
>
x
7
The first time we display x, its value is 5; the second
time, its value is 7. Figure 7-1 shows what
reassignment looks like in a
state diagram.
2. Updating Variables:
A common kind of reassignment is an update, where the new
value of the variable depends on the old. >>> x = x + 1
This means “get the current value of x, add one, and then
update x with the new value.” If you try to update a variable
that doesn’t exist, you get an error, because Python
evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it,
usually with a simple assignment: >>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment;
subtracting 1 is called a decrement.
3. The While Statement:
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is − while
expression: statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates while
the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
For
Ex:
cou
nt =
0
whil
e
(
cou
nt <
9):
print 'The
count is:',
count count =
count + 1
print "Good bye!"
When the above code is executed, it produces the
following result − The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The
count is:
8 Good
bye!
Using else Statement with While Loop
Python supports to have an else statement associated with a loop statement.
If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
The following example illustrates the combination of an else statement with a
while statement that prints a number as long as it is less than 5, otherwise else
statement gets executed. count = 0 while count < 5:
print count, " is less than 5"
count = count + 1
else: print count,
" is not less than
5"
When the above code is executed, it produces the following result − 0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
3. Break :
It terminates the current loop and resumes execution at the next statement, just like
the traditional break statement in C.
Syntax
The syntax for a break statement in
Python is as follows − break
Note: If you we use nested loops, the break statement stops the
execution of the innermost loop and start executing the next line of
code after the block. For ex: for letter in 'Python': # First Example if
letter == 'h':
bre
ak
print 'Current Letter :', letter
var = 10 # Second
Example while var >
0: print 'Current
variable value :',
var
var
=
var -
1 if
var
==
5:
bre
ak
print "Good bye!"
When the above code is executed, it produces the following
result – Current Letter : P
Current Letter : y
Current Letter : t
Current variable value :
10 Current variable
value : 9
Current variable value : 8
Current variable value : 7
Current variable
value : 6 Good bye!
4. Square Roots:
Python number method sqrt() returns the square
root of x for x > 0. Syntax
Following is the syntax for
sqrt() method − import
math
math.sqrt( x )
Note − This function is not accessible directly, so we need to import
math module and then we need to call this function using math static
object. Parameters x − This is a numeric expression. Return Value
This method returns square root of x for x > 0.
Example
The following example shows the usage of sqrt() method.
#!/usr/bin/
python
import math # This will import math module
print "math.sqrt(100)
: ", math.sqrt(100)
print
"math.sqrt(7) : ", math.sqrt(7)
print "math.sqrt(math.pi) : ", math.sqrt(math.pi)
When we run above program, it produces following result −
math.sqrt(100) : 10.0
math.sqrt(7) : 2.64575131106
math.sqrt(math.pi) :
1.77245385091
Algorithms
Newton’s method is an example of an algorithm: it is a mechanical
process for solving a category of problems (in this case, computing
square roots).Some kinds of knowledge are not algorithmic. For example,
learning dates from history or your multiplication tables involves
memorization of specific solutions.But the techniques you learned for
addition with carrying, subtraction with borrowing, and long division are
all algorithms. Or if you are an avid Sudoku puzzle solver, you might
have some specific set of steps that you alwaysfollow.
One of the characteristics of algorithms is that they do not require any
intelligence to carry out. They are mechanical processes in which each
step follows from the last according to a simple set of rules. And they’re
designed to solve a general class or category of problems, not just a single
problem.Understanding that hard problems can be solved by step-by-step
algorithmic processes (and having technology to execute these algorithms
for us) is one of the major breakthroughs that has had enormous benefits.
So while the execution of the algorithm may be boring and may require
no intelligence, algorithmic or computational thinking — i.e. using
algorithms and automation as the basis for approaching problems — is
rapidly transforming our society. Some claim that this shift towards
algorithmic thinking and processes is going to have even more impact on
our society than the invention of the printing press. And the process of
designing algorithms is interesting, intellectually challenging, and a
central part of what we call programming.
Some of the things that people do naturally, without difficulty or
conscious thought, are the hardest to express algorithmically.
Understanding natural language is a good example. We all do it, but so far
no one has been able to explain how we do it, at least not in the form of
astep- by-step mechanical algorithm.
Chapter-2
S
trings A string is a sequence
A string is a sequence of characters. You can access the characters one
at a time with the bracket operator: >>> fruit = 'banana'
>>> letter = fruit[1]
The second statement selects character number 1 from fruit and assigns
it to letter.The expression in brackets is called an index. The index
indicates which character in the sequence you want len. len is a built-in
function that returns the number of characters in a string: >>> fruit =
'banana'
>>>
l
e
n
(
f
r
u
i
t
)
6
To get the last letter of a string, you might be tempted to try something
like this: >>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
The reason for the IndexError is that there is no letter in 'banana' with the index 6.
Since we started counting at zero, the six letters are numbered 0 to 5. To get the
last character, you have to subtract 1 from length:
>>> last = fruit[length-1]
>
>
>
l
a
s
t
'
a
'
Or you can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,and
so on.
2. Traversal With A For Loop:
Traversal : visiting each character in the string is called string
traversal. We can do string traversing with either while or for
statements. For ex: for letter in 'Python': # First Example print
'Current
Letter
:',
letter
out
put: P
Y
T
H
O
n
3. String Slicing In Python:
Python slicing is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Python slicing can be done in two ways.
slice()
Constructor
E
xt
en
di
ng
In
de
xi
ng
sli
ce
()
Constructor
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Syntax: slice(stop) slice(start, stop, step) Parameters: start: Starting index
where the slicing of object starts. stop: Ending index
where the slicing of object stops. step: It is an optional argument that
determines the increment between each index for slicing. Return Type: Returns
a sliced object containing elements in the given range only. Example
# Python program to
demonstrate # string
slicing
# String slicing String ='ASTRING'
# Using
slice
constructor
s1
=slice(3)
s2 =
slice(1, 5,
2) s3 =
slice(-1, -
12, -2)
print("Stri
ng
slicing")
print(Strin
g[s1])
print(Strin
g[s2])
print(Strin
g[s3])
Output:
String
slicing
AST
S
R
G
I
T
A
Extending indexing
In Python, indexing syntax can be used as a substitute for the slice object.
This is an easy and convenient way to slice a string both syntax wise and
execution wise. Syntax string[start:end:step] start, end and step have the
same mechanism as slice() constructor.
Example
# Python program to
demonstratestring slicing
String ='ASTRING' #
Using indexing sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2]) #
Prints string in reverse
print("nReverse String")
print(String[::-1]) Output:
A
S
T
S
R
G
I
T
A
Reverse
String
GNIRT
SA
4. Strings Are Immutable :
In python, the string data types are immutable. Which means a string
value cannot be updated. We can verify this by trying to update a part of
the string which will led us to an error. # Can not reassign t= "Tutorialsp
oint" print type(t) t[0] = "M"
When we run the above program, we get the following output −
t[0] = "M"
TypeError: 'str' object does not support item assignment
5. Searching: Traversing in sequence and returning a character when we find what we are
looking
for—is called a search.
For ex:
def
find(wo
rd,
letter):
index = 0
while index
<
len(word):
if
word[index
] == letter:
return
index
index =
ind
ex
+
1
ret
ur
n -
1
String functions for
searching: find():
The find() method finds the first occurrence of the specified value. The find()
method returns -1 if the value is not found.
Syntax
string.find(value,
start, end)
Parameter Values
Parameter Description
Value Required. The value to search for
Start Optional. Where to start the search.
Default is 0
End Optional. Where to end the search.
Default is to the end of the string
More Examples
Example
Where in the text is the first occurrence of the letter "e"?:
txt = "Hello, welcome to my world."
x = txt.find("e")
p
r
i
n
t(
x
)
E
x
a
m
p
l
e
Where in the text is the first occurrence of the letter "e" when you only
search between position 5 and 10?:
txt = "Hello, welcome to my world."
x = txt.find("e", 5, 10)
print(x)
7. Looping And Counting
The following program counts the number of times the letter
a appears in a string: word = 'banana' count = 0 for letter in
word:
if letter == 'a':
count = count + 1
print(count)
This program demonstrates another pattern of computation called a counter.
The variable count is initialized to 0 and then incremented each time an a is
found. When the loop exits, count contains the result—the total number of
a’s.
8. String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original
string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of
where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified
value
rfind() Searches the string for a specified value and returns the last position
of where it was found
rindex() Searches the string for a specified value and returns the last position
of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
9. The In Operator:
The word in is a boolean operator that takes two strings and returns True if
the first appears as a substring in the second:
>>> 'a' in
'banana'
True
>>> 'seed' in
'banana' False
10. STRING COMPARISON
The relational operators work on strings. To see if two
strings are equal: if word == 'banana':
print('All right, bananas.')
Other relational operations are useful for putting words in
alphabetical order: if word < 'banana':
print('Your word, ' + word + ', comes
before banana.') elif word > 'banana':
print('Your word, ' + word + ', comes
after banana.') else: print('All right,
bananas.')
Python does not handle uppercase and lowercase letters the same way people do.
All the uppercase letters come before all the lowercase
letters, so: Your word, Pineapple, comes before banana.
Chapter-3
Case study
1. Reading word lists:
There are lots of word lists available on the Web, but the one most
suitable for our purpose is one of the word lists collected and contributed
to the public domain by Grady Ward as part of the Moby lexicon project1
.
It is a list of 113,809 official crosswords; that is, words that are
considered valid in crossword puzzles and other word games.
In the Moby collection, the filename is 113809of.fic; I include a copy of this
file, with the simpler name words.txt, along with Swampy.
This file is in plain text, so you can open it with a text editor, but you can
also read it from Python. The built-in function open takes the name of the
file as a parameter and returns a file object you can use to read the file.
>>> fin =
open('words.txt')
>>> print fin
<open file 'words.txt', mode 'r' at 0xb7f4b380>
fin is a common name for a file object used for input. Mode 'r' indicates that
this file is open for reading (as opposed to 'w' for writing).
The file object provides several methods for reading, including readline, which
reads characters from the file until it gets to a newline and returns the result as a
string:
>>>
f
i
n
.
r
e
a
d
l
i
n
e
(
)
'
a
a

r
n
'
The first word in this particular list is “aa,” which is a kind of lava. The
sequence rn represents two whitespace characters, a carriage return and a
newline, that separate this word from the next.
The file object keeps track of where it is in the file, so if you call readline
again, you get the next word:
>>>
f
i
n
.
r
e
a
d
l
i
n
e
(
)
'
a
a
h

r

n
'
The next word is “aah,” which is a perfectly legitimate word, so stop
looking at me like that. Or, if it’s the whitespace that’s bothering you, we
can get rid of it with the string method strip: >>> line = fin.readline()
>>>
word =
line.strip(
) >>>
print
word
aahed
You can also use a file object as part of a for loop. This program reads
words.txt and prints each word, one per line:
fin =
open('words.txt')
for line in fin:
word =
line.strip() print
word
2. Search
All of the exercises in the previous section have something in common;
The simplest example is: def has_no_e(word):
for
le
tt
er
in
w
or
d:
if
le
tt
er
=
=
'e'
:
re
tu
rn
F
al
se
return True
The for loop traverses the characters in word. If we find the letter “e”, we
can immediately return False; otherwise we have to go to the next letter.
If we exit the loop normally, that means we didn’t find an “e”, so we
return True.
You can write this function more concisely using the in operator, but I started
with this version because it demonstrates the logic of the search pattern.
avoids is a more general version of has_no_e but it has the same
structure: def avoids(word, forbidden):
for letter in word:
if letter in forbidden:
return False
return True
We can return False as soon as we find a forbidden letter; if we get to the end
of the loop, we return True.
uses_only is similar except that the sense of
the condition is reversed: def uses_only(word,
available): for letter in word:
if letter
not in
available:
return
F
a
l
s
e
r
e
t
u
r
n
T
r
u
e
Instead of a list of forbidden words, we have a list of available words. If
we find a letter in word that is not in available, we can return
False.uses_all is similar except that we reverse the role of the word and
the string of letters: def uses_all(word, required):
for
letter
in
requi
red:
if
letter
not
in
word
:
retur
n
False
retur
n
True
Instead of traversing the letters in word, the loop traverses the required
letters. If any of the required letters do not appear in the word, we can return
False.
If you were really thinking like a computer scientist, you would have
recognized that uses_all was an instance of a previously-solved problem, and
you would have written:
def uses_all(word,
required): return
uses_only(required,
word)
This is an example of a program development method called problem
recognition, which means that you recognize the problem you are working
on as an instance of a p reviously- solved problem, and apply a previously-
developed solution.
3. Looping with indices
I wrote the functions in the previous section with for loops because I only needed
the
characters in the strings; I didn’t have to do anything with the indices.For
is_abecedarian we have to compare adjacent letters, which is a little
tricky with a for loop:
Def is_abecedarian(word):
previous = word[0]
f
or
c
in
w
or
d:
if
c
<
pr
e
vi
o
us
:
re
tu
rn
F
al
se
previous = c
return True
An alternative is to use recursion:
def is_abecedarian(word):
if
len(word
) <= 1:
return
True
if word[0] > word[1]:
return False return
is_abecedarian(word[1:])
Another option is to use a
while loop:
def
is_abecedari
an(word): i
= 0 while i
<
len(word)-
1: if
word[i+1] <
word[i]:
return False
i = i+1
return True
The loop starts at i=0 and ends when i=len(word)-1. Each time through the loop, it
compares the ith character (which you can think of as the current character) to the
i+1th character (which you can think of as the next).
If the next character is less than (alphabetically before) the current one, then we have
discovered a break in the abecedarian trend, and we return False.
If we get to the end of the loop without finding a fault, then the word passes the test.
To convince yourself that the loop ends correctly, consider an example like 'flossy'.
The length of the word is 6, so the last time the loop runs is when i is 4, which is the
index of the second- to-last character. On the last iteration, it compares the second-
to-last character to the last, which is what we want.
Here is a version of is_palindrome (see Exercise 6.6) that uses two indices; one starts at
the beginning and goes up; the other starts at the end and goes down.
def is_palindrome(word):
i = 0
j = len(word)-1
while i<j:
if word[i] !=
word[j]:
return False
i
=
i
+
1
j
=
j
-
1
True
Or, if you noticed that this is an instance of a previously-solved problem, you might
have written: def is_palindrome(word):
return is_reverse(word,
word)
Chapter-4
LIST
Python offers a range of compound datatypes often referred to as sequences. List is one of the
most frequently used and very versatile datatype used in Python.
How to create a list?
In Python programming, a list is created by placing all the items (elements) inside a
square bracket [ ], separated by commas.It can have any number of items and they may
be of different types (integer, float, string etc.).
#
empt
y list
my_
list =
[] #
list
of
integ
ers
my_
list =
[1,
2, 3]
# list with mixed
datatypes my_list =
[1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested
list. # nested list
my_list = ["mouse", [8, 4, 6], ['a']]
How to access elements from a list?
There are various ways in which we can access the elements
of a list. List Index
We can use the index operator [] to access an item in a list. Index starts from 0. So,
a list having 5 elements will have index from 0 to 4.
Trying to access an element other that this will raise an IndexError. The index must be an
integer.
We can't use float or other types, this will result into TypeError.
Nested list are accessed using nested indexing.
my_list = ['p','r','o','b','e']
# Output: p print(my_list[0])
# Output: o print(my_list[2])
# Output: e
print(my_list[4])
# Error! Only integer can be used for indexing
# my_list[4.0]
# Nested List n_list =
["Happy", [2,0,1,5]]
# Nested indexing
# Output: a print(n_list[0]
[1])
# Output: 5 print(n_list[1]
[3])
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.
my_list =
['p','r','o','b','e']
# Output: e
print(my_list[-
1])
# Output: p
print(my_list[-
5])
4. List Slices:
How to slice lists in Python?
We can access a range of items in a list by using the slicing operator (colon).
my_list =
['p','r','o','g','r','a
','m','i','z']
# elements 3rd
to 5th
print(my_list[2
:5])
# elements
beginning to
4th
print(my_list[:-
5])
# elements 6th
to end
print(my_list[5
:])
# elements
beginning to
end
print(my_list[:]
)
Slicing can be best visualized by considering the index to be between the elements
as shown below. So if we want to access a range, we need two index that will slice
that portion from the list.
1.List is a sequence:
The most basic data structure in Python is the sequence. Each element of a sequence
is assigned a number - its position or index. The first index is zero, the second index
is one, and so forth. Python has six built-in types of sequences, but the most common
ones are lists and tuples, which we would see in this tutorial.
There are certain things you can do with all sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list
of comma- separated values (items) between square brackets. Important thing about
a list is that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between
square brackets. For example − list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2,
3, 4, 5 ];
list3 = ["a",
"b", "c",
"d"]
Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or
indices to obtain value available at that index. For example −
#!/usr/bin/
python
list1 = ['physics', 'chemistry',
1997, 2000];
list2 = [1, 2, 3,
4, 5, 6, 7 ]; print
"list1[0]: ",
list1[0] print
"list2[1:5]: ",
list2[1:5] When
the above code
is executed, it
produces the
following result
− list1[0]:
physics
list2[1:5]: [2, 3,
4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to elements
in a list with the append() method. For example −
#!/usr/bin/
python
list = ['physics', 'chemistry',
1997, 2000];
print "Value available at index
2 : "
print list[2] list[2] = 2001;
print "New value available at
index 2 : " print list[2]
Note − append() method is discussed in subsequent
section. When the above code is executed, it produces
the following result −
Value available at index 2 :1997
New value available at index 2 :2001
Lists are Mutable
Unlike strings, lists are mutable. This means we can change an item in a
list by accessing it directly as part of the assignment statement. Using the
indexing operator (square brackets) on the left side of an assignment, we
can update one of the list items. fruit = ["banana", "apple", "cherry"]
print(fruit)
fruit[0] =
"pear"
fruit[-1] =
"orange"
print
(fruit
)
outp
ut:
['banana', 'apple', 'cherry']
['pear', 'apple', 'orange']
An assignment to an element of a list is called item assignment. Item
assignment does not work for strings. Recall that strings are immutable.
Here is the same example in codelens so that you can step through the
statements and see the changes to the list elements.
By combining assignment with the slice operator we can update
several elements at once. alist = ['a', 'b', 'c', 'd', 'e', 'f']
alist[1:3] = ['x',
'y'] print(alist)
output:
['a', 'x', 'y', 'd', 'e', 'f']
We can also remove elements from a list by assigning the empty list
to them. alist = ['a', 'b', 'c', 'd', 'e', 'f']
alist[1:3] = []
print(alist)
output:
['a', 'd', 'e', 'f']
6.map(), filter(), and reduce() in Python
Introduction
The map(), filter() and reduce() functions bring a bit of functional
programming to
Python. All three of these are convenience functions that can be replaced
with List Comprehensions or loops, but provide a more elegant and short-
hand approach to some problems.
Before continuing, we'll go over a few things you should be familiar with
before reading about the aforementioned methods:
What is an anonymous function/method or lambda?
An anonymous method is a method without a name, i.e. not bound to an
identifier like when we define a method using def method:.
Note: Though most people use the terms "anonymous function" and
"lambda function" interchangeably - they're not the same. This mistake
happens because in most programming languages lambdas are
anonymous and all anonymous functions are lambdas. This is also the
case in Python. Thus, we won't go into this distinction further in this
article.
What is the syntax of a lambda function (or lambda
operator)? lambda arguments: expression
Think of lambdas as one-line methods without a name. They work
practically the same as any other method in Python, for example:
def
add(x,y):
return x + y
Can be
translated to:
lambda x, y: x
+ y
Lambdas differ from normal Python methods because they can have only
one expression, can't contain any statements and their return type is a
function object. So the line of code above doesn't exactly return the value
x + y but the function that calculates x + y.
Why are lambdas relevant to map(), filter() and
reduce()?
All three of these methods expect a function object as the first argument.
This function object can be a pre-defined method with a name (like def
add(x,y)).Though, more often than not, functions passed to map(), filter(),
and reduce() are the ones you'd use only once, so there's often no point in
defining a referenceable function.
To avoid defining a new function for your different map()/filter()/reduce()
needs - a more elegant solution would be to use a short, disposable,
anonymous function that you will only use once and never again - a
lambda.
The map() Function
The map() function iterates through all items in the given iterable and
executes the function we passed as an argument on each of them.
The syntax is:
map(function, iterable(s))
We can pass as many iterable objects as we want after passing the
function we want to use:
# Without
using
lambda
s def
starts_
with_A
(s):
return s[0] == "A"
fruit = ["Apple", "Banana", "Pear", "Apricot",
"Orange
"]
map_object = map(starts_with_A,
fruit)
print(list(map_o
bject)
)
This code will result in:
[True, False, False, True, False]
As we can see, we ended up with a new list where the function
starts_with_A() was evaluated for each of the elements in the list fruit.
The results of this function were added to the list sequentially.
A prettier way to do this exact same thing is by using lambdas:
fruit = ["Apple", "Banana", "Pear", "Apricot", "Orange"]
map_object = map(lambda s: s[0] == "A",
fruit)
print(list(map_o
b
ject))
We get the same output:
[True, False, False, True, False]
Note: You may have noticed that we've cast map_object to a list to print
each element's value. We did this because calling print() on a list will print
the actual values of the elements. Calling print() on map_object would
print the memory addresses of the values instead.
The map() function returns the map_object type, which is an iterable and
we could have printed the results like this as well:
for value in
map_object:
print(value
)
If you'd like the map() function to return a list instead, you can just cast it
when calling the function: result_list = list(map(lambda s: s[0] == "A",
fruit)) The filter() Function
Similar to map(), filter() takes a function object and an iterable and
creates a new list. As the name suggests, filter() forms a new list that
contains only elements that satisfy a certain condition, i.e. the function
we passed returns True.
The syntax is:
filter(function, iterable(s))
Using the previous example, we can see that the new list will only contain
elements for which the starts_with_A() function returns True:
# Without
using
lambda
s def
starts_
with_A
(s):
return
s[0] ==
"A"
fruit = ["Apple", "Banana", "Pear", "Apricot",
"Orange
"]
filter_object = filter(starts_with_A,
fruit)
print(list(filter_object))
Running this code will result in a shorter list:
['Apple', 'Apricot']
Or, rewritten using a lambda:
fruit = ["Apple", "Banana", "Pear", "Apricot",
filter_object = filter(lambda s: s[0] ==
print(list(filt
er_object))
Printing
gives us the
same output:
['Apple',
'Apricot']
The reduce() Function
reduce() works differently than map() and filter(). It does not return a new
list based on the function and iterable we've passed. Instead, it returns a
single value.Also, in Python reduce() isn't a built-in function anymore,
and it can be found in the functools module.
The syntax is:
reduce(function,
sequence[, initial])
reduce() works by calling the function we passed for the first two items in
the sequence. The result returned by the function is used in another call to
function alongside with the next (third in this case), element.
"Orange
"]
"A",
fruit)
This process repeats until we've gone through all the elements in the
sequence.
The optional argument initial is used, when present, at the beginning of
this "loop" with the first element in the first call to function. In a way, the
initial element is the 0th element, before the first one, when provided.
reduce() is a bit harder to understand than map() and filter(), so let's look
at a step by step example:
We start with a list [2, 4, 7, 3] and pass the add(x, y) function to reduce()
alongside this list, without an initial value calls add(2, 4), and
add() returns 6
calls add(6, 7) (result of the previous call to add() and the next element in the
list as parameters), and
add() returns 13 reduce() calls
add(13, 3), and add() returns 16
Since no more elements are left in the sequence, reduce() returns 16
The only difference, if we had given an initial value would have been an additional step -
1.5. where reduce() would call add(initial, 2) and use that return
value in step 2. Let's go ahead and use the reduce() function:
from functools import reduce
def
add(x,
y):
return
x + y
list = [2, 4, 7, 3]
print(reduce(add, list))
Running this code would yield: 16
Again, this could be written using lambdas:
from functools import reduce
list = [2, 4, 7, 3]
print(reduce(lambda x, y: x + y, list))
print("With an initial value: " + str(reduce(lambda x,
y: x + y, list, 10)))
And the code would result in:16
With an initial value: 26
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly
which element(s) you are deleting or the remove() method if you do not know. For
example −
#!/usr/bin/python
list1 = ['physics', 'chemistry', 1997, 2000];
print list1 del list1[2];
print "After deleting value at
index 2 : " print list1
When the above code is executed, it produces
following result − ['physics', 'chemistry', 1997,
reduce()
reduce()
2000] After deleting value at index 2 : ['physics',
'chemistry', 2000]
Note − remove() method is discussed in subsequent section.
4. Basic List Operations
Lists respond to the + and * operators much like strings; they mean concatenation
and repetition here too, except that the result is a new list, not a string.
In fact, lists respond to all of the general sequence operations we used on
strings in the prior chapter.
Python Expression Results Description
len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration
List Operations:
How to change or add elements to a list?
List are mutable, meaning, their elements can be changed unlike string or tuple.
We can use assignment operator (=) to change an item or a range of items.
# mistake values
odd = [2, 4, 6, 8]
# change the 1st item
odd[0] = 1
# Output: [1, 4, 6, 8]
print(odd)
# change 2nd to 4th items
odd[1:4] = [3, 5, 7]
# Output: [1, 3, 5, 7]
print(odd)
We can add one item to a list using append() method or
add several items using extend()method. odd = [1, 3, 5]
odd.ap
pend(7
) #
Output
: [1, 3,
5, 7]
print(o
dd)
odd.ex
tend([9
,
11, 13])
# Output: [1, 3, 5, 7, 9, 11, 13]
print(odd)
We can also use + operator to combine two lists. This is also called
concatenation. The * operator repeats a list for the given number of
times.
odd = [1, 3, 5]
# Output: [1, 3, 5, 9, 7, 5] print(odd + [9, 7, 5])
#Output: ["re", "re", "re"] print(["re"] * 3)
Furthermore, we can insert one item at a desired location by using the method insert() or
insert multiple items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
# Output: [1, 3,
9] print(odd)
odd[2:2] = [5,
7]
# Output: [1, 3,
5, 7, 9]
print(odd)
How to delete or remove elements from a list?
We can delete one or more items from a list using the keyword del. It can even delete
the list entirely.
my_list = ['p','r','o','b','l','e','m']
# delete one item
del my_list[2]
# Output: ['p', 'r', 'b', 'l', 'e', 'm']
print(my_list)
# delete multiple items
del my_list[1:5]
# Output: ['p', 'm']
print(my_list)
# delete entire list
del my_list
# Error: List not defined
print(my_list)
We can use remove() method to remove the given item or pop() method to remove
an item at the given index. The pop() method removes and returns the last item if
index is not provided. This helps us implement lists as stacks (first in, last out data
structure).
We can also use the clear() method to empty a list.
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'o'
print(my_list.pop(1))
# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)
# Output: 'm'
print(my_list.pop())
# Output: ['r', 'b', 'l', 'e']
print(my_list)
my_list.clear()
# Output: [] print(my_list)
Finally, we can also delete items in a list by assigning an empty list to a slice of
elements.
>>> my_list =
['p','r','o','b','l','e
','m']
>>>
my_list[2:3] =
[]
>>> my_list
['p', 'r', 'b', 'l',
'e', 'm']
>>>
my_list[2:5] =
[]
>>> my_list
['p', 'r', 'm']
5.Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input − L = ['spam', 'Spam', 'SPAM!']
Python Expression Results Description
L[2] SPAM! Offsets start at zero
L[-2] Spam Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
6.Python List Methods
Methods that are available with list object in Python programming are tabulated
below.They are accessed as list.method(). Some of the methods have already been used
above.
Python List Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
count() - Returns the count of number of items passed as an argument
sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Some examples of Python list methods:
my_list = [3, 8,
1, 6, 0, 8, 4]
# Output: 1
print(my_list.in
dex(8))
# Output: 2
print(my_list.c
ount(8))
my_list.sort()
# Output: [0, 1,
3, 4, 6, 8, 8]
print(my_list)
my_list.reverse
()
# Output: [8, 8,
6, 4, 3, 1, 0]
print(my_list)
Built-in Functions with List
Built-in functions like all(), any(), enumerate(), len(), max(), min(), list(), sorted() etc.
are commonly used with list to perform different tasks.
Built-in Functions with List
Function Description
all() Return True if all elements of the list are true (or if the list is empty).
any() Return True if any element of the list is true. If the list is empty, return False.
enumerate()
Return an enumerate object. It contains the index and value of all the items of
list as a tuple.
len() Return the length (the number of items) in the list.
list() Convert an iterable (tuple, string, set, dictionary) to a list.
max() Return the largest item in the list.
min() Return the smallest item in the list
sorted() Return a new sorted list (does not sort the list itself).
sum() Return the sum of all elements in the list.
Strings in Python A string is a sequence of characters. It can be declared in
python by using double-quotes. Strings are immutable, i.e., they cannot be
changed. # Assigning string to a variable a = "This is a string" print (a)
Lists in Python Lists are one of the most powerful tools in python. They are just
like the arrays declared in other languages. But the most powerful thing is that list
need not be always homogeneous. A single list can contain strings, integers, as well
as objects. Lists can also be used for implementing stacks and queues. Lists are
mutable, i.e., they can be altered once declared.
# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
L.a
ppe
nd(
6)
prin
t L
L.p
op()
prin
t L
prin
t
L[1
]
The output is :
[1, 'a', 'string', 3]
[1, 'a', 'string', 3, 6]
[1, 'a', 'string', 3] a
Objects and values
Objects are Python's abstraction for data. All data in a Python program is represented by objects
or by relations between objects. (In a sense, and in conformance to Von Neumann's model of a
``stored program computer,'' code is also represented by objects.)
Every object has an identity, a type and a value. An object's identity never changes once it has
been created; you may think of it as the object's address in memory. The `is' operator compares
the identity of two objects; the id() function returns an integer representing its identity (currently
implemented as its address). An object's type is also unchangeable. It determines the operations
that an object supports (e.g., ``does it have a length?'') and also defines the possible values for
objects of that type. The type() function returns an object's type (which is an object itself). The
value of some objects can change. Objects whose value can change are said to be mutable;
objects whose value is unchangeable once they are created are called immutable. (The value of an
immutable container object that contains a reference to a mutable object can change when the
latter's value is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed. So, immutability is not strictly the same as
having an unchangeable value, it is more subtle.) An object's mutability is determined by its type;
for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.
Objects are never explicitly destroyed; however, when they become unreachable they may be
garbage- collected. An implementation is allowed to postpone garbage collection or omit it
altogether -- it is a matter of implementation quality how garbage collection is implemented, as
long as no objects are collected that are still reachable. (Implementation note: the current
implementation uses a reference-counting scheme which collects most objects as soon as they
become unreachable, but never collects garbage containing circular references.)
Note that the use of the implementation's tracing or debugging facilities may keep objects alive
that would normally be collectable. Also note that catching an exception with a try...except'
statement may keep objects alive.
Some objects contain references to ``external'' resources such as open files or windows. It is
understood that these resources are freed when the object is garbage-collected, but since garbage
collection is not guaranteed to happen, such objects also provide an explicit way to release the
external resource, usually a close() method. Programs are strongly recommended to explicitly
close such objects. The `try...finally' statement provides a convenient way to do this.
Some objects contain references to other objects; these are called containers. Examples of
containers are tuples, lists and dictionaries. The references are part of a container's value. In most
cases, when we talk about the value of a container, we imply the values, not the identities of the
contained objects; however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied. So, if an immutable container (like a tuple)
contains a reference to a mutable object, its value changes if that mutable object is changed.
Aliasing
Since variables refer to objects, if we assign one variable to another, both variables refer to the
same object: a = [81, 82, 83]
b = a print(a is b)
o
u
t
p
u
t
:
T
r
u
e
In this case, the reference diagram looks like this:
Because the same list has two different names, a and b, we say that it is aliased. Changes made
with one alias affect the other. In the codelens example below, you can see that a and b
refer to the same list after executing the assignment statement b = a.
1 a = [81, 82, 83]
2 b = [81, 82, 83]
4 print(a == b)
5 print(a is b)
7 b = a
8 print(a == b)
9 print(a is b)
b[0] = 5
12 print(a)
Using Lists as Parameters
Functions which take lists as arguments and change them during execution are called
modifiers and the changes they make are called side effects. Passing a list as an argument
actually passes a reference to the list, not a copy of the list. Since lists are mutable, changes made
to the elements referenced by the parameter change the same list that the argument is referencing.
For example, the function below takes a list as an argument and multiplies each element in the
list by 2: def doubleStuff(aList):
""" Overwrite each element in aList with double its
value. """ for position in range(len(aList)):
aList[position] = 2 * aList[position]
things = [2, 5, 9]
print(th
ings)
double
Stuff(th
ings)
print(th
ings)
output
:
[2,5,9]
[4, 10, 18]
The parameter aList and the variable things are aliases for the same object.
Since the list object is shared by two references, there is only one copy. If a function
modifies the elements of a list parameter, the caller sees the change since the change
is occurring to the original. This can be easily seen in codelens. Note that after the
call to doubleStuff, the formal parameter aList refers to the same object as the actual
parameter things. There is only one copy of the list object itself.
UNIT-IV
Chapter-1 Dictionaries
1.Dictionary in mapping:
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds
key:value pair. Key value is provided in the dictionary to make it more optimized.
2.Dictionary as a Counter:
Suppose you are given a string and you want to count how many times each letter appears. There are
several ways you could do it:
You could create 26 variables, one for each letter of the alphabet. Then you could traverse the string
and, for each character, increment the corresponding counter, probably using a chained conditional.
You could create a list with 26 elements. Then you could convert each character to a number (using
the built-in function ord), use the number as an index into the list, and increment the appropriate
counter.
You could create a dictionary with characters as keys and counters as the corresponding values. The
first time you see a character, you would add an item to the dictionary. After that you would
increment the value of a existing item.
Each of these options performs the same computation, but each of them implements that
computation in a different way.
An implementation is a way of performing a computation; some implementations are better than
others. For example, an advantage of the dictionary implementation is that we don’t have to know
ahead of time which letters appear in the string and we only have to make room for the letters that
do appear.
Here is what the code might look like:
word = 'brontosaurus'd = dict()for c in word: if c not in d: d[c] = 1 else: d[c] = d[c] +
1print d We are effectively computing a histogram, which is a statistical term for a set of
counters (or frequencies).
The for loop traverses the string. Each time through the loop, if the character c is not in the
dictionary, we create a new item with key c and the initial value 1 (since we have seen this letter
once). If c is already in the dictionary we increment d[c].
Here’s the output of the program:
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
The histogram indicates that the letters ’a’ and 'b' appear once; 'o' appears twice, and so on.
Dictionaries have a method called get that takes a key and a default value. If the key appears in the
dictionary, get returns the corresponding value; otherwise it returns the default value. For example:
>>> counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}>>> print counts.get('jan', 0)100>>> print
counts.get('tim', 0)0
We can use get to write our histogram loop more concisely. Because the get method automatically
handles the case where a key is not in a dictionary, we can reduce four lines down to one and
eliminate the if statement.
word = 'brontosaurus'd = dict()for c in word: d[c] = d.get(c,0) + 1print d
The use of the get method to simplify this counting loop ends up being a very commonly used
“idiom” in Python and we will use it many times the rest of the book. So you should take a moment
and compare the loop using
the if statement and in operator with the loop using the get method. They do exactly the same thing,
but one is more succinct.
3. Looping and Dictionary:
If you use a dictionary as the sequence in a for statement, it traverses the keys of the dictionary.
This loop prints each key and the corresponding value: counts = { 'chuck' : 1 , 'annie' : 42, 'jan':
100}for key in counts: print key, counts[key] Here’s what the output looks like: jan 100chuck
1annie 42
Again, the keys are in no particular order.
We can use this pattern to implement the various loop idioms that we have described earlier. For
example if we wanted to find all the entries in a dictionary with a value above ten, we could write
the following code: counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}for key in counts: if
counts[key] > 10 : print key, counts[key] The for loop iterates through the keys of the dictionary,
so we must use the index operator to retrieve the corresponding value for each key. Here’s what the
output looks like:
jan 100annie 42
We see only the entries with a value above 10.
If you want to print the keys in alphabetical order, you first make a list of the keys in the dictionary
using the keys method available in dictionary objects, and then sort that list and loop through the
sorted list, looking up each key printing out key/value pairs in sorted order as follows as follows:
counts = { 'chuck' : 1 , 'annie' : 42, 'jan': 100}lst = counts.keys()print lstlst.sort()for key in lst: print
key, counts[key]
Here’s what the output looks like:
['jan', 'chuck', 'annie']annie 42chuck 1jan 100
First you see the list of keys in unsorted order that we get from the keys
method. Then we see the key/value pairs in order from the for loop.
4. Reverse dictionary lookup in Python
Doing a reverse dictionary lookup returns a list containing each key in the dictionary that maps to
a specified value.
U S E dict.items() T O D O A R E V E R S E D I C T I O N A R Y L O O K U P
Use the syntax for key, value in dict.items() to iterate over each key, value pair in the dictionary
dict. At each iteration, if value is the lookup value, add key to an initially empty list.
print(a_dictionary)
O U T P U T
{'a': 1, 'b': 3, 'c': 1, 'd': 2}
lookup_value = 1
all_keys = [] for key,
value
ina_dictionary.items():
if(value == lookup_value):
all_keys.append(key)
print(all_keys)
O U T P U T
['a', 'c']
Use a dictionary comprehension for a more compact
implementation. all_keys = [key for key, value
ina_dictionary.items() if value == lookup_value]
print(all_keys)
O U T P U T
['a', 'c']
5. Dictionaries and Lists:
Lists are just like the arrays, declared in other languages. Lists need not be homogeneous always
which makes it a most powerful tool in Python. A single list may contain DataTypes like Integers,
Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their
creation. Example:
# Python program to demonstrate
# Lists
# Creating a List with
# the use of multiple
values List=["Geeks",
"For", "Geeks"] print("List
containing multiple values:
") print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
# (By Nesting a list
inside a List)
List=[['Geeks', 'For'] ,
['Geeks']] print("
nMulti-Dimensional
List: ") print(List)
Output:
List containing multiple values:
Geeks
Geeks
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Dictionary in Python on the other hand is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is
separated by a colon :, whereas each key is separated by a
‘comma’. Example:
# Python program to demonstrate
# dictionary
# Creating a Dictionary
# with Integer Keys
Dict={1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("Dictionary with the use of Integer Keys:
") print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict={'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("nDictionary with the use of
Mixed Keys: ") print(Dict) Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Difference between List and Dictionary:
LIST DICTIONARY
List is a collection of index values pairs Dictionary is a hashed structure of key and value pairs.
LIST DICTIONARY
as that of array in c++.
List is created by placing elements in [
] seperated by commas “, “
Dictionary is created by placing elements in { } as “key”:”value”,
each key value pair is seperated by commas “, ”
The indices of list are integers starting
from 0. The keys of dictionary can be of any data type.
The elements are accessed via indices. The elements are accessed via key-values.
The order of the elements entered are
maintained. There is no guarantee for maintaining order.
6. MEMO: memoize and keyed-memoize decorators.
memo: The classical memoize decorator. It keeps a cache so you don’t continue to
perform the
same computations. keymemo(key): This decorator factory act as but it permits to
specify a key function that takes the args of
the decorated function and computes a value to use as key in the cache dictionary. This
way you can for example use a single value of a dictionary as key of the cache, or
apply a function before passing something to the cache.
args ->
result
mem
o
ke
y
The classical memoize decorator that can be applied to class functions. It
keeps a cache tinue to perform the same computations. The cache is kept in
the class namespace.
: This decorator factory works like a combination of and
keymemo, so it
allows to specify a function that generate the cache key based on the function arguments and can be
applied to class functions.
Usage
From memo import memo
@memo
de
ffi
bo
na
cci
(n)
:
ifn
<=
2:
ret
ur
n1
returnfibonacci(n-1)
+fibonacci(n-2)
frommemoimportkeym
emo
@keymemo(lambdatu
p: tup[0])
deffunction(tup):
# build a cache based on the first value of a tuple
...
The package has been uploaded to PyPI, so you can install it with pip:
pip install python-memo
7. Python Global Variables
In this tutorial, you’ll learn about Python Global variables, Local variables, Nonlocal
variables and where to use them. Global Variables
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside of the function.
Let's see an example of how a global variable is
created in Python. Example 1: Create a Global
Variable x = "global"
deffoo():
print("x inside:",
x)
foo()
print("x outside:",
x)
args
-
instancememo :
so you don’t
co
> result
instancekeymemo(key
)
instancememo
Cha
pter-
2
Tupl
es
1. Tuples are lists that are immutable.
I like Al Sweigart's characterization of a tuple as being the "cousin" of the list. The tuple is so
similar to the list that I am tempted to just skip covering it, especially since it's an object that other
popular languages – such as Ruby, Java, and JavaScript – get by just fine without having. However,
the tuple is an object that is frequently used in Python programming, so it's important to at least be
able to recognize its usage, even if you don't use it much yourself.
Syntax for declaring a tuple
Like a list, a tuple is a collection of other objects. The main visual difference, in terms of syntax, is
that instead of enclosing the values in we use parentheses, not square brackets, to enclose the
values of a tuple:
List Tuple
[1, 2,
"hello"]
(1, 2,
"hello")
Otherwise, the process of iterating through a tuple, and using square bracket notation to access or
slice a tuple's contents is the same as it is for lists (and pretty much for every other
Python sequence object, such as range…but we'll gloss over that detail for now).
Word of warning: if you're relatively new to programming and reading code, the use of
parentheses as delimiters might seem like a potential syntactic clusterf—, as parentheses are
already used in various other contexts, such as function calls. What differentiates a tuple declaration,
e.g.
mytuple=("hello","world")
– from the parentheses-enclosed values of a function call, e.g.
print("hello","world")
Well, that's easy – the latter set of parentheses-enclosed objects immediately follows a function name,
i.e.
The potential confusion from the similar notation isn't too terrible, in
practice. One strange thing you might come across is this:
>>>mytup
le=("hello
",)
>>>type(
mytuple)
tuple
print .
>>>len(mytuple)
1
Having a trailing comma is the only way to denote a tuple of length 1. Without that trailing comma,
would be pointing to a plain string object that happens to be enclosed in parentheses:
>>>mytuple=("hello")
>>>type(mytuple)
str
2. Tuples are immutable
Besides the different kind of brackets used to delimit them, the main difference between a tuple and a
list is that the tuple object is immutable. Once we've declared the contents of a tuple, we can't modify
the contents of that tuple.
For example, here's how we modify the 0th member of a list:
>>>m
ylist=
[1,2,3
]
>>>m
ylist[0
]=999
print(
mylist
)
[999,2,3]
That will not work with a tuple:
>>>mytuple=(1,2,3)
>>>mytuple[0]=999
TypeError:'tuple'objectdoesnotsupportitemassignment
And while the list object has several methods for adding new members, the tuple has no such
methods.
In other words, "immutability" == "never-changing".
Similarly, when a program alters the contents of a mutable object, it's often described as "mutating"
that object.
3. Tuple Assignment
Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of
an assignment to be assigned values from a tuple on the right of the assignment.
(name, surname, birth_year, movie, movie_year, profession, birth_place) =julia
This does the equivalent of seven assignment statements, all on one easy line. One requirement is
that the number of variables on the left must match the number of elements in the tuple.
Once in a while, it is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:
t
e
m
p
=
a
a
=
b
mytupl
e
b
=
t
e
m
p
Tuple assignment solves this problem neatly:
(a, b) = (b, a)
The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its
respective variable. All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile.
Naturally, the number of variables on the left and the number of values on the right have to be the
same. >>>(a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack.
4. Tuples as Return Values
Functions can return tuples as return values. This is very useful — we often want to know some
batsman’s highest and lowest score, or we want to find the mean and the standard deviation, or we
want to know the year, the month, and the day, or if we’re doing some ecological modeling we may
want to know the number of rabbits and the number of wolves on an island at a given time. In each
case, a function (which can only return a single value), can create a single tuple holding multiple
elements.
For example, we could write a function that returns both the area and the circumference of a circle
of radius r.
def circleInfo(r):
""" Return (circumference, area) of a circle
of radius r """ c = 2 * 3.14159 * r a =
3.14159 * r * r return (c, a)
print(circleInfo(10))
5. List and Tuple
The main difference between lists and tuples is the fact that lists are mutable whereas tuples are
immutable.
What does that even mean, you say?
A mutable data type means that a python object of this type can be modified.
An immutable object can’t.
Let’s create a list and assign it to a
variable. >>> a
=["apples","bananas","oranges"]
Now let’s see what happens when we try to modify the first item of the list.
Let’s change to “berries”.
>>>a[0]="berries"
>>> a
['berries','bananas','oranges']
Perfect! the first item of a has changed.
Now, what if we want to try the same thing with a tuple instead of a list?
Let’s see. >>> a =("apples","bananas","oranges")
>>>a[0]="berries"
Traceback(most recent call last):
File"", line 1,in
“apples
”
TypeError:'tuple'object does not support item assignment
We get an error saying that a tuple object doesn’t support item assignment.
The reason we get this error is because tuple objects, unlike lists, are immutable which means you
can’t modify a tuple object after it’s created.
But you might be thinking, Karim, my man, I know you say you can’t do assignments the way you
wrote it but how about this, doesn’t the following code modify a?
>>> a =("apples","bananas","oranges")
>>> a =("berries","bananas","oranges")
>>> a
('berries','bananas','oranges') Fair question! Let’s see, are we
actually modifying the first item in tuple a with the code above?
The answer is No, absolutely not.
6. Variable-length argument tuples:
To understand why, you first have to understand the difference between a variable and a python
object.
Syntax
Syntax for a function with non-keyword variable
arguments is this − def functionname([formal_args,]
*var_args_tuple ):
"functi
on_doc
string"
functio
n_suite
return
[expres
sion]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable
arguments. This tuple remains empty if no additional arguments are specified during the function
call.
Example
#!/usr/bin/python
# Function definition is here
defprintinfo( arg1,*vartuple
):
"This prints a variable
passed arguments"
print"Output is: " print arg1
forvarinvartuple: printvar
return;
# Now you can call printinfo function
printinfo(10)
printinfo(70,60,50) Output When the above code is
executed, it produces the following result − Output is:
10
Output is:
70
60
50
7. Dictionaries and Tuples
Besides lists, Python has two additional data structures that can store multiple objects. These data
structures are dictionaries and tuples. Tuples will be discussed first.
Tuples
Tuples are immutable lists. Elements of a list can be modified, but elements in a tuple can only be
accessed, not modified. The name tuple does not mean that only two values can be stored in this
data structure.
Tuples are defined in Python by enclosing elements in parenthesis ( ) and separating elements with
commas. The command below creates a tuple containing the numbers 3, 4, and 5. >>>t_var =
(3,4,5)
>>>t_var
(3, 4, 5)
Note how the elements of a list can be modified:
>>>l_var = [3,4,5] # a list
>>>l_var[0]= 8
>>>l_var
[8, 4, 5]
The elements of a tuple can not be modified. If you try to assign a new value to one of the elements
in a tuple, an error is returned.
>>>t_var = (3,4,5) # a tuple
>>>t_var[0]= 8
>>>t_var
TypeError: 'tuple' object does not support item assignment
To create a tuple that just contains one numerical value, the number must be followed by a comma.
Without a comma, the variable is defined as a number.
>>>n
um =
(5)
>>>
type(
num)
int
When a comma is included after the number, the variable is
defined as a tuple. >>>t_var = (5,) >>> type(t_var)
tuple
Dictionaries
Dictionaries are made up of key: value pairs. In Python, lists and tuples are organized and accessed
based on position. Dictionaries in Python are organized and accessed using keys and values. The
location of a pair of keys and values stored in a Python dictionary is irrelevant.
Dictionaries are defined in Python with curly braces { }. Commas separate the key-value pairs that
make up the dictionary. Each key-value pair is related by a colon :.
Let's store the ages of two people in a dictionary. The two
people are Gabby and Maelle. Gabby is 8 and Maelle is 5. Note the name Gabby is a string and the age
8 is an integer. >>>age_dict = {"Gabby": 8 , "Maelle": 5}
>>>
type(age_
dict) dict
The values stored in a dictionary are called and assigned using the following syntax:
dict_name[key] = value
>>>age_dict = {"Gabby": 8 , "Maelle": 5}
>>>age_dict["Gabby"]
8
We can add a new person to our age_dict with the following command:
>>>age_dict = {"Gabby": 8 , "Maelle": 5}
>>>age_dict["Peter"]= 40
>>>age_dict
{'Gabby': 8, 'Maelle': 5, 'Peter': 40}
Dictionaries can be converted to lists by calling the .items(), .keys(), and .values() methods.
>>>age_dict = {"Gabby": 8 , "Maelle": 5}
>>>whole_list = list(age_dict.items())
>>>whole_list
[('Gabby', 8), ('Maelle', 5)]
>>>name_list = list(age_dict.keys())
>>>name_list
['Gabby', 'Maelle']
>>>age_list = list(age_dict.values())
>>>age_list
[8, 5]
Items can be removed from dictionaries by calling the .pop() method. The dictionary key (and that
key's associated value) supplied to the .pop() method is removed from the dictionary.
>>>age_dict = {"Gabby": 8 , "Maelle": 5}
>>>age_dict.pop("Gabby")
>>>age_dict
{'Maelle': 5}
8. Sequences of Sequences:
Some basic sequence type classes in python are, list, tuple, range. There are some additional
sequence type objects, these are binary data and text string.
Some common operations for the sequence type object can work on both mutable and immutable
sequences.
Some of the operations are as follows −
Sr.No. Operation/Functions & Description
1 x in seq
True, when x is found in the sequence seq, otherwise False
2 x not in seq
False, when x is found in the sequence seq, otherwise True
3 x + y
Concatenate two sequences x and y
4 x * n or n * x
Add sequence x with itself n times
5 seq[i] ith item of the
sequence.
6 seq[i:j]
Slice sequence from index i to j
7 seq[i:j:k]
Slice sequence from index i to j with step k
8 len(seq)
Length or number of elements in the sequence
9 min(seq)
Minimum element in the sequence
10 max(seq)
Maximum element in the sequence
11 seq.index(x[, i[, j]])
Index of the first occurrence of x (in the index range i and j)
12 seq.count(x)
Count total number of elements in the sequence
13 seq.append(x)
Add x at the end of the sequence
14 seq.clear()
Clear the contents of the sequence
15 seq.insert(i, x)
Insert x at the position i
16 seq.pop([i])
Return the item at position i, and also remove it from sequence.
Default is last element.
17 seq.remove(x)
Remove first occurrence of item x
18 seq.reverse() Reverse
the list
Example Code
myList1
=[10,20,30,40,50]
myList2
=[56,42,79,42,85,9
6,23]
if30in myList1:
print('30 is present')
if120notin myList1:
print('120 is not present')
print(myList1 + myList2)#Concatinate lists
print(myList1 *3)#Add myList1 three times
with itself print(max(myList2))
print(myList2.count(42))#42 has two times in the list
print(myList2[2:7])
print(myList2[2:7:2])
myList1.append(60)
print(myList1)
myList2.insert(5,17)
print(myList2)
myLis
t2.pop
(3)
print(
myLis
t2)
myLis
t1.rev
erse()
print(myList1)
myLis
t1.cle
ar()
print(
myLis
t1)
Outpu
t
30 is present
120 is not present
[10, 20, 30, 40, 50, 56, 42, 79, 42, 85, 96, 23]
[10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50]
96
2
[79, 42, 85, 96, 23]
[79, 85, 23]
[10, 20, 30, 40, 50, 60]
[56, 42, 79, 42, 85, 17, 96, 23]
[56, 42, 79, 85, 17, 96, 23]
[60, 50, 40, 30, 20, 10]
[]
Chapter-3
Files
1. Persistence
During the course of using any software application, user provides some data to be processed. The
data may be input, using a standard input device (keyboard) or other devices such as disk file,
scanner, camera, network cable, WiFi connection, etc. Data so received, is stored in computer’s
main memory (RAM) in the form of various data structures such as, variables and objects until the
application is running. Thereafter, memory contents from RAM are erased.
However, more often than not, it is desired that the values of variables and/or objects be stored in
such a manner, that it can be retrieved whenever required, instead of again inputting the same data.
The word ‘persistence’ means "the continuance of an effect after its cause is removed". The term
data persistence means it continues to exist even after the application has ended. Thus, data stored in
a non-volatile storage medium such as, a disk file is a persistent data storage.
In this tutorial, we will explore various built-in and third party Python modules to store and retrieve
data to/from various formats such as text file, CSV, JSON and XML files as well as relational and
non-relational databases.
Using Python’s built-in File object, it is possible to write string data to a disk file and read from it.
Python’s standard library, provides modules to store and retrieve serialized data in various data
structures such as JSON and XML.
Python’s DB-API provides a standard way of interacting with relational databases. Other third
party Python packages, present interfacing functionality with NOSQL databases such as
MongoDB and Cassandra. This tutorial also introduces, ZODB database which is a persistence
API for Python objects. Microsoft Excel format is a very popular data file format. In this tutorial,
we will learn how to handle .xlsx file through Python.
2. Reading and Writing to text files in Python
Python provides inbuilt functions for creating, writing and reading files. There are two types of files
that can be handled in python, normal text files and binary files (written in binary language,0s and
1s).
Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
In this article, we will be focusing on opening, closing, reading and writing data in a text file.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file will
be used once its opened. These modes also define the location of the File Handle in the file. File
handle is like a cursor, which defines from where the data has to be read or written in the file. There
are 6 access modes in python.
Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If
the file does not exists, raises I/O error. This is also the default mode in which file is opened.
Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the
beginning of the file. Raises I/O error if the file does not exists.
Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written.
The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated
and over- written. The handle is positioned at the beginning of the file.
Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the existing
data.
Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not
exist. The handle is positioned at the end of the file. The data being written will be inserted at the
end, after the existing data.
Opening a File
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as
special character. For example, if there is temp in the file address, then t is treated as the tab
character and error is raised of invalid address. The r makes the string raw, that is, it tells that the
string is without any special characters. The r can be ignored if the file is in same directory and
address is not being placed.
# Open function to open the file
"MyFile1.txt" # (same directory)
in append mode and file1
=open("MyFile.txt","a")
# store its reference in the
variable file1 # and
"MyFile2.txt" in D:Text in
file2 file2 =open(r"D:Text
MyFile2.txt","w+")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2 Closing a file close()
function closes the file and frees the memory space acquired by that file. It is used at the time
when the file is no longer needed or if it is to be opened in a different file mode.
File_object.close()
# Opening and Closing a file
"MyFile.txt" # for object
name file1.
file1 =open("MyFile.txt","a")
file1.close()
Writing to a file
There are two ways to write in a file.
write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
writelines() : For a list of string elements, each string is inserted in the text file.Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Reading from a file
There are three ways to read data from a text file.
read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads
the entire file. File_object.read([n]) readline() : Reads a line of the file and returns in form
of a string.For specified n, reads at most n bytes. However, does not reads more than one
line, even if n exceeds the length of the line. File_object.readline([n]) readlines() : Reads
all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘n’ is treated as a special character
of two bytes filter_none edit play_arrow
brightness_4
# Program to show various ways
to read and # write data in a file.
file1 =open("myfile.txt","w")
L =["This is Delhi n","This is Paris n","This is London n"]
# n is placed to indicate EOL
(End of Line)
file1.write("Hello n")
file1.writelines(L)
file1.close() #to change file
access modes file1
=open("myfile.txt","r+")
print"Output of Read function is "
printfile
1.read()
print
# seek(n) takes the file
handle to the nth # bite
from the beginning.
file1.seek(0)
print"Output of Readline function is "
printfi
le1.re
adline
()
print
file1.s
eek(0)
# To show difference between read
and readline print"Output of
Read(9) function is "
printfile1.read(9) print
file1.seek(0)
print"Output of Readline(9) function is "
printfile1.readline(9)
file1.seek(0) # readlines
function print"Output of
Readlines function is "
printfil
e1.read
lines()
print
file1.cl
ose()
Output
:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9)
function is Hello
Output of Readlines function is
['Hello n', 'This is Delhi n', 'This is Paris n', 'This is London n']
Appending to a file
filter_none
ed
it
pl
ay
_a
rr
o
w
br
ig
ht
ne
ss
_4
# Python
program to
illustrate #
Append vs write
mode file1
=open("myfile.t
xt","w")
L =["This is Delhi n","This is Paris n","This is London 
n"] file1.close()