0% found this document useful (0 votes)
31 views64 pages

Module 4 - Python

Python is a versatile, easy to learn programming language. It has many features including being simple, portable, object-oriented, and having a large standard library. Python was created in the late 1980s and has evolved significantly since then. It is widely used for web development, data science, scientific computing, and desktop applications. The document discusses Python's history, features, applications, and basic data types including numbers, strings, lists, tuples, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
31 views64 pages

Module 4 - Python

Python is a versatile, easy to learn programming language. It has many features including being simple, portable, object-oriented, and having a large standard library. Python was created in the late 1980s and has evolved significantly since then. It is widely used for web development, data science, scientific computing, and desktop applications. The document discusses Python's history, features, applications, and basic data types including numbers, strings, lists, tuples, and dictionaries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

MODULE – 4

1. Features and History of Python:


1.1Features of Python
Simple: Reading a program written in Python feels almost like reading
english. The main strength of Python which allows programmer to concentrate
on the solution to the problem rather than language itself.
Easy to Learn: Python program is clearly defined and easily readable. The
structure of the program is simple. It uses few keywords and clearly defined
syntax.
Versatile: Python supports development of wide range of applications such
as simple text processing, WWW browsers and games etc..
Free and Open Source: It is a Open Source Software. So, anyone can freely
distribute it, read the source code, edit it, and even use the code to write new
(free) programs.
High-level Language: While writing programs in Python we do not worry
about the low-level details like managing memory used by the program.
Interactive: Programs in Python work in interactive mode which allows
interactive testing and debugging of pieces of code. Programmer can easily
interact with the interpreter directly at the python prompt to write their
programs.
Portable: It is a portable language and hence the programs behave the
same on wide variety of hardware platforms with different operating systems.
Object Oriented: Python supports object-oriented as well as procedure-
oriented style of programming .While object-oriented technique encapsulates
data and functionality with in objects, Procedure oriented at other hand, builds
programs around procedure or functions.
Interpreted: Python is processed at runtime by interpreter. So, there is no
need to compile a program before executing it. You can simply run the
program. Basically python converts source program into intermediate form
called byte code.
Dynamic and strongly typed language: Python is strongly typed as the
interpreter keeps track of all variables types. It's also very dynamic as it rarely
uses what it knows to limit variable usage.
Extensible: Since Python is an open source software, anyone can add low-
level modules to the python interpreter. These modules enable programmers to
add to or customize their tools to work more efficiently.
Embeddable: Programmers can embed Python within their C, C++, COM,
ActiveX, CORBA and Java Programs to give scripting capability for users.

Prepared by: Mr. R A Khan Page 1


Extensive Libraries: Python has huge set of libraries that is easily portable
across different platforms with different operating systems.
Easy maintenance: Code Written in Python is easy to maintain.
Secure: This Programming language is secure for tampering. Modules can
be distributed to prevent altering of source code. Additionally, Security checks
can be easily added to implement additional security features.
Robust: Python Programmers cannot manipulate memory directly, errors
are raised as exceptions that can be catch and handled by the program code.
For every syntactical mistake, a simple and easy to interpret message is
displayed. All these make python robust.
Multi-threaded: Python supports executing more than one process of a
program simultaneously with the help of Multi Threading.
Garbage Collection: The Python run-time environment handles garbage
collection of all python objects. For this, a reference counter is maintained to
assure that no object that is currently in use is deleted.
1.2 History of Python.
Python was first developed by Guido van Rossum in the late 80‟s and
early 90‟s at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
It has been derived from many languages such as ABC, Modula-3, C, C++,
Algol-68, SmallTalk, UNIX shell and other scripting languages.
Since early 90‟s Python has been improved tremendously. Its version 1.0
was released in 1991, which introduced several new functional programming
tools.
While version 2.0included list comprehension was released in 2000 by the
Be Open Python Labs team.
Python 2.7 which is still used today will be supported till 2020.
Currently Python 3.6.4 is already available. The newer versions have better
features like flexible string representation e.t.c,
Although Python is copyrighted, its source code is available under GNU
General Public License (GPL) like that Perl.
Python is currently maintained by a core development team at the institute
which is directed by Guido Van Rossum.
These days, from data to web development, Python has emerged as very
powerful and popular language. It would be surprising to know that python is
actually older than Java, R and JavaScript.
1.3 Applications of Python:

Prepared by: Mr. R A Khan Page 2


Embedded scripting language: Python is used as an embedded scripting
language for various testing/ building/ deployment/ monitoring frameworks,
scientific apps, and quick scripts.
3D Software: 3D software like Maya uses Python for automating small user
tasks, or for doing more complex integration such as talking to databases and
asset management systems.
Web development: Python is an easily extensible language that provides
good integration with database and other web standards.
GUI-based desktop applications: Simple syntax, modular architecture,
rich text processing tools and the ability to work on multiple operating systems
makes Python a preferred choice for developing desktop-based applications.
Image processing and graphic design applications: Python is used to
make 2D imaging software such as Inkscape, GIMP, Paint Shop Pro and
Scribus. It is also used to make 3D animation packages, like Blender, 3ds Max,
Cinema 4D, Houdini, Light wave and Maya.
Scientific and Computational applications: Features like high speed,
productivity and availability of tools, such as Scientific Python and Numeric
Python, have made Python a preferred language to perform computation and

All the keywords except True, False and None are in lowercase and they
must be written as it is. The list of all the keywords are given below.
Keywords in Python programming language
FALSE await else import pass
None break except in raise
TRUE class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
2. Literal Constants
In programming constants are referred to variables that cannot be changed.
Generally Literal constants are classified into three types.
Literal Constants
 Numeric Literals
 Boolean Literals
 String Literals
2.1 Numeric Literals
The value of a literal constant can be used directly in programs. For
example, 7, 3.9, 'A', and "Hello" are literal constants.

Prepared by: Mr. R A Khan Page 3


Numbers refers to a numeric value. You can use four types of numbers in
Python program- integers, long integers, floating point and complex
numbers.
Numbers like 5 or other whole numbers are referred to as integers. Bigger
whole numbers are called long integers. For example, 535633629843L is a
long integer.
Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers.
Numbers of a + bj form (like -3 + 7j) are complex numbers.

2.2 Boolean Literals


A Literals Boolean type can have one of the two values- True or False.

2.3 String Literals


