FYBSC CS Programming With Python I
FYBSC CS Programming With Python I
(CS)
SEMESTER - I (CBCS)
PROGRAMMINGWITH
PYTHON - I
Course Writers :
Module - I
1. Programming with Python-I 01
2. Programming with Python-I 19
Module - II
4. Functions 48
6. Dictionaries 61
Module - III
7. Anonymous Functions 63
8. List Comprehensions 65
Syllabus
F.Y.B.Sc. (CS) Programming with Python - I
Semester I (CBCS)
Objectives
The objective of this paper is to introduce various concepts of
programming to the students using Python.
Unit I :
Reason for Python as the learner’s first programming language.
Introduction to the IDLE interpreter (shell) and its documentation.
Expression evaluation: similarities and differences compared to a
calculator; expressions and operators of types int, float, boolean. Built-in
function type. Operator precedence.
Unit II
Advantages of functions, function parameters, formal parameters,
actual parameters, global and local variables.
I
The range function, the iterative for statement. The conditional
statements if, if-else, if-elif-else. The iterative statements while, while-
else, for-else. The continue statement to skip over one iteration of a loop,
the break statement to exit the loop. Nested compound statements.
Dictionaries: concept of key-value pairs, techniques to create, update and
delete dictionary items. Problem-solving using compound types and
statements.
Unit III
Anonymous functions. List comprehensions. Gentle introduction to
object-oriented programming; using the built-in dir() function, enumerate
the methods of strings, tuples, lists, dictionaries. Using these methods for
problem-solving with compound types.
Text books:
1. Magnus Lie Hetland, Beginning Python: From Novice to Professional,
Apress
2. Paul Gries, et al., Practical Programming: An Introduction to
Computer Science Using Python 3, Pragmatic Bookshelf, 2/E 2014
Additional References:
1. Charles Dierbach, Introduction to Computer Science using Python,
Wiley, 2013
2. Paul Gries, Jennifer Campbell, Jason Montojo, Practical Programming:
An Introduction to Computer Science Using Python 3, Pragmatic
Bookshelf, 2/E 2014
3. Adesh Pandey, Programming Languages – Principles and Paradigms,
Narosa, 2008
II
1
PROGRAMMING WITH PYTHON- I
Unit Structure
1.1 Objective
1.2 Reasons for Python as the learner’s first programming language.
1.3 Introduction to the IDLE interpreter (shell) and its documentation.
Expression evaluation: similarities and differences compared to a
calculator; expressions and operators of types int, float, boolean.
1.4 Built-in function type.
1.5 Operator precedence
1.6 Summary
1.7 Reference for further reading
1.8 Unit End Exercises
1.1OBJECTIVE
1
3. Open Source and Community Development:
Python language is developed under an OSI-approved open source
license, which makes it free to use and distribute, including for
commercial purposes.
Applications of Python
GUI based desktop applications
o Image processing and graphic design applications
o Scientific and computational applications
o Games
Web frameworks and web applications
Enterprise and business applications
Operating systems
Language development
Prototyping
2
e. search within any window, replace within editor windows, and
search through multiple files (grep)
f. debugger with persistent breakpoints, stepping, and viewing of
global and local namespaces configuration, browsers, and other
dialogs
Menus
IDLE has two main window types, the Shell window and the Editor
window. It is possible to have multiple editor windows
simultaneously. On Windows and Linux, each has its own top menu.
Each menu documented below indicates which window type it is
associated with.
Output windows, such as used for Edit => Find in Files, are a subtype
of editor window. They currently have the same top menu but a
different default title and context menu.
On macOS, there is one application menu. It dynamically changes
according to the window currently selected. It has an IDLE menu, and
some entries described below are moved around to conform to Apple
guidelines.
File menu
New File
Create a new file editing window.
Open…
Open an existing file with an Open dialog.
Recent Files
Open a list of recent files. Click one to open it.
Open Module…
Open an existing module (searches sys.path).
Class Browser
Show functions, classes, and methods in the current Editor file in a tree
structure. In the shell, open a module first.
Path Browser
Show sys.path directories, modules, functions, classes and methods in
a tree structure.
Save
Save the current window to the associated file, if there is one.
Close
Close the current window (ask to save if unsaved).
Exit
Close all windows and quit IDLE (ask to save unsaved windows).
4
used to dynamically evaluate Python expressions from any input that
comes as a string or a compiled code object.
The eval() is defined as :
eval(expression[, globals[, locals]])
The function takes three arguments. The function takes a first
argument, called expression, which holds the expression that you need to
evaluate. eval() also takes two optional arguments:
1. globals
2. locals
>>> x = 50
>>>eval("x * 2")
100
1. Parse expression
2. Compile it to bytecode
3. Evaluate it as a Python expression
4. Return the result of the evaluation
Python
>>>x1 = 100 # A global variable
>>>eval("x1 + 100", {"x1": x1})
200
5
>>> y1 = 200 # Another global variable
>>>eval("x1 + y1", {"x1": x1})
Python
>>>eval("x1 + y1", {"x1": x1, "y1": y1})
300
Since you add y1 to your custom globals dictionary, the evaluation of "x1
+ y1" is successful and you get the expected return value of 300.
The following examples show that even though you supply an empty
dictionary to globals, the call to eval() will still have access to Python’s
built-in names:
Python
>>>eval("sum([13, 12, 25])", {})
50
>>>eval("min([19, 55, 12])", {})
12
>>>eval("pow(10, 2)", {})
100
Since eval() is already written, you can’t add local names to its
code . However, you can pass a dictionary to locals, and eval() will treat
those names as local names:
>>>eval("x1 + 100", {}, {"x1": 100})
200
Boolean Expressions
Python
>>>x1 = 100
>>> y1 = 100
>>>eval("x1 != y1")
False
7
>>>eval("x1< 300 and y1> 100")
False
>>>eval("x1 is y1")
True
eval()can be use with Boolean expressions that use any of the following
Python operators:
Math Expressions
One common use case of Python’s eval() is to evaluate math expressions
from a string-based input.
The following examples show how you can use eval() along with math to
perform math operations:
Python
>>> import math
>>> # Area of a circle
>>>eval("math.pi * pow(2, 2)")
12.56
General-Purpose Expressions
eval() can use with more complex Python expressions that incorporate
function calls, object creation, attribute access, comprehensions, and so
on.
For example, you can call a built-in function or one that you’ve
imported with a standard or third-party module:
Python
>>> import subprocess
>>>eval("subprocess.getoutput('echo Hi, Friends')")
'Hi, Friends'
8
For example:
Python
>>>12+93
115
Here, + is the operator that performs addition. 12 and 93 are the operands
and 115 is the output of the operation.
Arithmetic operators:
x = 15
y=4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
9
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Output
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators:
Operator Meaning:
a = 100
b = 112
print('a>ais',a>b)
Output: a > b is False
print('a<bis',a<b)
Output: a < b is True
print('a == b is',a==b)
Output: a == b is False
10
print('a != b is',a!=b)
Output: a != b is True
Logical operators
Operator Meaning
and if both the operands are true then condition become true.
or if either of the operands is true then condition become true.
not Used to reverse the logical state of its operand.
Example 1:
a=25
a += 10
print(“ a is : ”,a)
output:
a is : 35
Example 2:
a=25
a -= 10
print(“ a is : ”,a)
output:
a is : 15
Example 3:
a=25
a *= 2
print(“ a is : ”,a)
output:
a is : 50
12
Example 4:
a=25
a /= 5
print(“ a is : ”,a)
output:
a is : 5
Example 5:
a=26
a %= 5
print(“ a is : ”,a)
output:
a is : 1
Special operators
Python language offers some special types of operators like the identity
operator or the membership operator.
Identity operators
Example:
p=50
q=50
print(‘p =’,p,’:’,id(p))
p=50 : 80983211
print(‘q =’,p,’:’,id(q))
q=50 : 80983211
if(p is q)
13
print(‘p and q have same identity’)
else
print(‘p and q do not have same identity’)
output:
p and q have same identity
if(id(p) is id(q))
print(‘p and q have same identity’)
else
print(‘p and q do not have same identity’)
output:
p and q have same identity
if(p is not q)
print(‘p and q do not have same identity’)
else
print(‘p and q have same identity’)
output:
p and q have same identity
Membership operators
There are two membership operators in Python (in and not in).
They are used to test for membership in a sequence(string, list, tuple and
dictionary).
Example:
p=60
q=30
list1=[10,30,50,66]
example 1:
if(p in list):
print(‘p is in the list’)
else
print(‘p is not in the list’)
output:
p is not in the list
example 2:
if(p not in list):
print(‘p is not in the list’)
else
14
print(‘p is in the list’)
output:
p is not in the list
example 3:
if(q in list):
print(‘q is in the list’)
else
print(‘q is not in the list’)
output:
q is in the list
Built-in Functions
abs() delattr() hash() len() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
abs(x)
Return the absolute value of a number. The argument may be an
integer, a floating point number, or an object implementing __abs__(). If
the argument is a complex number, its magnitude is returned.
15
all (iterable)
Return True if all elements of the iterable are true (or if the iterable
is empty). Equivalent to:
def all(iterable):
for element in iterable:
if not element:
return False
return True
ascii(object)
classbool([x])
chr(i)
delattr(object, name)
divmod(a, b)
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or
some other object which supports iteration. The __next__() method of the
iterator returned by enumerate() returns a tuple containing a count (from
start which defaults to 0) and the values obtained from iterating over
iterable.
4 Operator precedence.
The order of the operation means the operator precedence to evaluate
an expression. The operator will help to evaluate the expression.
Following table shows which operator has highest presedence to lowest.
Operator Description
() Parentheses
** Exponent
+a, -a, ~a Unary plus, Unary minus, Bitwise NOT
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise shift operator
& Bitwise and
^ Bitwise XOR
| Bitwise or
==, !=, >, >=, <, <= Comparisons operator
Not Logical NOT
And Logical AND
Or Logical OR
operators with the highest precedence appear at the top of the table
Example:
>>> 5*2+10
20
17
In this example the first precedence is given to the division then addition
operator.
1.6 SUMMARY
18
2
PROGRAMMING WITH PYTHON- I
Unit Structure
2.1 Objective
2.2 Enumeration of simple and compound statements.
2.3 The expression statement. Theassert statement,
2.4 Boolean expression (values true or false).
2.5 The assignment statement, dynamic binding of names to values,
(type is associated with data and not with names); automatic and
implicit declaration of variable names with the assignment
statement; assigning the value None to a name.
2.6 The del (delete)statement.
2.7 Input/output with print and input functions.
2.8 A statement list (semicolon- separated list of simple statements on
a single line) as a single interpreter command.
2.9 The import statement for already defined functions and constants.
2.10 The augmented assignment statement.
2.11 The built-inhelp() function.
2.12 Summary
2.13 Reference for further reading
2.14 Unit End Exercises
2.1 OBJECTIVE
19
There are many simple statements like assert, break, continue, pass
,del,import, return, etc.
The syntax for simple statements is:
simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| annotated_assignment_stmt
| pass_stmt
| del_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| future_stmt
| global_stmt
| nonlocal_stmt
If Statement:
This statement is used for conditional execution. The syntax of the
statement is as follows,
if expression: suite
elif expression: suite
else: suite
while Statement
While statement is used to execute a block of statements repeatedly
until a given condition is fulfilled. Syntax of the statement is as follows
while expression:
statement(s)
for statement:
for statement is used to traverse a list or string or array in a
sequential manner for example
print("List Iteration")
l = ["python", "for", "programmers"]
for i in l:
print(i)
try statement:
20
The try statement specifies exception handlers and/or cleanup code
for a group of statements.
With statement:
The with statement is used to wrap the execution of a block with
methods defined by a context manager where a context manager is an
object that defines the runtime context to be established.
Example:
>>> i=5
>>> a=10
>>> #keyword cannot be used in asignment
>>>for=5
SyntaxError: invalid syntax
if __debug__:
if not expression: raise AssertionError
21
The extended form, assert expression1, expression2, is equivalent to
if __debug__:
if not expression1: raise AssertionError(expression2)
These equivalences assume that __debug__ and AssertionError refer to
the built-in variables with those names. In the current implementation,
the built-in variable __debug__ is True under normal circumstances,
False when optimization is requested (command line option -O). The
current code generator emits no code for an assert statement when
optimization is requested at compile time. Note that it is unnecessary
to include the source code for the expression that failed in the error
message; it will be displayed as part of the stack trace.
In python, you can directly use the word “and ” instead of “&&” to
denote the “and ” boolean operator while for other languages, you need to
put “&&” instead. Consequently,
Example:
a = 30
b = 45
if(a > 30 and b == 45):
print("True")
22
else:
print("False")
Output:
False
a = 25
b = 30
if(a > 30 or b < 45):
print("True")
else:
print("False")
Output:
True
Output:
Else Executed
23
2.5 DYNAMIC BINDING OF NAMES TO VALUES,
(TYPE IS ASSOCIATED WITH DATA AND NOT WITH
NAMES); AUTOMATIC AND IMPLICIT
DECLARATION OF VARIABLE NAMES WITH THE
ASSIGNMENT STATEMENT; ASSIGNING THE
VALUENONE TO A NAME.
Example:
#This will store 99 in the memory and binds the name x to it. After it runs,
type of x will be int.
x = 99
print(type(x))
# This will store 'India' at some location int the memory and binds name x
to it. After it runs type of x will be str.
x = 'India'
print(type(x))
Output:
<class 'int'>
<class 'str'>
Variables
As the name implies, a variable is something which can change. A
variable is a way of referring to a memory location used by a computer
program. A variable is a symbolic name for this physical location. This
memory location contains values, like numbers, stringetc.
24
Another aspect of Python: Not only the value of a variable may
change during program execution but the type as well. You can assign an
float value to a variable, use it as an float for a while and then assign a
string to the variable.
Example:
x = 122
>>>print x
122
>>> x =”Mumbai”
>>>print x
Mumbai
>>>
None is not the same as 0 (Zero), False, or an empty string. None is a data
type of its own and only None can be None.
List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# deleting the third item
del list1[2]
# Output: [1, 2, 4, 5, 6, 7, 8, 9]
print(list1)
# deleting items from 2nd to 4th
del list1[1:4]
# Output: [1, 6, 7, 8, 9]
print(list1)
# deleting all elements
del list1[:]
# Output: []
print(list)
26
2.7 INPUT/OUTPUT WITH PRINT AND INPUT
FUNCTIONS.
Python Input:
In Python, input() function to allow to take the input from the user.
The syntax for input() is:
input([prompt])
Example 1 :
print(' Python programming')
Output:
Python programming
example 2:
a = 56
print(‘a is', a)
Output
a is 56
27
The file is the object where the values are printed and its default value is
sys.stdout.
print(11, 21, 31, 41)
print(11, 21, 31, 41, sep='$')
print(11, 21, 31, 41, sep='@', end='#')
Output
11 21 31 41
11$21$31$41
11@21@31@41#
a=10
b=20
c=a*b
print (c)
These statements can very well be written in one line by putting semicolon
in between.
for i in range(4):
print ("Mumabi")
print ("i=",i)
28
2.9 THE IMPORT STATEMENT FOR ALREADY-
DEFINED FUNCTIONS AND CONSTANTS.
Importing a Module
now import this module and execute the sum() function in the Python.
Example:
# main.py
import constants1
No2 = 170
29
total = No2 + constants1.No1
print("Toatl is {total}")
Output:
Total is 190
# Addition
a = 10
b=5
a += b
print('Addition = %d' %(a))
OUTPUT
Addition = 15
# Subtraction
a = 10
b=5
a -= b
print('Subtraction = %d' %(a))
OUTPUT
Subtraction = 5
PROGRAM
30
# Multiplication
a = 10
b=5
a *= b
print('Multiplication = %d' %(a))
OUTPUT
Multiplication = 50
PROGRAM
# Division
a = 23
b=3
a /= b
print('Division = %f' %(a))
OUTPUT
Division = 7.666667
PROGRAM
# Remainder or Modulo
a = 12
b=5
a %= b
print('Remainder or Modulo = %d' %(a))
OUTPUT
Remainder or Modulo = 2
31
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
2.12 SUMMARY
32
3
PROGRAMMING WITH PYTHON- I
Unit Structure
3.1 Objective
3.2 Interactive and script modes of IDLE, running a script, restarting
the shell.
3.3 The compound statement def to define functions; the role of
indentation for delimiting the body of a compound statement;
calling a previously defined function. Compound data types str,
tuple and list (enclosed in quotes, parentheses and brackets,
respectively). Indexing individual elements within these types.
Strings and tuples are immutable, lists are mutable.
3.4 Built-in functions min, max, sum.
3.5 Interactive solution of model problems, (e.g., finding the square
root of a number or zero of a function), by repeatedly executing the
body of a loop (where the body is a statement list).
3.6 Summary
3.7 Reference for further reading
3.8 Unit End Exercises
3.1 OBJECTIVE
33
you can restart the shell from this menu. If you select that option,
then you’ll clear the state of the shell. It will act as though you’ve started a
fresh instance of Python IDLE. The shell will forget about everything
from its previous state.
Syntax of Function
deffunction_name(parameters):
"""docstring"""
statement(s)
34
Parameters (arguments) through which we pass values to a function.
A colon (:) to mark the end of the function header.
Optional documentation string (docstring) to describe what the function
does.
One or more valid python statements that make up the function body.
Statements must have the same indentation level.
An optional return statement to return a value from the function.
Example of a function
defdisp(name):
print("Hi, " + name + ". Good morning!")
>>>disp('Raj')
Hi, Raj. Good morning!
For example:
>>>print(disp.__doc__)
Syntax of return
return [expression_list]
35
For example:
>>>print(disp("Deep"))
Hello, deep. Good morning!
None
Here, None is the returned value since disp() directly prints the name
and no return statement is used.
Example of return
defabsolute_value(num):
"""This function returns the
value of the entered number"""
if number >= 0:
return number
else:
return -number
print(absolute_value(92))
print(absolute_value(-64))
Output
92
64
Example:
def my_func1():
x1 = 100
print("Value inside function is :",x1)
x = 220
my_func1()
36
print("Value outside function is :",x1)
Output
Here, we can see that the value of x1 is 220 initially. Even though the
function my_func1() changed the value of x1 to 100, it did not affect
the value outside the function.
On the other hand, variables outside of the function are visible from
inside. They have a global scope.
We can read these values from inside the function but cannot change
them. In order to modify the value of variables outside the function,
they must be declared as global variables using the keyword global.
Types of Functions
Basically, we can divide functions into the following two types:
Python’s math module, in the standard library, this library can help
you work on math-related problems in code. It contains useful
37
functions, such as remainder() and factorial(). It also includes the
Python square root function, sqrt().
importing math:
>>>math.sqrt(49)
7.0
>>>math.sqrt(70.5)
8.396427811873332
>>>math.sqrt(0)
0.0
List
Dictionaries
Tuples
List:
The list are the mutable data type. Mutable means you can do
changes in the list elements after crating the list.
Mutable Concept:
The list are the mutable data type. Mutable means you can do
changes in the list elements after creating the list.
After creating list of the six elements then you can change the
value of any element in the list.
Example:
>>>list=[13,66,88,45,76,77]
>>>print(“value of second index position ”,list[2])
88
>>list[2]=999
>>>print(“value of second index position ”,list[2])
999
>>> List2=[]
>>L2
[‘Raj’,’Deep’]
>>>del list[2]
39
>>print(list)
[10,20,40,50]
Build in function:
Min Function:
The min() function is used to find the minimum value from the list.
Max Function:
The max() function is used to find the maximum value from the
list.
List Operators:
There are two list operator ‘+’and ‘*’ are use in python.
Operator ‘+’ are used for concatenation and operator ‘*’are used
for repetation.
Operator ‘+’
The ‘+’ operator is used for concatenating the list.
Example:
>>>x1=[11,33,55]
>>>x2=[67,87,92]
>>x3=x1+x2
>>>X3
[11,33,55,67,87,92]
Operator ‘*’
>>> x=[11,33,55]
>>>x*2
[11,33,55,11,33,55
In Operator:
Operator in us used to find that given element is present in the list.
If given element is present in the list it return true.
Example:
>>x=[11,33,55,66,78,98,211]
>> 66 in x
True
40
Tuples:
Creating Tuple
>> tuple1=(‘a’,’b’,c’,’d’)
>>print(tuple1)
(‘a’,’b’,c’,’d’)
>> tuple1=(‘Deep’,’Raj’,Sam’,’Geet’)
Min method:
>>tuple2=(12,34,5,67,55)
>>print(“Minimum values”,min(tuple2))
5
Max method:
>>>tuple2=(12,34,5,67,55)
>>>print(“Maximum values”,max(tuple2))
67
Len Method:
41
>>>len(tuple2)
5
Cmp Method:
Tuple Operators:
There are two operator ‘+’and ‘*’ are use in python.
Operator ‘+’ are used for concatenation and operator ‘*’are used
for repetition.
Operator ‘+’
The ‘+’ operator is used for concatenating the two tuple.
Example:
>>>x1=(1,3,5)
>>>x2=(67,87,92)
>>x3=x1+x2
>>>X3
(1,3,5,67,87,92)
Operator ‘*’
>>> x=(1,3,5)
>>>x*2
(1,3,5,1,3,5)
In Operator:
Operator in us used to find that given element is present in the
tuple . If givenelement is present it return true.
Example:
>>x=(11,33,55,66,78,98,211)
>> 66 in x
True
Dictionaries:
Dictionaries are the mutable data types. Each key available in the
dictionary is separated from its values by using the colon(:). The
items of the dictionary are separated by using a comma(,) and the
entire thing in enclosed in curly braces.
>>print(“Name is”,mydict([“name”])
42
Name is Deep
>>print(“Age is”,mydict([“age”])
Age is 29
>>>del(mydict([“name”]
>>>mydict
{“surname”:”patil”, “age”:29}
d.clear()
Clears a dictionary.
>>>d1.clear()
>>> d1
{}
d.get(<key>[, <default>])
>>>print(d.get('a2'))
43
20
>>>print(d.get('a8'))
None
d.items()
>>>list(d1.items())
[('a1', 10), ('a2', 20), ('a3', 30)]
>>>list(d1.items())[1][1]
20
d1.keys()
>>>list(d1.keys())
['a1', 'a2', 'a3']
Python’s math module, in the standard library, can help you work on
math-related problems in code. It contains many useful functions, such
as remainder() and factorial(). It also includes the Python square root
function, sqrt().
44
You’ll begin by importing math:
>>>math.sqrt(49)
7.0
>>>math.sqrt(70.5)
8.396427811873332
Max Function:
Syntax :
max(a,b,c,..,key,default)
Parameters :
a,b,c,.. : similar type of data.
key : key function where the iterables are passed and comparsion is
performed
default : default value is passed if the given iterable is empty
Return Value :
Returns the maximum of all the arguments.
Example:
print (max( 4,12,43.3,19,100 ) )
output:
100
min()
This function is used to compute the minimum of the values passed in
its argument and lexicographically smallest value if strings are passed
as arguments.
Syntax :
min(a,b,c,.., key,default)
45
Parameters :
a,b,c,.. : similar type of data.
key : key function where the iterables are passed and comparsion is
performed
default : default value is passed if the given iterable is empty
Return Value :
Returns the minimum of all the arguments.
Example:
print (min( 4,12,43.3,19,100 ) )
output:
4
Sum Function:
Sum of numbers in the list is required everywhere. Python provide an
inbuilt function sum() which sums up the numbers in the list.
Syntax:
sum(iterable, start)
iterable :iterable can be anything list , tuples or dictionaries ,but most
importantly it should be numbers.
start : this start is added to the sum of
numbers in the iterable.
If start is not given in the syntax , it is assumed to be 0.
numbers = [1,2,3,4,5,1,4,5]
Sum = sum(numbers)
print(Sum)
3.5 SUMMARY
46
3.6 REFERENCE FOR FURTHER READING
47
Module II
4
FUNCTIONS
Unit Structure
4.1.1 Definition
4.1.2 Advantages
4.1.3 Function types
4.1.4 Parameters and arguments
4.1.5 Return statement
4.1.6 recursive function
4.1.7 Global and local varibles
Built in functions
A function which is already defined in a program or programming
framework with a set of statements, which together performs a task
and it is called Build-in function. There is no need for a user to create
these functions and these can be used directly in their program or
application.
48
The Python interpreter has a number of functions and types built into it
that are always available. They are listed here in alphabetical order.
abs(x)
abs()
returns absolute value of a number
all()
returns true when all elements in iterable is true
any()
Checks if any Element of an Iterable is True
ascii()
Returns String Containing Printable Representation
bin()
converts integer to binary string
bool()
Converts a Value to Boolean
bytearray()
returns array of given byte size
bytes()
returns immutable bytes object
callable()
Checks if the Object is Callable
chr()
Returns a Character (a string) from an Integer
classmethod()
returns class method for given function
compile()
Returns a Python code object
complex()
Creates a Complex Number
delattr()
Deletes Attribute From the Object
dict()
Creates a Dictionary
dir()
Tries to Return Attributes of Object
divmod()
Returns a Tuple of Quotient and Remainder
enumerate()
Returns an Enumerate Object
eval()
49
Runs Python Code Within Program
exec()
Executes Dynamically Created Program
filter()
constructs iterator from elements which are true
float()
returns floating point number from number, string
format()
returns formatted representation of a value
frozenset()
returns immutable frozenset object
getattr()
returns value of named attribute of an object
globals()
returns dictionary of current global symbol table
hasattr()
returns whether object has named attribute
hash()
returns hash value of an object
help()
Invokes the built-in Help System
hex()
Converts to Integer to Hexadecimal
id()
Returns Identify of an Object
input()
reads and returns a line of string
int()
returns integer from a number or string
isinstance()
Checks if a Object is an Instance of Class
issubclass()
Checks if a Class is Subclass of another Class
iter()
returns an iterator
len()
Returns Length of an Object
list()
50
creates a list in Python
locals()
Returns dictionary of a current local symbol table
map()
Applies Function and Returns a List
max()
returns the largest item
memoryview()
returns memory view of an argument
min()
returns the smallest value
next()
Retrieves next item from the iterator
object()
creates a featureless object
oct()
returns the octal representation of an integer
open()
Returns a file object
ord()
returns an integer of the Unicode character
pow()
returns the power of a number
print()
Prints the Given Object
property()
returns the property attribute
range()
return sequence of integers between start and stop
repr()
returns a printable representation of the object
reversed()
returns the reversed iterator of a sequence
round()
rounds a number to specified decimals
set()
constructs and returns a set
setattr()
sets the value of an attribute of an object
51
slice()
returns a slice object
sorted()
returns a sorted list from the given iterable
staticmethod()
transforms a method into a static method
str()
returns the string version of the object
sum()
Adds items of an Iterable
super()
Returns a proxy object of the base class
tuple()
Returns a tuple
type()
Returns the type of the object
vars()
Returns the __dict__ attribute
zip()
Returns an iterator of tuples
__import__()
Function called by the import statement
User defined function
They are functions created by the user. They are defined once and
called multiple times.
Syntax:-
def functionname( parameters ):
block of statements
return [expression]
function call
function call
Example:
def display(name):
print(name)
return
display()
display()
52
4.1.4 PARAMETER AND ARGUMENT
Actual parameters
Example:
Def add(a,b):
print(a+b)
add(20,30)
output: 50
Default arguments
A default argument is a default value which is used by a function if
avalue is not provided
Eg: def display(marks = 40)
The Python return statement is a special statement that you can use
inside a function or method to send the function's result back to the
caller. A return statement consists of the return keyword followed by
an optional return value. The return value of a Python function can be
any Python object
Example:-
def add(a,b):
return(a+b)
print((“sum =”,add(10,20))
output:
sum= 30
53
4.1.6 GLOBAL AND LOCAL VARIABLES
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.
Example :
g = "global"
def display():
print("Global variable inside the Function :", g)
display()
print("Global variable outside the Function:", g)
Local Variables
A variable declared inside the function's body or in the local scope is
known as a local variable.
Example :
def display():
l=”Local”
print(l)
display()
54
5
CONDITIONAL STATEMENTS AND
LOOPS
Unit Structure
5.2.1 Range function
5.2.2 Iterative for statement
5.2.3 Conditional statements if, if…else, if…elif…else and Nested if
5.2.4 Loops
55
5.2.2 ITERATIVE FOR STATEMENT
Example:
If statement
Syntax:
if expression
Statement
else
Statement
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
56
Else
If the condition is false the block of else is executed. Else is optional
Syntax:
if test expression:
Body of if
else:
Body of else
57
Elif
If condition for if is false the conditions in elif are checked if the
conditions are true the blocks are excuted. It allows us to check for
multiple expressions.
Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
Example:
x = 105
if x > 10:
print("Above ten,")
if x > 100:
print("and also above 100")
else:
print("but not above 20.")
5.2.4 LOOPS
Syntax:
while expression:
Block of statements
Example:
i=1
while i < 10:
print(i)
i += 1
While …else
While loops can also have a optional else block. The else part is
executed if the condition in while loop is evaluated as false.
counter = 0
Example:
Syntax:
while expression:
Block of statements
If condition:
continue
60
6
DICTIONARIES
Unit Structure
6.3.1 What is a dictionary?
6.3.1 What is a dictionary?
Dictionary Items
Dictionary items are ordered, changeable, and does not allow
duplicates.
61
"Rollno": 01
}
studentinfo["DOB"] = "01/01/2020" #new item added
Deleting an item from a dictionary
Individual elements can be removed from a dictionary
Syntax:
del dictionary_name[item]
Example:
Example:
studentinfo = {
"Name": "John",
"Class": "FYCS",
"Rollno": 01
}
print(studentinfo)
del studentinfo[Rollno]
print(studentinfo)
62
Module - III
7
ANONYMOUS FUNCTIONS
Unit Structure
7.1 Introduction to Annonymous function
7.1.1 What are Annonymous functions in Python?
7.1.2 Use of Annonymous functions
7.1.3 How to use Annonymous Functions in a Python program?
7.1.4 Using Anonymous functions with other built-in functions
7.1.5 Using Anonymous function with filter()
7.1.6 Using Anonymous function with map()
Example:
= [10, 15, 20, 25, 30]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output:
[10, 20, 30]
EXAMPLE:
my_list = [1, 2, 3, 4, 5]
new_list = list(map(lambda x: x * 10 , my_list))
print(new_list)
OUTPUT:
[10, 20, 30, 40, 50]
Questions:
1. Explain Anonymous functions ?
2. Write a short note on lambda functions ?
3. Explain use of Anonymous functions with other built in functions ?
4. Explain with an example use of Anonymous function with filter().
5. Explain with an example use of Anonymous function with map().
64
8
LIST COMPREHENSIONS
Unit Structure
8.2 List Comprehensions
8.2.1 what are list comprehensions ?
8.2.2 using List Comprehensions with a existing list
8.2.3 using list comprehensions with a Range
The result of the first expression will be stored in the new list.
The for loop is used to iterate over the iterable object that optionally
includes the if condition.
EXAMPLE:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
65
OUTPUT:
EXAMPLE :
CREATE A LIST OF EVEN NUMBERS WITH LIST
COMPREHENSION
even_nums = [x for x in range(31) if x%2 == 0]
print(even_nums)
OUTPUT:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
Queswtions:
1. Explain list comprehensions with an Example.
2. Explain with an example how list comprehensions can be used with an
existing list().
3. Explain with an example how list comprehensions can be used with
range().
66
9
INTRODUCTION TO OBJECT ORIENTED
PROGRAMMING
Unit Structure
9.3 Introduction to Object Oriented Programming
9.3.1 what is Object oriented programming?
9.3.2 Major Python OOPs concept
9.3.3Class
9.3.4 Object
9.3.5 Method
9.3.6 Inheritance
9.3.7 Encapsulation
9.3.8 Polymorphism
9.3.9 Data Abstraction
67
9.3.3Class
A class is a collection of objects.
Class creates a user-defined data structure, which holds its own data
members and member functions.
A class can be accessed and used by creating an instance of that class
which is an object
Classes are created by keyword class
Syntax:
class classname:
statements
.
.
.
Example:
class newclass:
display():
print(“new class”)
9.3.4 Object
An object is a self-contained component which consists of methods
and properties to make a particular type of data useful.
An Object is an identifiable entity with some characteristics and
behavior
. An Object is an instance of a Class.
When a class is defined, no memory is allocated but when an object is
created memory is allocated.
Syntax:
class classname:
statements
.
.
.
Object = classname()
Example:
class newclass:
def display():
print(“new class”)
o=newclass()
68
Example:
class newclass:
def display(a):
print(“new class”)
o=newclass()
o.display()
9.3.6 Inheritance
Inheritance allows us to define a class that inherits all the methods
and properties from another class
Syntax:
Class Child_class(Parent_class)
Example:
class Parent_class:
def display(a):
print(“new class”)
class Child_class(Parent_class):
o= Child_class()
o.display()
types of inheritance
1. Single
When one class inherits members of just one class.
2. Multiple
When one class inherits members of multiple classes
Syntax:
Class Base1:
Body of the class
Class Base2:
Body of the class
Example:
class Parent_class:
def display(a):
print(“new class”)
class Parent_class2:
def display2(a):
print(“new class”)
class Child_class(Parent_class, Parent_class2):
o= Child_class class()
o.display()
69
3. Multilevel
When there is inheritance at various levels
Syntax:
Class level1:
Body of the class
Class level2(level1):
Body of the class
Class level3(level2):
Body of the class
Example:
Class level1:
def display(a):
print(“new class”)
Class level2(level1):
Class level3(level2):
o= level3 ()
o.display()
4. Hierarchical
When two or more classes inherit members of one class.
Class Base:
Body of the class
Class child1(base):
Body of the class
Class child2(base):
Body of the class
Example:
class Parent_class:
def display(a):
print(“new class”)
class Child_class1(Parent_class):
class Child_class2(Parent_class):
o= Child_class1()
o.display()
o= Child_class2()
o.display2()
5. Hybrid
When there is a mix of any of the above types
70
9.3.7 Encapsulation
Encapsulation refers to the bundling of data, along with the methods that
operate on that data, into a single unit.
9.3.8 Polymorphism
Polymorphism is one of the OOPs feature that allows us to perform
a single action in different ways.
With polymorphism we can create multiple entities with same
name.
Example:
class newclass:
def display(a):
print(“new class”)
def display(a,b):
o=newclass()
o.display()
Questions:
Dir() function
9.4.1 what is dir() function ?
dir() is a powerful inbuilt function in Python3, which returns list of the
attributes and methods of any object
The dir() function returns all properties and methods of the specified
object, without the values.
This function will return all the properties and methods, even built-in
properties which are default for all object .
Syntax:
dir(object)
71
9.5 METHODS
Questions:
1. State and explain any 5 string functions.
2. State and explain any 5 tuple functions.
3. State and explain any 5 list functions.
4. State and explain any 5 dictionary functions.
73