A string is a group of characters.
Using Single Quotes ('): For example, a string can be written as 'HELLO'.
Using Double Quotes ("): Strings in double quotes are exactly same as
those in single quotes. Therefore, 'HELLO' is same as "HELLO".
Using Triple Quotes (''' '''): You can specify multi-line strings using triple
quotes. You can use as many single quotes and double quotes as you want in a
string within triple quotes.
Examples:

Prepared by: Mr. R A Khan Page 4


2.3.1Unicode Strings
Unicode is a standard way of writing international text. That is, if you want
to write some text in your native language like Hindi, then you need to have a
Unicode-enable text editor.
Python allows you to specify Unicode text by prefixing the string with a u or
U.
For Example: u‖Sample Unicode string‖
Note: The „U‟ prefix specifies that the file contains text written in language
other than English
2.3.2Escape Sequences
Some characters (like ", \) cannot be directly included in a string. Such
characters must be escaped by placing a backslash before them.

2.3.2Raw Strings
 If you want to specify a string that should not handle any escape sequences
and want to display exactly as specified then you need to specify that string as
a raw string. A raw string is specified by prefixing r or R to the string.

3. Data types
The variables can hold values of different type called Data Type.
Data type is a set of values and the allowable operations on those values.
Python has a great set of useful data types. Python's data types are built in
the core of the language. They are easy to use and straightforward.

Prepared by: Mr. R A Khan Page 5


Example a person age is stored in a number, his name is made only with
characters, and his address is made with mixture of numbers and characters.
Python has various standard data types to define the operations possible on
them and storage method for each of them.
Python supports the following five standard data types
1. Numbers
2. Strings
3. Lists
4. Tuple
5. Dictionary
Note: Python is pure object oriented programming language.it refers to
everything as an object including numbers and strings.
The Following Diagram shows the classification of Python Data Types.

Data
Types

Immutable (Which Can’t Mutable (Which Can be


be Changed) Changed)

Dictionar
Numbers String Boolean Tuples Lists Sets
ies

3.1.1. Assigning or Initializing Values to Variables


In Python, programmers need not explicitly declare variables to reserve
memory space. The declaration is done automatically when a value is assigned
to the variable using the equal sign (=). The operand on the left side of equal
sign is the name of the variable and the operand on its right side is the value to
be stored in that variable. Example: Program to display data of different types
using variables and literal constants.

Prepared by: Mr. R A Khan Page 6



In Python, you can reassign variables as many times as you want to change
the value stored in them. You may even store value of one data type in a
statement and other data type in subsequent statement. This is possible
because Python variables do not have specific types, i.e., we can assign integer
to the variable, later we assign string to the same variable.
Example: Program to reassign value to a variable
val = ―Hello”
print(val)
val = 100
print(val)
val=10.32
print(val)
Output
Hello
100
10.32
3.1.2Multiple Assignments
Python allows programmers to assign single value to more than one
variable simultaneously.
For example
>>>sum = flag = a = b = 0
In the above statement, all four integer variables are assigned a value 0.You
can also assign different values to multiple variables simultaneously as shown
below
For example

Prepared by: Mr. R A Khan Page 7


>>>sum, a, b, mesg = 0, 3, 5, ―Result‖
Here, variable sum, a and b are integers(numbers) and mesg is assigned
―Result‖.
Note: Removing a variable means that the reference from the name to the value
has been deleted.However, deleted variables can be used again in the code if
and only if you reassign them some value.
3.2 Boolean Type
A variable of Boolean type can have one of the two values- True or False.
Similar to other variables, the Boolean variables are also created while we
assign a value to them or when we use a relational operator on them.

3.3 Tuples
A tuple is similar to the list as it also consists of a number of values
separated by commas and enclosed within parentheses.
The main difference between lists and tuples is that you can change the
values in a list but not in a tuple. This means that while tuple is a read only
data type, the list is not.

Prepared by: Mr. R A Khan Page 8


3.4 Lists
Lists are the most versatile data type of Python language.
A list consist of items separated by commas and enclosed within square
brackets. The values stored in a list are accessed using indexes.
The index of the first element being 0 and n-1 as that of the last element,
where n is the total number of elements in the list. Like strings, you can also
use the slice, concatenation and repetition operations on lists.
Example program to demonstrate operations on lists
list = ['a', 'bc', 78, 1.23]
list1 = ['d', 78]
print(list)
print(list[0])
print(list[1:3])
print(list[2:])
print(list * 2)
print(list + list1)
Output:
['a', 'bc', 78, 1.23]
a
['bc', 78]
[78, 1.23]
['a', 'bc', 78, 1.23, 'a', 'bc', 78, 1.23]
['a', 'bc', 78, 1.23, 'd', 78]
3.5 Dictionary
Python’s dictionaries stores data in key-value pairs.
The key values are usually strings and value can be of any data type. The
key value pairs are enclosed with curly braces ({ }).
Each key value pair separated from the other using a colon (:). To access
any value in the dictionary, you just need to specify its key in square braces
([]).Basically dictionaries are used for fast retrieval of data.
Example

4. Variables and Identifiers


4.1 Variables

Prepared by: Mr. R A Khan Page 9


Variable means its value can vary. You can store any piece of information
in a variable.
Variables are nothing but just parts of your computer’s memory where
information is stored. To identify a variable easily, each variable is given an
appropriate name.
4.2 Identifiers
Identifiers are names given to identify something. This something can be a
variable, function, class, module or other object. For naming any identifier,
there are some basic rules like:
The first character of an identifier must be an underscore ('_') or a letter
(upper or lowercase).
The rest of the identifier name can be underscores ('_'), letters (upper or
lowercase), or digits (0-9).
Identifier names are case-sensitive. For example, myvar and myVar are
not the same.
Punctuation characters such as @, $, and % are not allowed within
identifiers.
Examples of valid identifier names are sum, __my_var, num1, r, var_20,
First, etc.
Examples of invalid identifier names are 1num, my-var, %check, Basic Sal,
H#R&A, etc.,
5. Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
>>> 2+3
5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5
is the output of the operation.
Python supports the following operators
1. Arithmetic operators
2. Comparison (Relational) operators
3. Unary Operators
4. Bitwise operators
5. Shift Operators
6. Logical Operators
7. Membership and Identity Operators
8. Assignment operators
9. Special operators

Prepared by: Mr. R A Khan Page 10


5.1 Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
This operator will work on two operands.
Example: If a=100 and b=200 then look at the table below, to see the
result of arithmetic operations.

5.2 Comparision (Relational) Operators


A Relational or Comparison operator checks the relationship between two
operands. If the relation is true, it returns 1; if the relation is false, it returns value
0
For Example assuming a=100 and b=2000, we can use the comparison
operators on them as specified in the following table.

Prepared by: Mr. R A Khan Page 11


5.3 Unary Operator
Unary operators act on single operands. Python supports unary minus
operator.
Unary minus operator is strikingly different from the arithmetic operator that
operates on two operands and subtracts the second operand from the first
operand.
When an operand is preceded by a minus sign, the unary operator negates its
value.
For example, if a number is positive, it becomes negative when preceded with a
unary minus operator. Similarly, if the number is negative, it becomes positive
after applying the unary minus operator. Consider the given example.
b = 10 a = - (b)
The result of this expression, is a = -10, because variable b has a positive
value. After applying unary minus operator (-) on the operand b, the value
becomes -10, which indicates it as a negative value.
5.4 Bitwise Operators
As the name suggests, bitwise operators perform operations at the bit level.
These operators include bitwise AND, bitwise OR, bitwise XOR, and shift
operators.
Bitwise operators expect their operands to be of integers and treat them as a
sequence of bits.
The truth tables of these bitwise operators are given below.

Prepared by: Mr. R A Khan Page 12



Example: If a=60 and b=13 then look at the table below, to see the result of
Bitwise operations.
Operator Description Example
& Operator copies a bit to the result if it
(a & b) =12 (means 0000 1100)
Binary AND exists in both operands
| It copies a bit if it exists in either
(a | b) = 61 (means 0011 1101)
Binary OR operand.
^ It copies the bit if it is set in one
(a ^ b) = 49 (means 0011 0001)
Binary XOR operand but not both.
~ (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of
Binary Ones complement form due to a signed
'flipping' bits.
Complement binary number
<<
Binary The left operands value is moved left
a << 2 = 240 (means 1111 0000)
Left Shift by the number of bits specified by the
right operand.

The left operands value is moved


>>
right by the number of bits specified a >> 2 = 15 (means 0000 1111)
Binary Right
by the right operand.
Shift

5.5 Shift Operators


 Python supports two bitwise shift operators. They are shift left (<<) and
shift right (>>).
 These operations are used to shift bits to the left or to the right. The
syntax for a shift operation can be given as follows:
 Examples:

Prepared by: Mr. R A Khan Page 13


5.6 Logical Operators
 Logical operators are used to simultaneously evaluate two conditions or
expressions with relational operators.
 Logical AND (and) If expressions on both the sides (left and right side) of
the logical operator are true, then the whole expression is true.
For example, If we have an expression (a>b) and (b>c), then the whole
expression is true only if both expressions are true. That is, if b is greater than
a and c.
 Logical OR (or) operator is used to simultaneously evaluate two
conditions or expressions with relational operators. If one or both the
expressions of the logical operator is true, then the whole expression is
true.
For example, If we have an expression (a>b) or (b>c), then the whole expression
is true if either b is greater than a or b is greater than c.
 Logical NOT (not) operator takes a single expression and negates the
value of the expression. Logical NOT produces a zero if the expression
evaluates to a non-zero value and produces a 1 if the expression
produces a zero. In other words, it just reverses the value of the
expression.
For example, a = 10; b = not a; Now, the value of b = 0.
5.7 Membership and Identity Operators
5.7.1. Membership Operator
Python supports two types of membership operators–in and not in. These
operators, test for membership in a sequence such as strings, lists, or tuples.
 in Operator: The operator returns true if a variable is found in the
specified sequence and false otherwise. For example, a in nums returns
1, if a is a member of nums.
 not in Operator: The operator returns true if a variable is not found in
the specified sequence and false otherwise. For example, a not in nums
returns 1, if a is not a member of nums.
5.7.2. Identity Operators
 is Operator: Returns true if operands or values on both sides of the
operator point to the same object and false otherwise. For example, if a is
b returns 1, if id(a) is same as id(b).
 is not Operator: Returns true if operands or values on both sides of the
operator does not point to the same object and false otherwise. For
example, if a is not b returns 1, if id(a) is not same as id(b).

5.8 Assignment Operators


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

Prepared by: Mr. R A Khan Page 14


Assignment operators in Python
Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
5.9 Operator Precedence
The operator precedence in Python are listed in the following table. It is in
descending order, upper group has higher precedence than the lower ones.
Operator precedence rule in Python
Operators Meaning
() Parentheses
** Exponent
+x, -x, ~x Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparison, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR
6. Input Operation
To take input from the users, Python makes use of the input ( ) function.
The input ( ) function prompts the user to provide some information on which
the program can work and give the result.
However, we must always remember that the input function takes user‟s
input as a string.
Example:

Prepared by: Mr. R A Khan Page 15


7. Comments
Comments are the non-executable statements in a program. They are just
added to describe the statements in the program code.
Comments make the program easily readable and understandable by the
programmer as well as other users who are seeing the code. The interpreter
simply ignores the comments.
In Python, a hash sign (#) that is not inside a string literal begins a
comment. All characters following the # and up to the end of the line are part of
the comment

Note: For writing Multi line comments. Make sure to indent the leading „ „ „
appropriately to avoid an Indentation Error
„„„
This is a multiline
comment.
„„„
8. Indentation
Whitespace at the beginning of the line is called indentation. These
whitespaces or the indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at
the beginning of the logical line determines the indentation level of that logical
line.

Prepared by: Mr. R A Khan Page 16


9. Expressions
An expression is any legal combination of symbols (like variables, constants
and operators) that represents a value.
In Python, an expression must have at least one operand (variable or
constant) and can have one or more operators. On evaluating an expression,
we get a value. Operand is the value on which operator is applied.
Generally Expressions are divided into the following types
1. Constant Expressions: One that involves only constants.
Example: 8 + 9 – 2
2. Integral Expressions: One that produces an integer result after evaluating the
expression.
Example: a = 10
3. Floating Point Expressions: One that produces floating point results.
Example: a * b / 2.0
4. Relational Expressions: One that returns either true or false value.
Example: c = a>b
5. Logical Expressions: One that combines two or more relational expressions
and returns a value as True or False.
Example: a>b and y! = 0
6. Bitwise Expressions: One that manipulates data at bit level.
Example: x = y&z
7. Assignment Expressions: One that assigns a value to a variable.
Example: c = a + b or c = 10
Example Program:
Give the output for the following statements.( April 2018 Regular)
a = 20
b = 10
c = 15
d=5
print ("a:%d b:%d c:%d d:%d" % (a,b,c,d ))
e = (a + b) * c / d
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d
print ("Value of ((a + b) * c) / d is ", e)
e = (a + b) * (c / d)

Prepared by: Mr. R A Khan Page 17


print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d
print ("Value of a + (b * c) / d is ", e)
Output:
a:20 b:10 c:15 d:5
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
10. Operations on Strings
Like numbers we can also manipulate strings by performing operations on
them.
Basically there are three operations on strings

1.String concatenation.
2.String repetition or multiplication.
3.String slicing.
10.1String Concatenation
Like numbers we can add two strings in Python. The process of combining
two strings is called concatenation.
Two strings whether created using single or double quote are concatenated
in the same way. Look at the codes given in the following example.
Example: Codes to demonstrate how easily two strings are concatenated.
>>>print(“hello” + “-world”)
output
hello-world
>>>print(―hello‖+‘-world’)
output
hello-world
>>print(‗hello’+‘-world’)
output
hello-world.
Note:we cannot add string to number which generates an error.
10.2 String Repetition or Multiplication
You cannot add string and number but we can multiply string and number
with the help of this string repetition.
When a string is multiplied with an integer n, then the string is repeted n
times.
Thus, the * operator is also called as string repetition operator.
The order of string and integer is not important.

Example

Prepared by: Mr. R A Khan Page 18


>>print(― hello‖ * 5)
Output
hello hello hello hello hello
>>print(5 * ― hello‖)
Output
hello hello hello hello hello
Note: We cannot multiply two strings and cannot multiply string with floating
point number.
10.3 Slice Operations on Strings

You can extract subsets of strings by using the slice operator ([ ] and [:]).
You need to specify index or the range of index of characters to be extracted.
The index of the first character is 0 and the index of the last character is n-
1, where n is the number of characters in the string.
If you want to extract characters starting from the end of the string, then
you must specify the index as a negative number. For example, the index of the
last character is -1.
Program to perform slice operation on strings
#string operations
str = ―Python is easy !!!‟
print(str)
print(str[0])
print(str[3:9])
print(str[4:])
print(str[-1])
print(str[:5])
print(str * 2)
print(str + ―Isn’t gec‟)
Output
Python is easy !!!
P
hon is
on is easy
!
Pytho
Python is easy !!! Python is easy !!!
Python is easy !!! Isn‟t gec
11. Type Conversion
In Python, it is just not possible to complete certain operations that involve
different types of data.
For example, it is not possible to perform "2" + 4 since one operand is an
integer and the other is of string type.

Prepared by: Mr. R A Khan Page 19


>>>‖20‖ + ―30‖ >>> int(―2‖) + int(―3‖)
Output Output
„2030‟ 5
Another situation in which type conversion is must when we want to accept
a non string value (integer or float) as an input. We know that input function
returns string, so we must typecast the input to numbers to perform
calculations on them.
Example1:
x=input(―Enter the first number‖)
y=input(―Enter the second number‖)
print(x+y)
output
Enter the first number 6
Enter the second number 7
67
Example2:
x=int(input(―Enterthefirstnumber))
y=int(input(―Enterthesecondnumber))
print(x+y)
Output
Enterthefirstnumber6
Enterthesecondnumber7
13
Python provides various built-in functions to convert value from one data
type to another datatype.The following are the functions return new object
representing the coverted value. Some of them are given in the following table.

12 Type Casting vs Type Coercion


we have done explicit conversion of a value from one data type to another.
This is known as type casting.

Prepared by: Mr. R A Khan Page 20


However, in most of the programming languages including Python, there is
an implicit conversion of data types either during compilation or during run-
time. This is also known type coercion.
For example, in an expression that has integer and floating point numbers
(like 21 + 2.1 gives 23.1), the compiler will automatically convert the integer
into floating point number so that fractional part is not lost.
13 Limitations of Python:
Parallel processing can be done in Python but not as elegantly as done in
some other languages (like JavaScript and Go Lang).
Being an interpreted language, Python is slow as compared to C/C++.
Python is not a very good choice for those developing a high-graphic 3d game
that takes up a lot of CPU.
As compared to other languages, Python is evolving continuously and there
is little substantial documentation available for the language.
As of now, there are few users of Python as compared to those using C, C++
or Java.
It lacks true multiprocessor support.
It has very limited commercial support point.
Python is slower than C or C++ when it comes to computation heavy tasks
and desktop applications.
It is difficult to pack up a big Python application into a single executable
file. This makes it difficult to distribute Python to non-technical.
Procedure for Executing your First Python Program 
Step1: Type the program in notepad and save your python program with the
following extension
Filename.py
Step2: To Open Python Shell goto
Start->All Programs->Python 3.4->IDLE(Python GUI)
Step3: To Load your python file in the shell goto
Select->open->Select the path of the python file where it actually Store.
Output:A Separate window will be opened
Step4: For running your Python program click on run tab on the top of the
separate window in the previous step and select run module or simply press
F5.
1.simplemsg.py 
# Write a Python program to display the simple message “Hello World”
print(―Hello World‖)
Output
Hello World
2.sumoftwonumbers.py 
# Write a Python program to add two numbers
num1=int(input("Enter first number"))

Prepared by: Mr. R A Khan Page 21


num2=int(input("Enter second number"))
res=num1+num2
print(str("The sum of two numbers is"))
print(str(num1)+"+"+str(num2)+"="+str(res))
Output:
Enter first number 10
Enter second number 20
The sum of two numbers is
10+20=30
3.distancebetweentwopoints.py
#Write a Python Program to find distance between two points using
Pythagoras Theorem
x1=(int(input("Enter x1")))
x2=(int(input("Enter x2")))
y1=(int(input("Enter y1")))
y2=(int(input("Enter y2")))
distance=((x2-x1)**2+(y2-y1)**2)**0.5
print("Distance Between two points")
print(distance)
Output:
Enter x1 8
Enter x2 9
Enter y1 10
Enter y2 12
Distance Between two points
2.2360679775
Subjective Questions
1. Describe the features of Python
2. Differentiate between literals and variables in python.
3. What are literals? Explain with the help of suitable examples?
4. Explain the significance of Escape sequences with relevant examples
5. Write briefly about Data types in Python
6. Explain in detail about Membership and Identity Operators.
7. How can the ternary operator used in python?

8. Give the operator precedence in python.


9. Define Expression? Explain different types of Expressions supported by
Python?
10. Differentiate string with slicing operator.

Prepared by: Mr. R A Khan Page 22


11. What is tuple? What are the different operations performed on tuple?
Explain with an example?
12. Write briefly about Type Conversion process in Python.Write the meaning
for the following.
str(x), chr(x), float(x), ord(x)
13. Momentum is calculated as, e=mc2, where m is the mass of the object and
c is the velocity. Write a Python program that accepts object‟s mass (in
kilograms) and velocity (in meters per second) and displays its momentum.
14. a)Write a Python Program to convert temperature in Celsius to Fahrenheit
b) Write a Python Program to convert Fahrenheit to Celsius.
15. Write a Python program to calculate the area of triangle using Heron‟s
formula
Hint:√ ( )( )( )
16. Evaluate the following Expression
a) True and False
b) (100<0) and (100>20)
c) not(true) and false
d) not true and false or true
e) not(100<0 or 100>20)
f)100<0 and not 100>20
17. Give an appropriate boolean expression for the each of the following
a) check if variable v is greater than or equal to 0,and less than 10
b )check if variable v is less than 10 and greater than or equal to 0,or it is equal
to 20.
c) check if either the name „cse‟ or „it‟ appears in the list of names assigned to variable
last_names.
d) check if the name „cse‟ appears and the name „it‟does not appear in the list
of last name assigned to variable last_names.
18. Identify the datatype is best suitable to represent the following data values
a) Number of days in the year
b) The circumference of a rectangle
c) Yours father salary
d) Distance between moon and earth
e) Name of your best friend
f) Whether you go for the party

Prepared by: Mr. R A Khan Page 23


Decision Control and Looping Statements
Control Statements:
 A control statement is a statement that determines the control flow of a
set of instructions, i.e., it decides the sequence in which the instructions
in a program are to be executed.

 Types of Control Statements —


Selection/Conditional Control: To execute only a selected set of
statements.

Iterative Control: To execute a set of statements repeatedly.

Un-conditional Control:

1. Selection /Conditional Branching Statements:

 Python language supports different types of conditional branching


statements which are as follows:

 if Statement

 if-else Statement

 Nested if statement

 if-elif-else statement.
1. 1 if Statement:
An if statement is a selection control statement which is based on the value
of a given Boolean Expression.
Syntax:
if test_expression:
statement 1
.....
statement n
statement x
if structure may include 1 or n statements enclosed within if block.

First, test expression is evaluated. If the test expression is true, the


statement of if block (statement 1 to n) are executed, otherwise these
statements will be skipped and the execution will jump to statement x.
Flow chart:

Prepared by: Mr. R A Khan Page 24


Example:

1.2 if else Statement:

The if .... else statement executes a group of statements when a test


expression is true; otherwise, it will execute another group of statements.
Syntax:
if (test expression):
statement_block 1
else:
statement_block 2
statement x
If the condition is true, then it will execute statement block 1 and if the
condition is false then it will execute statement block 2.
Flowchart:

Prepared by: Mr. R A Khan Page 25


Example: Write a program to determine whether a person is eligible to vote:

1.3 Nested if Statements :


A statement that contains other statements is called a compound statement.
To perform more complex checks, if statements can be nested, that is, can be placed one
inside the other.
In such a case, the inner if statement is the statement part of the outer one.
Nested if statements are used to check if more than one conditions are satisfied.
if statements can be nested resulting in multi-way selection.
var = 100
if var < 200:
print( "Expression value is less than 200")
if var == 150:
print ("Which is 150‖)
elif var == 100:
print ("Which is 100")
elif var == 50:
print ("Which is 50")
elif var < 50:

Prepared by: Mr. R A Khan Page 26


print ("Expression value is less than 50")
else:
print ("Could not find true expression")
print ("Good bye!")
Output:-
Expression value is less than 200
Which is 100
Good bye!
1.4 if-elif-else Statement :

Python supports if-elif-else statements to test additional conditions apart from the initial
test expression.
The if-elif-else construct works in the same way as a usual if-else statement.
If-elif-else construct is also known as nested-if construct.
A series of if and elif statements have a final else block, which is executed if none of the if
or elif expressions is True.
Syntax:
if (test expression 1):
statement block1
elif (test expression 2):
statement block2
. . . . . . . . . . . . . . ..
elif( test expression N):
statement block N
else:
statement block X
Flowchart:

Program: To test whether a number entered by the user is negative, positive, or


zero

Prepared by: Mr. R A Khan Page 27


2. Looping Statements/Iterative Structure:

 Iterative statements are decision control statements that are used to


repeat the execution of a list of statements.

 Python supports 2 types of iterative statements-while loop and for loop.


2.1 while Loop :

The While loop provides a mechanism to repeat one or more statements


while a particular condition is TRUE.
Syntax:
Statement x
while (condition):
Statement block
Statement y
In while loop, the condition is tested before any of the statements in the
statement block is executed.

If the condition is TRUE, only then the statements will be executed
otherwise if the condition is False, the control will jump to statement y, that is
the immediate statement outside the while loop block.
Flowchart:

Prepared by: Mr. R A Khan Page 28


Example: Program to print first 10 numbers using a while loop
i=0
while(i<=10):
print(i, end=‖ ―)
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9 10
2.2 for Loop:

 For loop provides a mechanism to repeat a task until a particular


condition is True. It is usually known as a determinate or definite loop
because the programmer knows exactly how many times the loop will
repeat.

 The for...in statement is a looping statement used in Python to iterate


over a sequence of objects.
Syntax:
for loop_control_var in sequence:
statement block
Flowchart:

Prepared by: Mr. R A Khan Page 29


2.2.1 for Loop and range() Function :
o The range( ) function is a built-in function in Python that is used to iterate
over a sequence of numbers.
Syntax:
range(beg, end, [step])
o The range( ) produces a sequence of numbers starting with beg (inclusive)
and ending with one less than the number end.

o The step argument is option (that is why it is placed in brackets). By default,


every number in the range is incremented by 1 but we can specify a different
increment using step. It can be both negative and positive, but not zero.
Example: Program to print first n numbers using the range() in a for loop

Prepared by: Mr. R A Khan Page 30


o If range( ) function is given a single argument, it produces an object with
values from 0 to argument-1. For example: range(10) is equal to writing
range(0, 10).

o If range( ) is called with two arguments, it produces values from the first to
the second. For example, range (0, 10) gives 0-9.
o If range( ) has three arguments then the third argument specifies the interval
of the sequence produced. In this case, the third argument must be an integer.
For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16, 19.
Example:

1. Program that accepts an integer (n) and computes the value of n+nn+nnn.
(Eg. If n=5, find 5+55+555).
n = int(input("Enter a number: "))
str_n = str(n)
sum = n
sum_str = str(n)
for i in range(1, 3):
sum_str = sum_str + str_n
sum = sum + int(sum_str)
print(sum)
2. Program that accepts a word from the user and reverse it
s = input("Enter a word: ")
str = ""
for i in s:
str = i + str
print("Reverse of", s, "is:", str)
2.3 Nested Loops :

Python allows its users to have nested loops, that is, loops that can be
placed inside other loops.

Although this feature will work with any loop like while loop as well as for
loop.

A for loop can be used to control the number of times a particular set of
statements will be executed.
Another outer loop could be used to control the number of times that a
whole loop is repeated.

Loops should be properly indented to identify which statements are


contained within each for statement.
Example:

Prepared by: Mr. R A Khan Page 31


1. Program to print the following pattern

2. Program to display multiplication tables from 1 to 10


for i in range(1, 11):
for j in range(1, 11):
print(i, '*', j, '=', i*j)
2.4 Condition-controlled and Counter-controlled Loops:

2.5 The Break Statement:

The break statement is used to terminate the execution of the nearest


enclosing loop in which it appears.

The break statement is widely used with for loop and while loop.

When compiler encounters a break statement, the control passes to the


statement that follows the loop in which the break statement appears.
Syntax:
Break
Example: Program to demonstrate the break statement

Prepared by: Mr. R A Khan Page 32


Above code is meant to print first 10 numbers using a while loop, but it
will actually print only numbers from 0 to 4. As soon as i becomes equal to 5,
the break statement is executed and the control jumps to the following while
loop.

Hence, the break statement is used to exit a loop from any point with in its
body, by passing its normal termination expression. Below, Figure shows the
transfer of control when the break statement is encountered.

2.6 The Continue Statement:

Like the break statement, the continue statement can only appear in the
body of a loop.

When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing loop.
Syntax:
Continue
Example: Program to demonstrate continue statement

Prepared by: Mr. R A Khan Page 33


Note that the code is meant to print numbers from 0 to 10.But as soon as i
becomes equal to 5, the continue statement is encountered, so rest of the
statements in the loop are skipped. In the output, 5 is missing as continue
caused early increment of i and skipping of statement that printed the value of
i on screen.

Below figure illustrates the use of continue statement in loops.

It can be concluded that the continue statement is somewhat the opposite
of the break statement. It forces the next iteration of the loop to take place,
skipping any code in between itself and the test condition of the loop.

Prepared by: Mr. R A Khan Page 34


The continue statement is usually used to restart a statement sequence
when an error occurs.

2.7 The Pass Statement:

Pass statement is used when a statement is required syntactically but no


command or code has to be executed.

It specified a null operation or simply No Operation (NOP) statement.


Nothing happens when the pass statement is executed.

The difference between a comment and pass statement is that while the
interpreter ignores a comment entirely, pass is not ignored.

Comment is not executed but pass statement is executed but nothing


happens.

Pass is a null statement.


Example:
1. Program to demonstrate pass statement

2.8 Difference between break, continue and pass

The break statement terminates the execution of the nearest enclosing loop
in which it appears.

The continue statement skips the rest of the statements in the loop
transfer the control un-conditionally to the loop-continuation portion of the
nearest enclosing loop.

The pass statement is a do-nothing statement in a loop. It is just added to


make the loop syntactically correct. i.e, a pass statement is written as we can
not have an empty body of the loop.

Prepared by: Mr. R A Khan Page 35


2.9 The Else Statement Used With Loops:

In Python you can have the else statement associated with a loop
statements.

If the else statement is used with a for loop, the else statement is executed
when the loop has completed iterating.

But when used with the while loop, the else statement is executed when
the condition becomes false.
Examples:

3. Programs:
3. 1 Write a python program to Test whether a given number is even or odd.
num = int(input("Enter a number: "))
if (num % 2==0):
print(num, "is an even number.")
else:
print(num, "is an odd number.")
Output:
Enter a number: 5
5 is an odd number.
3. 2 Write a python program to Print out the decimal equivalents of 1/1, 1/2,
1/3, 1/4........1/10 using for loop.
i=1
for i in range(1,11):
value=1.0/i
print("1/", i, "=", value)
Output:
1/ 1 = 1.0
1/ 2 = 0.5
1/ 3 = 0.333333333333
1/ 4 = 0.25
1/ 5 = 0.2
1/ 6 = 0.166666666667
1/ 7 = 0.142857142857
1/ 8 = 0.125

Prepared by: Mr. R A Khan Page 36


1/ 9 = 0.111111111111
1/ 10 = 0.1
3. 3. Write a python program to Print a count down from the given number to
zero using a while loop.
num=int(input("Enter a number: "))
print("count down from ", num, "to 0 :")
while (num >= 0):
print(num)
num = num - 1
Output:
Enter a number: 6
count down from 6 to 0:
6
5
4
3
2
1
0
3.4. Write a python program to Find the sum of all the primes below hundred.
sum=0
for j in range(1,100):
for i in range(2,j):
if (j% i) == 0:
break
else:
sum=sum+j #where j is a prime number
print("Sum of prime numbers up to 100 is", sum)
0utput:
Sum of prime numbers up to 100 is 1061
3. 5. Write a python program to find the factorial of a given number.
num=int(input("Enter a number: "))
fact=1
while (num>0):
fact=fact*num
num=num-1
print("Factorial of", num, "is",fact)
Output:
Enter a number: 6
Factorial of 6 is 720
Descriptive Questions

1. Explain Conditional Statements in Python with examples.

2. Write syntax and logical flow for if-elif-else.

Prepared by: Mr. R A Khan Page 37


3. Explain the significance of for loop with else using an example.

4. Differentiate between counter-controlled loops and sentinel-controlled loops.

5. Write the differences between iteration and recursion.

6. Explain the utility of break and continue statements with the help of an
example.

7. What is pass statement in python?

8. Explain with an example, how continue statement is used in python.

9. Write a program to display multiplication tables from 1 to 10.

10. Write a Python program that accepts a word from the user and reverse it

11. Write a Python program that accepts an integer (n) and computes the value
of n+nn+nnn. (Eg. If n=5, find 5+55+555).

12. Write a program to find the factorial of a given number.

Prepared by: Mr. R A Khan Page 38


Functions and Strings
Functions
 A function is a block of organized and reusable program code that
performs a single, specific, and well-defined task.
 Python enables its programmers to break up a program into functions,
each of which can be written more or less independently of the others.
Therefore, the code of one function is completely insulated from the
codes of the other functions.

Figure 1: Calling a function


 In figure 1 which explains how a function func1() is called to perform a
well-defined task. As soon as func1() is called, the program control is
passed to the first statement in the function. All the statements in the
function are executed and then the program control is passed to the
statement following the one that called the function.

Figure 2: Function calling another function


 In figure 2 func1() calls function named func2(). Therefore, func1() is
known as the calling function and func2() is known as the called function.
The moment the compiler encounters a function call, instead of
executing the next statement in the calling function, the control jumps to
the statements that are a part of the called function. After called function
is executed, the control is returned back to the calling program.

Prepared by: Mr. R A Khan Page 39


 It is not necessary that the func1() can call only one function, it can call
as many functions as it wants and as many times as it wants. For
example, a function call placed within for loop or while loop may call the
same function multiple times until the condition holds true.
Need for Functions:

Figure 3: Top-down approach of solving a problem


 Each function to be written and tested separately.
 Understanding, coding and testing multiple separate functions are far
easier than doing the same for one huge function.
 When a big program is broken into comparatively smaller functions, then
different programmers working on that project can divide the workload
by writing different functions.
 All the libraries in Python contain pre-defined and pre-tested functions
which the programmers are free to use directly in their programs,
without worrying about their code details. This speed up program
development.
 Like Python libraries, programmers can also make their own functions
and use them from different points in the main program or any other
program that needs its functionalities. So code reuse is one of the most
prominent reasons to use functions.
Function Declaration and Definition:
 A function, f that uses another function g, is known as the calling
function and g is known as the called function.
 The inputs that the function takes are known as arguments/parameters.
 When a called function returns some result back to the calling function,
it is said to return that result.
 The calling function may or may not pass parameters to the called
function. If the called function accepts arguments, the calling function
will pass parameters, else not.
 Function declaration is a declaration statement that identifies a function
with its name, a list of arguments that it accepts and the type of data it
returns.

Prepared by: Mr. R A Khan Page 40


 Function definition consists of a function header that identifies the
function, followed by the body of the function containing the executable
code for that function.
Function Definition
There are two basic types of functions
1. built-in functions eg: dir(), len(), abs() etc.,
2. user defined functions.
 Function blocks starts with the keyword def.
 The keyword is followed by the function name and parentheses (( )).
 After the parentheses a colon (:) is placed.
 Parameters or arguments that the function accept are placed within
parentheses.
 The first statement of a function can be an optional statement - the
docstringdescribe what the function does.
 The code block within the function is properly indented to form the block
code.
 A function may have a return[expression] statement. That is, the return
statement is optional.
 You can assign the function name to a variable. Doing this will allow you
to call same function using the name of that variable.

Figure 4: Program that subtracts two numbers using a function.

Figure 5: The syntax of a function definition.


Function Call
 Defining a function means specifying its name, parameters that are
expected, and the set of instructions.

Prepared by: Mr. R A Khan Page 41


 The function call statement invokes the function. When a function is
invoked the program control jumps to the called function to execute the
statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
 A function can take parameters which are nothing but some values that
are passed to it so that the function can manipulate them to produce the
desired result. These parameters are normal variables with a small
difference that the values of these variables are defined (initialized) when
we call the function and are then passed to the function.
 Function name and the number and type of arguments in the function
call must be same as that given in the function definition.
 If the data type of the argument passed does not matches with that
expected in function then an error is generated.

Figure 6: a function that displays string repeatedly.

Figure 7: Program to demonstrate mismatch of name of function parameters and


arguments.
Note: Names of variables in function call and header of function definition may
vary.

Prepared by: Mr. R A Khan Page 42


Figure 8: Arguments may be passed in the form of expressions to the called
function.

Figure 9: Program to add two integers using functions


Variable scope and lifetime:
In python, you cannot just access any variable from any part of your program.
Some of the variables may not even exist for the entire duration of the program. In
which part of the program you can access a variable and in which parts of the
program a variable exits depends on how the variable has been declared.
Therefore, we need to understand these two things:
1. Scope of the variable: Part of the program in which a variable is accessible is
called its scope.
2. Lifetime of the variable: Duration for which the variable exits it‟s called its
lifetime.
Local and Global variables:
A variable which is defined within a function is local to that function. A local
variable can be accessed from the point of its definition until the end of the
function in which it is defined. It exists as long as the function is executing.
Function parameters behave like local variables in the function. Moreover,
whenever we use the assignment operator (=) inside a function, a new local
variable is created.

Prepared by: Mr. R A Khan Page 43


Global variables are those variables which are defined in the main body of the
program file. They are visible throughout the program file. As a good programming
habit, you must try to avoid the use of global variables because they may get
altered by mistake and then result in erroneous output.

Figure 10: lists the differences between global and local variables.
Comparison between global and Local variables
local variables Global variables
They are defined in the main body They are defined within a function and is local
of the program file. to that function.
They can be accessed throughout They can be accessed from the point of its
the program life. definition until the end of the block in which
it is defined.
Global variables are accessible to They are not related in any way to other
all functions in the program. variables with the same names used outside
the function.
Using the Global Statement
To define a variable defined inside a function as global, you must use the global
statement. This declares the local or the inner variable of the function to have
module scope.
Key points to remember:
You can have a variable with the same name as that of a global variable in the
program. In such a case a new local variable of that name is created which is
different from the global variable.

Prepared by: Mr. R A Khan Page 44


Figure 11: Program to demonstrate the use of global statement.
Resolution of names
Scope defines the visibility of a name within a block. If a local variable is
defined in a block, its scope is that particular block. If it is defined in a
function, then its scope is all blocks within that function.
When a variable name is used in a code block, it is resolved using the nearest
enclosing scope. If no variable of that name is found, then a NameError is
raised. In the code given below, str is a global string because it has been
defined before calling the function.

Figure 12: Program that demonstrates using a variable defined in global


namespace.
The Return Statement
The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is
present, it is evaluated and the resultant value is returned to the calling
function. However, if no expression is specified then the function will return
none.
The return statement is used for two things.
• Return a value to the caller
• To end and exit a function and go back to its caller

Prepared by: Mr. R A Khan Page 45


Figure 13: Program to write another function which returns an integer to the
caller.
More on defining functions:
In this section we will discuss some more ways of defining a function.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
In the required arguments, the arguments are passed to a function in correct
positional order. Also, the number of arguments in the function call should
exactly match with the number of arguments specified in the function
definition
Example:

Keyword Arguments
When we call a function with some values, the values are assigned to the
arguments based on their position. Python also allow functions to be called
using keyword arguments in which the order (or position) of the arguments can
be changed. The values are not assigned to arguments according to their
position but based on their name (or keyword).
Keyword arguments are beneficial in two cases.
 First, if you skip arguments.
 Second, if in the function call you change the order of parameters.
Example:

Prepared by: Mr. R A Khan Page 46


Default Arguments
Python allows users to specify function arguments that can have default
values. This means that a function can be called with fewer arguments than it
is defined to have.
That is, if the function accepts three parameters, but function call provides
only two arguments, then the third parameter will be assigned the default
(already specified) value. The default value to an argument is provided by using
the assignment operator (=). Users can specify adefault value for one or more
arguments.
Example:

Variable-length Arguments
In some situations, it is not known in advance how many arguments will be
passed to a function. In such cases, Python allows programmers to make
function calls with arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the
function definition use an asterisk (*) before the parameter name. The syntax
for a function using variable arguments can be given as,

Prepared by: Mr. R A Khan Page 47


Example:

Lambda Functions or Anonymous Functions


Lambda or anonymous functions are so called because they are not declared as
other functions using the def keyword. Rather, they are created using the
lambda keyword.
Lambda functions are throw-away functions, i.e. they are just needed where
they have been created and can be used anywhere a function is required. The
lambda feature was added to Python due to the demand from LISP
programmers.
Lambda functions contain only a single line. Its syntax can be given as,

Example

Documentation Strings
Docstrings (documentation strings) serve the same purpose as that of
comments, as they are designed to explain code. However, they are more
specific and have a proper syntax.

Prepared by: Mr. R A Khan Page 48


Example:

Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a call to
itself. Every recursive solution has two major cases, which are as follows:
 base case, in which the problem is simple enough to be solved directly
without making any further calls to the same function.
 recursive case, in which first the problem at hand is divided into simpler
sub parts.
Recursion utilized divide and conquer technique of problem solving.
Example:

Recursion vs Iteration:

Prepared by: Mr. R A Khan Page 49


Recursion is more of a top-down approach to problem solving in while the
original problem is divided into smaller sub-problems.
Iteration follows a bottom-up approach that begins with what is known and
then constructing the solution step-by-step.
Pros The benefits of using a recursive program are:
Recursive solutions often tend to be shorter and simpler than non-recursive
ones.
Code is clearer and easier to use.
Recursion uses the original formula to solve a problem.
It follows a divide and conquer technique to solve problems.
In some instances, recursion may be more efficient.
Cons The limitations of using a recursive program are:
For some programmers and readers, recursion is difficult concept.
Recursion is implemented using system stack. If the stack space on the
system is limited, recursion to a deeper level will be difficult to implement.
Aborting a recursive process in midstream is slow and sometimes nasty.
Using a recursive function takes more memory and time to execute as
compared to its non-recursive counterpart.
It is difficult to find bugs, particularly when using global variables.
Conclusion: The advantages of recursion pays off for the extra overhead
involved in terms of time and space required.
Modules
 We have seen that functions help us to reuse a particular piece of code.
Module goes a step ahead. It allows you to reuse one or more functions
in your programs, even in the programs in which those functions have
not been defined.
 Putting simply, module is a file with a.py extension that has definitions
of all functions and variables that you would like to use even in other
programs. The program in which you want to use functions or variables
defined in the module will simply import that particular module (or .py
file).
 Modules are pre-written pieces of code that are used to perform common
tasks like generating random numbers, performing mathematical
operations, etc.
 The basic way to use a module is to add import module_name as the first
line of your program and then writing module_name.var to access
functions and values with the name var in the module.
The from…import Statement
A module may contain definition for many variables and functions. When you
import a module, you can use any variable or function defined in that module.

Prepared by: Mr. R A Khan Page 50


But if you want to use only selected variables or functions, then you can use
the from...import statement. For example, in the aforementioned program you
are using only the path variable in the sys module, so you could have better
written from sys import path.
Example:

To import more than one item from a module, use a comma separated list. For
example, to import the value of pi and sqrt() from the math module you can
write,

Making your own Modules


Every Python program is a module, that is, every file that you save as .py
extension is a module.
 Modules should be placed in the same directory as that of the program in
which it is imported. It can also be stored in one of the directories listed
in sys.path.

Prepared by: Mr. R A Khan Page 51


The dir() function
dir() is a built-in function that lists the identifiers defined in a module. These
identifiers may include functions, classes and variables. If no name is specified,
the dir() will return the list of names defined in the current module.
Example: demonstrate the use of dir() function.

The Python Module:


 We have seen that a Python module is a file that contains some
definitions and statements. When a Python file is executed directly, it is
considered the main module of a program.
 Main modules are given the special name __main__ and provide the basis
for a complete Python program.
 The main module may import any number of other modules which may
in turn import other modules. But the main module of a Python program
cannot be imported into other modules.
Modules and Namespaces
A namespace is a container that provides a named context for identifiers. Two
identifiers with the same name in the same scope will lead to a name clash. In
simple terms, Python does not allow programmers to have two different
identifiers with the same name. However, in some situations we need to have
same name identifiers. To cater to such situations, namespaces is the keyword.
Namespaces enable programs to avoid potential name clashes by associating
each identifier with the namespace from which it originates.
Example:

Prepared by: Mr. R A Khan Page 52


Local, Global, and Built-in Namespaces
During a program‟s execution, there are three main namespaces that are
referenced- the built-in namespace, the global namespace, and the local
namespace. The built-in namespace, as the name suggests contains names of all
the built-in functions, constants, etc that are already defined in Python. The global
namespace contains identifiers of the currently executing module and the local
namespace has identifiers defined in the currently executing function (if any).
When the Python interpreter sees an identifier, it first searches the local
namespace, then the global namespace, and finally the built-in namespace.
Therefore, if two identifiers with same name are defined in more than one of these
namespaces, it becomes masked.
Example: Program to demonstrate name clashes in different namespaces

Module Private Variables

Prepared by: Mr. R A Khan Page 53


 In Python, all identifiers defined in a module are public by default. This
means that all identifiers are accessible by any other module that
imports it. But, if you want some variables or functions in a module to be
privately used within the module, but not to be accessed from outside it,
then you need to declare those identifiers as private.
 In Python identifiers whose name starts with two underscores (__) are
known as private identifiers. These identifiers can be used only within
the module. In no way, they can be accessed from outside the module.
 Therefore, when the module is imported using the import * form
modulename, all the identifiers of a module‟s namespace is imported
except the private ones (ones beginning with double underscores). Thus,
private identifiers become inaccessible from within the importing module.
Advantages of Modules:
 Python modules provide all the benefits of modular software design.
These modules provide services and functionality that can be reused in
other programs.
 Even the standard library of Python contains a set of modules. It allows
you to logically organize the code so that it becomes easier to understand
and use.
Programs:
1. Write a function cumulative product to compute cumulative product of a list
of numbers.
Program:
def cumulative_product():
list=[1,2,3,4]
prod=1
for i in list:
prod=prod*i
print prod
cumulative_product()
Output:

Prepared by: Mr. R A Khan Page 54


2. Write function to compute gcd, lcm of two numbers. Each function
shouldn‟t exceed one line.
Program:
from fractions import gcd
print gcd(5,25)
def lcm():
a=60
b=40
print (a * b) // gcd(a, b)
lcm()
output:

3. Find the sum of the even-valued terms in the Fibonacci sequence whose
values do not exceed ten thousand.

Prepared by: Mr. R A Khan Page 55


program:
i=0
j=1
sum=0
while(i<10000):
i=i+j
j=i-j
if(i%2==0):
sum+=i
print sum
output:

Strings
 Python treats strings as contiguous series of characters delimited by
single, double or even triple quotes. Python has a built-in string class
named "str" that has many useful features. We can simultaneously
declare and define a string by creating a variable of string type. This can
be done in several ways which are as follows:
 name = "India" graduate = 'N' country = name nationality = str("Indian")
 Indexing: Individual characters in a string are accessed using the
subscript ([ ]) operator. The expression in brackets is called an index. The
index specifies a member of an ordered set and in this case it specifies
the character we want to access from the given set of characters in the
string.
 The index of the first character is 0 and that of the last character is n-1
where n is the number of characters in the string. If you try to exceed the
bounds (below 0 or above n-1), then an error is raised.

Prepared by: Mr. R A Khan Page 56


 Traversing a String: A string can be traversed by accessing character(s)
from one index to another. For example, the following program uses
indexing to traverse a string from first character to the last.
Example:

Concatenating, Appending and Multiplying Strings


Example: Program to concatenate two strings using + operator

Example: Program to repeat a string using * operator

Example: Program to append a string using += operator

Prepared by: Mr. R A Khan Page 57


Strings are Immutable
Python strings are immutable which means that once created they cannot be
changed. Whenever you try to modify an existing string variable, a new string is
created.
Example:

Prepared by: Mr. R A Khan Page 58


String Formatting Operator
The % operator takes a format string on the left (that has %d, %s, etc) and
the corresponding values in a tuple on the right. The format operator, % allow
users to construct strings, replacing parts of the strings with the data stored in
variables. The syntax for the string formatting operation is:
"<Format>" % (<Values>)
Example:

Built-in String Methods and Functions

Prepared by: Mr. R A Khan Page 59


Prepared by: Mr. R A Khan Page 60
Programs:
1. Write a program that accepts a string from a user and re-displays the
same after removing vowels from it.
Program:
while True:
Prepared by: Mr. R A Khan Page 61
print('Enter x for exit.')
string = raw_input('Enter any string: ')
if string == 'x':
break
else:
newstr = string
print("\nRemoving vowels from the given string...")
vowels = ('a', 'e', 'i', 'o', 'u')
for x in string.lower():
if x in vowels:
newstr = newstr.replace(x,"")
print("New string after successfully removing all vowels!")
print(newstr,"\n")
output:

2. Write a program to calculate the length of a string.


Program:
string=raw_input("Enter string:")
count=0
for i in string:
count=count+1
print("Length of the string is:")
print(count)
output:

Prepared by: Mr. R A Khan Page 62


3. Write a function to reverse a given string.
Program:
def reverse(text):
lst = []
count = 1
for i in range(0,len(text)):
lst.append(text[len(text)-count])
count += 1
lst = ''.join(lst)
return lst
print reverse('Python Programming')
output:

Prepared by: Mr. R A Khan Page 63


Subjective Questions
1. Define function and give its advantages.
2. Differentiate between local and global variables.
3. What are modules? How do you use them in your programs?
4. Write short notes on
a) Keyword arguments
b) Default arguments
5. What are docstrings?
6. Write short note on format operator.
7. With the help of an example, explain how we can create string variables in
Python.
8. What are user-defined functions? Explain with the help of example.
9. Briefly describe String formatting operator with an example.
10. List out Advantages and disadvantages of Recursion.
11. Write a python program to find the factorial of a given number using recursion.
12. Write any 5 Built-in string methods and functions usage and example.

--------- to be continued

Prepared by: Mr. R A Khan Page 64

You might also like