Python Notes
Python Notes
To install Python software into our laptop or desktop, we need to visit their official website by typing
‘python.org’ in the web browser. The following screen as shown in Figure 1.4 will appear. Select
‘Downloads’ and then click on ‘Windows’ to see various versions of Python available.
The latest version of Python (during April of 2021) is Python 3.9.4. This version has again got two
variations, a 32-bit version and a 64-bit version. Depending upon our operating system, we can choose a
version. Nowadays most people use 64-bit operating system and hence we can use the 64-bit version of
Python. For Machine learning and Data Science related tasks, it is better to go for 64-bit version. Hence
click on ‘Download Windows installer (64-bit)’ . See Figure 1.5.
1
Figure 1.5: Selecting Windows installer to install Python.
This will download Windows installer by the name ‘python-3.9.4-amd64.exe’ file into our computer.
Double click on this file and the installer will run and display ‘Setup’ window. Go to the bottom of the
screen and select the check box at ‘Add Python 3.9 to PATH’. A tick mark will appear in that checkbox. Then
come up and click on ‘Install Now’. See Figure 1.6.
2
Figure 1.6: Starting screen of Installation of Python
Installation Progress bar will appear as shown in Figure 1.7 and we have to wait for a few minutes.
3
Figure 1.7: Installation of Python is going on.
After completion, ‘Setup was successful’ message can be seen. Click on ‘Close’ button as shown in Figure
1.8. This completes installation of Python in our System.
Along with basic Python software, we need to install additional packages developed by other companies.
These additional packages are nothing but additional libraries (or code) which can be imported and used in
our Python programs. We may require to install the following packages: numpy, pandas, xlrd, matplotlib
and seaborn. These packages can be installed by going to DOS prompt (or System prompt or command
prompt). To go to DOS prompt, we can Right click on Windows ‘Start’ button and then click on ‘Run’. Then
type ‘cmd’ or ‘command’ to go to System prompt. This is shown in Figure 1.9.
4
Figure 1.9: Going to DOS System prompt
Installing numpy
Python supports only single dimensional arrays. To create multi-dimensional
arrays, we need a special package called Numerical Python package or numpy. To
download and install this package, first we should go to System prompt and then
use ‘pip’ (Python Installation of Packages) command as shown below:
C:\> pip install numpy
‘pip’ program comes with Python software by default. When this command is given,
it searches the latest version of the numpy package on the Internet, downloads it
and installs it, as shown in Figure 1.10:
Installing pandas
pandas is a package used in data analysis. This package is mostly used by data
scientists and data analysts. To download and install this package, we should go to
System prompt and then use ‘pip’ (Python Installation of Packages) command as
shown below:
C:\> pip install pandas
5
This command downloads pandas package from the Internet and installs it, as
shown in Figure 1.11:
Installing xlrd
xlrd is a package that is useful to retrieve data from Microsoft Excel spreadsheet
files. Hence, it is useful in data analysis. To download and install this package, we
should go to System prompt and then use ‘pip’ (Python Installation of Packages)
command as shown below:
C:\> pip install xlrd
This command downloads xlrd package from the Internet and installs it, as shown
in Figure 1.12:
Installing matplotlib
matplotlib is another important package in Python that is useful to produce good
quality 2D graphics. It is mostly used for the purpose of showing data in the form
of graphs and also for designing electronic circuits, machinery parts, etc. To
download and install this package, we should go to System prompt and then use
‘pip’ (Python Installation of Packages) command as shown below:
C:\> pip install matplotlib
This command downloads the matplotlib package from the Internet and installs it
as shown in Figure 1.13:
6
Figure 1.13: Installation of matplotlib package
We can verify whether the installed packages are added to our Python software properly or not by
going into Python and typing the following command at Python prompt (triple greater than symbol) as:
>>> help(‘modules’)
For this purpose, first click on the Python IDLE Window pinned at the taskbar and then type the
preceding command as shown in the Figure 2.12.
It will display all the module names available currently in your Python software as shown in the
Figure 2.13. You can verify that your Python software now has the packages like: numpy, xlrd,
pandas, and matplotlib available as modules.
7
Figure 2.13: To verify installed packages in Python
When a programmer faces some doubt about how to use a particular feature of the Python language,
he can view the help. To get help, one can enter help mode by typing help() at Python prompt (i.e. >>>
prompt). We can see the help utility appearing as shown in Figure 2.14.
8
Figure 2.14: Entering Help Mode in Python
Now, we can type ‘modules’ to see which modules are available in Python. We can type ‘topics’ to know
about topics in Python. Let’s enter topics at the help prompt, as shown in Figure 2.15.
9
Figure 2.16: Getting Help on Functions
To get help on the print function, we can type ‘print’ at the help prompt, as shown in Figure 2.17.
To quit from the help mode, we should simply press the Enter button once again without typing
anything. A message appears that we are leaving the help mode and then we arrive at the Python
10
prompt, i.e. >>>. To exit the Python interpreter (or PVM), we should type either exit() or quit(), as
shown in Figure 2.18.
We can also view help without entering the help mode. Viewing help is possible at the Python prompt.
We can use the help() command and inside the parentheses, type the item name in single quotes. For
example, to get help on topics, we can type help (‘topics’) and to get help on the print function, we can
type help(‘print’), as shown in Figure 2.19:
11
Getting Python Documentation Help
Python developers have provided extensive description of all Python features in a document that is
called ‘Python documents’. This provides a great help for beginners and for professional programmers
to understand all the features of Python. To see Python documentation help, we should open the IDLE
window. Then select Help Python Docs, as shown in Figure 2.20:
At the left side frame, we see contents out of which the following are very useful for us:
12
The Python Tutorial
The Python Language Reference
The Python Standard Library
For example, click ‘The Python Standard Library’ to see the topic-wise comprehensive help on Python
Standard Library. We can click on the close button ( X ) to close this help window, as shown in Figure
2.22.
13
FUNDAMENTALS OF PYTHON
Python is a high level programming language that contains features of functional programming
language like C and object oriented programming language like Java.
FEATURES OF PYTHON
□□ Simple
Python is a simple programming language because it uses English like sentences in its programs.
□□ Easy to learn
Python uses very few keywords. Its programs use very simple structure.
□□ Open source
Python can be freely downloaded from www.python.org website. Its source code can be read,
modified and can be used in programs as desired by the programmers.
□□ Dynamically typed
In Python, we need not declare the variables. Depending on the value stored in the variable,
Python interpreter internally assumes the datatype.
□□ Platform independent
Hence, Python programs are not dependant on any computer with any operating system. We can
use Python on Unix, Linux, Windows, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, etc. almost
all operating systems. This will make Python an ideal programming language for any network or
Internet.
□□ Portable
When a program yields same result on any computer in the world, then it is called a portable
program. Python programs will give same result since they are platform independent.
14
An object is anything that exists physically in the real world. An object contains behavior. This
behavior is represented by its properties (or attributes) and actions. Properties are represented by
variables and actions are performed by methods. So, an object contains variables and methods.
A class represents common behavior of a group of objects. It also contains variables and methods.
But a class does not exist physically.
A class can be imagined as a model for creating objects. An object is an instance (physical form) of
a class.
□□ Interpreted
First, Python compiler translates the Python program into an intermediate code called byte code.
This byte code is then executed by PVM. Inside the PVM, an interpreter converts the byte code
instructions into machine code so that the processor will understand and run that machine code.
□□ Extensible
There are other flavors of Python where programs from other languages can be integrated into
Python. For example, Jython is useful to integrate Java code into Python programs and run on JVM
(Java Virtual Machine). Similarly IronPython is useful to integrate .NET programs and libraries into
Python programs and run on CLR (Common Language Runtime).
□□ Embeddable
Several applications are already developed in Python which can be integrated into other
programming languages like C, C++, Delphi, PHP, Java and .NET. It means programmers can use
these applications for their advantage in various software projects.
□□ Huge library
Python has a big library that contains modules which can be used on any Operating system.
□□ Scripting language
A scripting language uses an interpreter to translate the source code into machine code on the fly
(while running). Generally, scripting languages perform supporting tasks for a bigger application or
software. Python is considered as a scripting language as it is interpreted and it is used on Internet
to support other softwares.
□□ Database connectivity
A database represents software that stores and manipulates data. Python provides interfaces to
connect its programs to all major databases like Oracle, Sybase, SQL Server or MySql.
□□ Scalable
A program would be scalable if it could be moved to another Operating system or hardware and
take full advantage of the new environment in terms of performance.
15
□□ Batteries included
The huge library of Python contains several small applications (or small packages) which are
already developed and immediately available to programmers. These libraries are called ‘batteries
included’. Some interesting batteries or packages are given here:
To know the entire list of packages included in Python, one can visit:
https://www.pythonanywhere.com/batteries_included/
16
PVM
A Python program contains source code (first.py) that is first compiled by Python compiler to
produce byte code (first.pyc). This byte code is given to Python Virtual Machine (PVM) which
converts the byte code to machine code. This machine code is run by the processor and finally the
results are produced.
Python Virtual Machine (PVM) is a software that contains an interpreter that converts the byte
code into machine code.
PVM is most often called Python interpreter. The PVM of PyPy contains a compiler in addition to
the interpreter. This compiler is called Just In Time (JIT) compiler which is useful to speed up
execution of the Python program.
Memory allocation and deallocation are done by PVM during runtime. Entire memory is allocated
on heap.
We know that the actual memory (RAM) for any program is allocated by the underlying Operating
system. On the top of the Operating system, a raw memory allocator oversees whether enough
memory is available to it for storing the objects (ex: integers, strings, functions, lists, modules etc).
On the top of the raw memory allocator, there are several object-specific allocators operate on
the same heap. These memory allocators will implement different types of memory management
policies depending on the type of the objects. For example, an integer number should be stored in
memory in one way and a string should be stored in a different way. Similarly, when we deal with
tuples and dictionaries, they should be stored differently. These issues are taken care by object-
specific memory allocators.
Garbage collection
17
A module represents Python code that performs specific task. Garbage collector is a module in
Python that is useful to delete objects from memory which are not used in the program. The
module that represents the garbage collector is named as gc. Garbage collector in the simplest
way maintains a count for each object regarding how many times that object is referenced (or
used). When an object is referenced twice, its reference count will be 2. When an object has some
count, it is being used in the program and hence garbage collector will not remove it from
memory. When an object is found with a reference count 0, garbage collector will understand that
the object is not used by the program and hence it can be deleted from memory. Hence, the
memory allocated for that object is deallocated or freed.
Frozen Binaries
When a software is developed in Python, there are two ways to provide the software to the end
user. The first way is to provide the .pyc files to the user. The user will install PVM in his computer
and run the byte code instructions of the .pyc files.
The other way is to provide the .pyc files, PVM along with necessary Python library. In this
method, all the .pyc files, related Python library and PVM will be converted into a single
executable file (generally with .exe extension) so that the user can directly execute that file by
double clicking on it. In this way, converting the Python programs into true executables is called
frozen binaries. But frozen binaries will have more size than that of simple .pyc files since they
contain PVM and library files also.
For creating Frozen binaries, we need to use other party softwares. For example, py2exe is a
software that produces frozen binaries for Windows operating system. We can use pyinstaller for
UNIX or LINUX. Freeze is another program from Python organization to generate frozen binaries
for UNIX.
Running a Python program can be done from 3 environments: 1. Command line window 2. IDLE
graphics window 3. System prompt
18
LEARNING RESOURCE ON INTERNET
www.tutorialspoint.com
COMMENTS (2 types)
Docstrings
If we write strings inside “”” or ‘’’ and if these strings are written as first statements in a module,
function, class or a method, then these strings are called documentation strings or docstrings.
These docstrings are useful to create an API documentation file from a Python program. An API
(Application Programming Interface) documentation file is a text file or html file that contains
description of all the features of a software, language or a product.
DATATYPES
A datatype represents the type of data stored into a variable (or memory).
Built-in datatypes
□□ None Type
□□ Numeric types
□□ Sequences
□□ Sets
□□ Mappings
NOTE:
Binary numbers are represented by a prefix 0b or 0B. Ex: 0b10011001
Hexadecimal numbers are represented by a prefix 0x or 0X. Ex: 0X11f9c
Octal numbers are represented by a prefix 0o or 0O. Ex: 0o145.
19
bool type: represents any of the two boolean values, True or False.
Ex: a = 10>5 # here a is treated as bool type variable.
print(a) #displays True
NOTE:
1. To convert a float number into integer, we can use int() function. Ex: int(num)
2. To convert an integer into float, we can use float() function.
3. bin() converts a number into binary. Ex: bin(num)
4. oct() converts a number into octal.
5. hex() converts a number into hexadecimal.
STRINGS
str datatype: represents string datatype. A string is enclosed in single quotes or double quotes.
Ex: s1 = “Welcome”
s2 = ‘Welcome’
A string occupying multiple lines can be inserted into triple single quotes or triple double quotes.
Ex: s1 = ‘’’ This is a special training on
Python programming that
gives insights into Python language.
‘’’
To display a string with single quotes.
Ex: s2 = “””This is a book ‘on Core Python’ programming”””
We can find substring position in a string using find() method. It returns -1 if not found.
20
Ex: n = str.find(sub, 0, len(str))
We can count number of substrings in a string using count() method. Returns 0 if not found.
Ex: n = str.count(sub)
We can replace a string s1 with another string s2 in a main string using replace() method.
Ex: str.replace(s1, s2)
We can change the case of a string using upper(), lower(), title() methods.
Ex: str.upper()
CHARACTERS
There is no datatype to represent a single character in Python. Characters are part of str datatype.
Ex:
str = "Hello"
print(str[0])
H
H
e
l
l
o
bytes datatype: represents a group of positive integers in the range of 0 to 255 just like an array.
The elements of bytes type cannot be modified.
Ex: arr = [10, 20, 55, 100, 99]
x = bytes(arr)
for i in x:
print(i)
10
20
55
100
99
bytearray datatype: same as bytes type but its elements can be modified.
arr = [10,20,55,100,99]
x=bytearray(arr)
x[0]=11
x[1]=21
for i in x: print(i)
21
11
21
55
100
99
NOTE:
We can do only indexing in case of bytes or bytearray datatypes. We cannot do slicing or
repetitions.
LISTS
A list is similar to an array that can store a group of elements. A list can store different types of
elements and can grow dynamically in memory. A list is represented by square braces [ ]. List
elements can be modified.
Ex:
lst = [10, 20, 'Ajay', -99.5]
print(lst[2])
Ajay
NOTE:
Indexing, slicing and repetition are possible on lists.
print(lst[1])
20
print(lst[-3:-1])
[20, 'Ajay']
lst = lst*2
print(lst)
[10, 20, 'Ajay', -99.5, 10, 20, 'Ajay', -99.5]
We can use len() function to find the no. of elements in the list.
n = len(lst) -> 4
remove() will remove a particular element. clear() wil delete all elements from the list.
lst.remove(‘Ajay’)
lst.clear()
Example Description
lst.index(x) Returns the first occurrence of x in lst.
lst.count(x) Returns the number of occurrences of x in lst.
lst.insert(i, x) Inserts x into lst in the position specified by i.
lst.copy() Copies all elements of lst into a new list and returns it.
lst.extend(lst1) Appends lst1 to lst.
lst.sort() Sorts all elements into ascending order.
lst.sort(reverse=True) Sorts all elements into descending order.
lst.reverse() Reverses the sequence of elements.
TUPLES
A tuple is similar to a list but its elements cannot be modified. A tuple is represented by
parentheses ( ).
Indexing, slicing and repetition are possible on tuples also.
Ex:
tpl=( ) # creates an empty tuple
tpl=(10, ) # with only one element – comma needed after the element
print(tpl[0:2])
(10, 20)
tpl = tpl*2
print(tpl)
(10, 20, -30, 'Raju', 10, 20, -30, 'Raju')
NOTE: len(), count(), index(), max(), min() functions are same in case of tuples also.
We cannot use append(), extend(), insert(), remove(), clear() methods on tuples.
23
RANGE DATATYPE
range represents a sequence of numbers. The numbers in the range cannot be modified.
Generally, range is used to repeat a for loop for a specified number of times.
print(r[0]) -> 0
for i in r: print(i)
0
1
2
3
4
0
2
4
6
8
50
48
46
44
42
SETS
A set datatype represents unordered collection of elements. A set does not accept duplicate
elements where as a list accepts duplicate elements. A set is written using curly braces { }. Its
elements can be modified.
Ex:
s = {1, 2, 3, "Vijaya"}
print(s)
{1, 2, 3, 'Vijaya'}
NOTE: Indexing, slicing and repetition are not allowed in case of a set.
24
To add elements into a set, we should use update() method as:
s.update([4, 5])
print(s)
{1, 2, 3, 4, 5, 'Vijaya'}
A frozenset datatype is same as set type but its elements cannot be modified.
Ex:
s = {1, 2, -1, 'Akhil'} -> this is a set
s1 = frozenset(s) -> convert it into frozenset
for i in s1: print(i)
1
2
Akhil
-1
MAPPING DATATYPES
A map indicates elements in the form of key – value pairs. When key is given, we can retrieve the
associated value. A dict datatype (dictionary) is an example for a ‘map’.
keys() method gives keys and values() method returns values from a dictionary.
k = d.keys()
for i in k: print(i)
10
11
12
kamal
Subbu
Sanjana
d[10] = ‘Kamal’
d[11] = ‘Pranav’
We can update the value of a key, as: d[key] = newvalue.
Ex: d[10] = ‘Subhash’
The datatype of the variable is decided depending on the value assigned. To know the datatype of
the variable, we can use type() function.
Ex:
x = 15 #int type
print(type(x))
<class 'int'>
x = 'A' #str type
print(type(x))
<class 'str'>
x = 1.5 #float tye
print(type(x))
<class 'float'>
x = "Hello" #str type
print(type(x))
<class 'str'>
x = [1,2,3,4]
print(type(x))
<class 'list'>
x = (1,2,3,4)
print(type(x))
<class 'tuple'>
x = {1,2,3,4}
print(type(x))
<class 'set'>
26
Literals in Python
User-defined datatypes
The datatypes which are created by the programmers are called ‘user-defined’ datatypes. For
example, an array, a class, or a module is user-defined datatypes.
Constants in Python
A constant is similar to variable but its value cannot be modified or changed in the course of the
program execution. For example, pi value 22/7 is a constant. Constants are written using caps as
PI.
An identifier is a name that is given to a variable or function or class etc. Identifiers can include
letters, numbers, and the underscore character ( _ ). They should always start with a nonnumeric
character. Special symbols such as ?, #, $, %, and @ are not allowed in identifiers. Some examples
for identifiers are salaray, name11, gross_income, etc.
Reserved words are the words which are already reserved for some particular purpose in the
Python language. The names of these reserved words should not be used as identifiers. The
following are the reserved words available in Python:
OPERATORS
Arithmetic operators
27
They perform basic arithmetic operations.
a=13, b = 5
Operator Meaning Example Result
+ Addition operator. a+b 18
Assignment operators
To assign right side value to a left side variable.
Ex:
a=b=c=5
print(a,b,c)
555
a,b,c=1,2,'Hello'
print(a,b,c)
1 2 Hello
x = [10,11,12]
a,b,c = 1.5, x, -1
print(a,b,c)
1.5 [10, 11, 12] -1
Unary minus operator
Converts +ve value into negative and vice versa.
Relational operators
Relational operators are used to compare two quantities. They return either True or False (bool
datatype).
28
Ex:
a, b = 1, 2
print(a>b)
False
Ex:
1<2<3<4 will give True
1<2>3<4 will give False
Logical operators
Logical operators are useful to construct compound conditions. A compound condition is a
combination of more than one simple condition. 0 is False, any other number is True.
X=1, y=2
Operator Example Meaning Result
and x and y And operator. If x is False, it returns x, otherwise 2
it returns y.
or x or y Or operator. If x is False, it returns y, otherwise it 1
returns x.
not not x Not operator. If x is False, it returns True. If x is False
True it returns False.
Ex:
x=1; y=2; z=3
if(x<y or y>z):
print('Yes')
else:
print('No') -> displays Yes
Boolean operators
Boolean operators act upon ‘bool’ type values and they provide ‘bool’ type result. So the result
will be again either True or False.
x = True, y = False
Operator Example Meaning Result
and x and y Boolean and operator. If both x and y are True, False
then it returns True, otherwise False.
or x or y Boolean or operator. If either x or y is True, then True
it returns True, else False.
not not x Boolean not operator. If x is True, it returns False
False, else True.
29
INPUT AND OUTPUT
Example Output
print() Blank line
print(“Hai”) Hai
print(“This is the \nfirst line”) This is the
first line
print(“This is the \\nfirst line”) This is the \nfirst line
print(‘Hai’*3) HaiHaiHai
print(‘City=’, “Hyderabad”) City= Hyderabad
print(‘City=’+”Hyderabad”) City=Hyderabad
print(a, b) 12
print(a, b, sep=”,”) 1,2
print(a, b, sep=’ ---- ‘) 1-----2
print("Hello") Hello
print("Dear") Dear
print("Hello", end='') HelloDear
print("Dear", end='')
a=2
print('You typed ', a, 'as input') You typed 2 as input
%i, %f, %c, %s can be used as format strings.
name='Linda'; sal=12000.50
print('Hai', name, 'Your salary is', sal) Hai Linda Your salary is 12000.5
print('Hai %s, Your salary is %.2f' % (name, sal)) Hai Linda, Your salary is 12000.50
print('Hai {}, Your salary is {}'.format(name, sal)) Hai Linda, Your salary is 12000.5
print('Hai {0}, Your salary is {1}'.format(name, sal)) Hai Linda, Your salary is 12000.5
print('Hai {1}, Your salary is {0}'.format(name, sal)) Hai 12000.5, Your salary is Linda
Example
str = input()
str = input(‘Enter your name= ‘)
a = int(input(‘Enter int number: ‘)
a = float(input(‘Enter a float number: ‘)
a,b,c = [int(x) for x in input("Enter three numbers: ").split()]
a,b,c = [int(x) for x in input('Enter a,b,c: ').split(',')]
a,b,c = [x for x in input('Enter 3 strings: ').split(',')]
lst = [float(x) for x in input().split(',')]
lst = eval(input(‘Enter a list: ‘))
30
PROGRAMS
1. Enter id number, name and salary one by one and display them.
2. Enter 3 numbers and find their sum and average.
3. Enter the radius of a circle and find the area.
4. Enter a character and display it.
5. Enter two strings and display the total string.
6. Enter a number and display its cube value.
7. Sort a group of strings into ascending order.
8. Enter a list of different elements and display them.
31
CONTROL STATEMENTS
□□ if statement
□□ if…else statement
□□ if…elif…else statement
□□ while loop
□□ for loop
□□ break statement
□□ continue statement
□□ pass statement
□□ return statement
if statement
executes statements based on a condition.
if condition:
statements
if…else statement
executes statements1 else statements2 based on a condition.
if condition:
statements1
else:
statements2
PROGRAMS
9. Test whether a given number is even or odd.
if…elif…else statement
executes statements depending on multiple conditions.
if condition1:
statements1
elif condition2:
statements2
elif condition3:
statements3
else:
statements4
PROGRAMS
10. Test whether a given number is even or odd or zero.
while loop
executes statements as long as the condition is True.
while condition:
32
statements
PROGRAMS
11. Display numbers from 1 to 10.
12. Display even numbers between m and n.
33
for loop
to iterate over the elements of a sequence like string, list, tuple, set, range, etc.
PROGRAMS
13. Display numbers from 100 to 110.
14. Display even numbers from 100 to 110.
15. Display the individual letters of a string.
16. Find sum of list of numbers.
17. Display required multiplication table.
else suit
else can be used with for loop or while loop. The statements in the else part are always executed.
while condition:
statements
else:
statements
PROGRAMS
18. Enter a number and find out if it exists in a list.
break statement
to come out of a for loop or while loop.
continue statement
to continue the next iteration of a loop.
PROGRAMS
19. To break a loop of 1 to 10 at 5.
20. Do not display a loop from 5 onwards.
pass statement
does nothing. It is used in ‘if statement’ or a ‘loop’ to represent no operation.
PROGRAMS
21. Retrieve only negative numbers from a list.
return statement
to return result from a function.
34
PROGRAMS
22. A function to return the sum of two numbers from a function.
assert statement
to check if a particular condition is fulfilled or not. If the condition fails, it displays the assert
statement and also raises AssertionError.
PROGRAMS
23. Check if the user entered a number greater than 10 or not.
The arguments passed to a Python program at command prompt. They are stored in the form of a
list in argv defined in ‘sys’ module.
len(sys.argv) gives number of command line args.
sys.argv is a list that contains all command line args.
sys.argv[0] contains the program name.
PROGRAMS
24. Display the no. of command line args and their names.
25. Enter a group of numbers at command line and find their sum and average.
35
FUNCTIONS
Contains a group of statements to perform a particular task. A function written inside a class is a
‘method’. A method is called as: obj.methodname() or class.methodname().
36
PROGRAMS
26. A function to find sum of two numbers.
A function can return more than one value. When several values are returned, they are stored
into a tuple and then returned.
PROGRAMS
27. A function to return result of addition and subtraction of two numbers.
28. A function to return results of addition, subtraction, multiplication and division.
It is possible to send a group of strings or numbers in the form of a list to a function and do any
operation inside the function.
PROGRAMS
29. Enter a group of numbers from keyboard and sort them using a function.
PROGRAMS
30. Create a global variable and local variable and display their values.
When local variable and global variable have same name, we can use globals() function to retrieve
the global variable value inside the function. Ex: globals()[‘var’]
PROGRAMS
31. Use globals() to retrieve the global variable inside a function.
PROGRAMS
32. Assign a function to a variable.
33. Define message() function inside display() function.
34. Pass message() function to display() function as parameter.
35. Return message() function from display() function.
Recursive functions
A function calling itself repeatedly.
37
PROGRAMS
36. Using recursion, calculate factorial value of a given number.
When a function is defined, it may have some parameters. These parameters are useful to receive
values from outside of the function. They are called ‘formal arguments’. When we call the
function, we should pass data or values to the function. These values are called ‘actual
arguments’. In the following code, ‘a’ and ‘b’ are formal arguments and ‘x’ and ‘y’ are actual
arguments.
□□ Positional arguments
□□ Keyword arguments
□□ Default arguments
□□ Variable length arguments
Positional arguments
These are the arguments passed to a function in correct positional order. Here, the number of
arguments and their positions in the function definition should match exactly with the number
and position of the argument in the function call
Keyword arguments
Keyword arguments are arguments that identify the parameters by their names.
Default arguments
We can mention some default value for the function parameters in the definition.
A variable length argument is an argument that can accept any number of values. The variable
length argument is written with a ‘ * ‘ symbol before it in the function definition, as:
Here, ‘farg’ is the formal argument and ‘*args’ represents variable length argument. We can pass
1 or more values to this ‘*args’ and it will store them all in a tuple.
Function decorators
A decorator is a function that accepts a function as parameter and returns a function. A decorator
takes the result of a function, modifies the result and returns it. Thus decorators are useful to
perform some additional processing required by a function.
2. We should define a function inside the decorator function. This function actually modifies or
decorates the value of the function passed to the decorator function.
def decor(fun):
def inner():
value = fun() # access value returned by fun()
return value+2 # increase the value by 2
return inner # return the inner function
3. Return the inner function that has processed or decorated the value. In our example, in the last
statement, we were returning inner() function using return statement. With this, the decorator is
completed.
The next question is how to use the decorator. Once a decorator is created, it can be used for any
function to decorate or process its result. For example, let us take num() function that returns
some value, e.g. 10.
def num():
return 10
Now, we should call decor() function by passing num() function name as:
result_fun = decor(num)
So, ‘result_fun’ indicates the resultant function. Call this function and print the result, as:
39
print(result_fun())
PROGRAMS
37. Write a decorator function to increase the value by 2.
Generators
Generators are functions that return a sequence of numbers. A generator function is written like
an ordinary function but it uses ‘yield’ statement. This statement is useful to return the value.
PROGRAMS
38. Create a generator object with numbers from 5 to 10.
A module represents a group of classes, methods, functions and variables. In Python, we have
several built-in modules like sys, io, time etc. Just like these modules, we can also create our own
modules and use them whenever we need them. Once a module is created, any programmer in
the project team can reuse that module. Hence, modules will make software development easy
and faster.
PROGRAMS
39. Create ‘mymodule’ with addition and subtraction functions and use them in another program.
When a program is executed in Python, there is a special variable internally created by the name
‘ name ’. This variable stores information regarding whether the program is executed as an
individual program or as a module. When the program is executed directly, the Python interpreter
stores the value ‘ main ’ into this variable. When the program is imported as a module into
another program, then Python interpreter stores the module name into this variable. Thus, by
observing the value of the variable ‘ name ’, we can understand how the program is executed.
PROGRAMS
40. Create ‘one’ module with display() function. Find out how it is executed.
A package is a folder that contains a group of modules. To distinguish between a normal folder
and package, we need to store an empty file by the name ‘ init .py’ in the package folder.
A Library is a group of packages. The main advantage of libraries and packages is to reuse their
contents by any programmer in different projects.
40
LAMBDAS OR ANONYMOUS FUNCTIONS
A function without a name is called ‘anonymous function’. So far, the functions we wrote were defined
using the keyword ‘def’. But anonymous functions are not defined using ‘def’. They are defined using the
keyword lambda and hence they are also called ‘Lambda functions’. Let us take a normal function that
returns square of a given value.
def square(x):
return x*x
lambda x: x*x
Observe the keyword ‘lambda’. This represents that an anonymous function is being created. After that we
have written an argument of the function, i.e. ‘x’. Then colon ( : ) represents the beginning of the function
that contains an expression x * x. Please observe that we did not use any name for the function here. So,
the format of lambda functions is:
Normally, if a function returns some value, we assign that value to a variable, as:
y = square(5)
But, lambda functions return a function and hence they should be assigned to a function, as:
f = lambda x: x*x
Here, ‘f’ is the function name to which the lambda expression is assigned. Now, if we call the function f(),
as:
value = f(5)
PROGRAMS
41. Create a lambda function to find square value of a number.
42. Write a lambda to test whether a given number is even or not.
The filter() function is useful to filter out the elements of a sequence depending on the result of a function.
We should supply a function and a sequence to the filter() function as:
filter(function, sequence)
Here, the ‘function’ represents a function name that may return either True or False; and ‘sequence’
represents a list, string or tuple.
PROGRAMS
43. Create a lambda that returns even numbers from a list of numbers.
41
Using lambdas with map() function
The map() function is similar to filter() function but it acts on each element of the sequence and perhaps
changes the elements. The format of map() function is:
map(function, sequence)
The ‘function’ performs a specified operation on all the elements of the sequence and the modified
elements are returned which can be stored in another sequence.
PROGRAMS
44. Create a lambda that returns squares of all elements in a list.
reduce() function reduces a sequence of elements to a single value by processing the elements according
to a function supplied. The reduce() function is used in the format:
reduce(function, sequence)
PROGRAMS
45. Create a lambda function to calculate products of elements of a list.
ARRAYS
An array is an object that stores a group of elements (or values) of same datatype. Array elements
should be of same datatype. Arrays can increase or decrease their size dynamically.
NOTE: We can use for loops to display the individual elements of the array.
A 1D array contains one row or one column of elements. For example, the marks of a student in 5
subjects.
Creating arrays in numpy can be done in several ways. Some of the important ways are:
42
□□ Using array() function
□□ Using linspace() function
□□ Using logspace() function
□□ Using arange() function
□□ Using zeros() and ones() functions.
To create a 1D array, we should use array() method that accepts list of elements.
Ex: arr = numpy.array([1,2,3,4,5])
PROGRAMS
46. Create different types of 1D arrays using numpy.
linspace() function is used to create an array with evenly spaced points between a starting point
and ending point. The form of the linspace() is:
linspace(start, stop, n)
‘start’ represents the starting element and ‘stop’ represents the ending element. ‘n’ is an integer
that represents the number of parts the elements should be divided. If ‘n’ is omitted, then it is
taken as 50. Let us take one example to understand this.
a = linspace(0, 10, 5)
In the above statement, we are creating an array ‘a’ with starting element 0 and ending element
10. This range is divided into 5 equal parts and hence the points will be 0, 2.5, 5, 7.5 and 10. These
elements are stored into ‘a’. Please remember the starting and ending elements 0 and 10 are
included.
PROGRAMS
47. Create an array with 5 equal points using linspace().
logspace() function is similar to linspace(). The linspace() produces the evenly spaced points.
Similarly, logspace() produces evenly spaced points on a logarithmically spaced scale. logspace is
used in the following format:
logspace(start, stop, n)
The logspace() starts at a value which is 10 power of ‘start’ and ends at a value which is 10 power
of ‘stop’. If ‘n’ is not specified, then its value is taken as 50. For example, if we write:
a = logspace(1, 4, 5)
This function represents values starting from 101 to 104 . These values are divided into 5 equal
43
points and those points are stored into the array ‘a’.
PROGRAMS
48. A program to create an array using logspace().
The arange() function in numpy is same as range() function in Python. The arange() function is
used in the following format:
This creates an array with a group of elements from ‘start’ to one element prior to ‘stop’ in steps
of ‘stepsize’. If the ‘stepsize’ is omitted, then it is taken as 1. If the ‘start’ is omitted, then it is
taken as 0. For example,
arange(10)
arange(5, 10, 2)
PROGRAMS
We can use zeros() function to create an array with all zeros. The ones() function is useful to
create an array with all 1s. They are written in the following format:
zeros(n, datatype)
ones(n, datatype)
where ‘n’ represents the number of elements. we can eliminate the ‘datatype’ argument. If we do
not specify the ‘datatype’, then the default datatype used by numpy is ‘float’. See the examples:
zeros(5)
This will create an array with 5 elements all are zeros, as: [ 0. 0. 0. 0. 0. ]. If we want this
array in integer format, we can use ‘int’ as datatype, as:
zeros(5, int)
If we use ones() function, it will create an array with all elements 1. For example,
44
ones(5, float)
Taking an array as an object, we can perform basic operations like +, -, *, /, // and % operations on
each element.
Ex:
import numpy
arr = numpy.array([10, 20, 30])
arr+5
Ex:
numpy.sort(arr)
numpy.max(arr)
numpy.sqrt(arr)
b=a
This is a simple assignment that does not make any new copy of the array ‘a’. It means, ‘b’ is not a
new array and memory is not allocated to ‘b’. Also, elements from ‘a’ are not copied into ‘b’ since
45
there is no memory for ‘b’. Then how to understand this assignment statement? We should
understand that we are giving a new name ‘b’ to the same array referred by ‘a’. It means the
names ‘a’ and ‘b’ are referencing same array. This is called ‘aliasing’.
‘Aliasing’ is not ‘copying’. Aliasing means giving another name to the existing object. Hence, any
modifications to the alias object will reflect in the existing object and vice versa.
We can create another array that is same as an existing array. This is done by view() method. This
method creates a copy of an existing array such that the new array will also contain the same
elements found in the existing array. The original array and the newly created arrays will share
different memory locations. If the newly created array is modified, the original array will also be
modified since the elements in both the arrays will be like mirror images.
Viewing is nothing but copying only. But it is called ‘shallow copying’ as the elements in the view
when modified will also modify the elements in the original array. So, both the arrays will act as
one and the same. Suppose we want both the arrays to be independent and modifying one array
should not affect another array, we should go for ‘deep copying’. This is done with the help of
copy() method. This method makes a complete copy of an existing array and its elements. When
the newly created array is modified, it will not affect the existing array or vice versa. There will not
be any connection between the elements of the two arrays.
PROGRAMS
50. Create a 1D array using arange() and then create another array by alias, view and copy.
Ex:
import numpy as np
arr = np.array([10, 20, 30, 40, 50, 90])
arr[1] -> 20
print(arr[1:5])
[20 30 40 50]
arr[1:5:2]
array([20, 40])
arr[:5:]
array([10, 20, 30, 40, 50])
arr[::]
46
array([10, 20, 30, 40, 50, 90])
arr[0::2]
array([10, 30, 50])
arr[5:0:-1]
array([90, 50, 40, 30, 20])
Attributes of an array
Numpy’s array class is called ndarray. It is also known by alias name array. Let us remember that
there is another class ‘array’ in Python that is different from numpy’s ‘array’ class. This class
contains the following important attributes (or variables):
ndim
‘ndim’ represents the number of dimensions or axes of the array. The number of dimensions is
also referred to as ‘rank’. For a single dimensional array, it is 1 and for a two dimensional array, it
is 2. See the examples:
shape
‘shape’ gives the shape of an array. The shape is a tuple listing the number of elements along each
dimension. A dimension is called an axis. For a 1D array, shape gives the number of elements in
the row. For a 2D array, it specifies the number of rows and columns in each row. We can also
change the shape using ‘shape’ attribute. See the examples:
arr1 = array([1,2,3,4,5])
print(arr1.shape) displays (5,) # no. of elements
size
gives the total number of elements in the array. For example,
arr1 = array([1,2,3,4,5])
print(arr1.size) displays 5
47
arr2 = array([[1,2,3], [4,5,6]])
print(arr2.size) displays 6
itemsize
This gives the memory size of the array element in bytes. As we know, 1 byte is equal to 8 bits. For
example,
arr1 = array([1,2,3,4,5])
print(arr1.itemsize) displays 4
arr2 = array([1.1,2.1,3.5,4,5.0])
print(arr2.itemsize) displays 8
dtype
This attribute gives the datatype of the elements in the array. For example,
nbytes
gives the total number of bytes occupied by an array. The total number of bytes = size of the
array * item size of each element in the array. For example,
Apart from the attributes discussed in the preceding sections, we can use reshape() and flatten()
methods which are useful to convert the 1D array into a 2D array and vice versa.
reshape()
This method is useful to change the shape of an array. The new array should have the same
number of elements as in the original array. For example,
flatten()
This method is useful to return a copy of the array collapsed into one dimension. For example, let
us take a 2D array as:
arr1 = array([[1,2,3],[4,5,6]])
print(arr1) displays the following:
[[1 2 3]
[4 5 6]]
By using flatten() method, we can convert this array into 1D array, as:
arr1 = arr1.flatten()
print(arr1) displays the following:
[1 2 3 4 5 6]
They represent more than one row and more than one column of elements. For example, marks
obtained by a group of students each in five subjects.
To create a 2D array, we can use array() method that contains a list with lists.
PROGRAMS
51. Create and display a 2D array using array() method.
The ones() function is useful to create a 2D array with several rows and columns where all the
elements will be taken as 1. The format of this function is:
Here, ‘r’ represents the number of rows and ‘c’ represents the number of columns. ‘dtype’
represents the datatype of the elements in the array. For example,
49
a = ones((3, 4), float)
will create a 2D array with 3 rows and 4 columns and the datatype is taken as float. If ‘dtype’ is
omitted, then the default datatype taken will be ‘float’. Now, if we display ‘a’, we can see the
array as:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
The decimal point after each element represents that the elements are float type.
Just like ones() function, we can also use zeros() function to create a 2D array with elements filled
with zeros. Suppose, we write:
b = zeros((3,4), int)
Then a 2D array with 2 rows and 4 columns will be created where all elements will be 0s, as shown
below:
[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
eye() function
The eye() function creates a 2D array and fills the elements in the diagonal with 1s. The general
format of using this function is:
eye(n, dtype=datatype)
This will create an array with ‘n’ rows and ‘n’ columns. The default datatype is ‘float’. For example,
eye(3) will create a 3x3 array and fills the diagonal elements with 1s as shown below:
a = eye(3)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Ex:
import numpy as np
arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
arr[0] gives 0th row -> [1,2,3]
arr[1] gives 1st row -> [4,5,6]
arr[0,1] gives 0th row, 1st column element -> 2
arr[2,1] gives 2nd row, 1st column element -> 8
50
a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
a
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
a[0:2, 0:3] -> 0th row to 1st row, 0th column to 2nd column
array([[1, 2, 3],
[5, 6, 7]])
a[1:3, 2:] -> 1th row to 2nd row, 2nd column to last column
array([[ 7, 8],
[11, 12]])
MATRICES IN NUMPY
Ex:
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
m = np.matrix(a)
m
matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
We can find biggest and smallest elements in the matrix using max() and min() methods.
b = m.max()
print(b)
9
s = m.min()
print(s)
1
We can find sum and average of elements using sum() and mean() methods.
sum = m.sum()
print(sum)
45
51
avg = m.mean()
print(avg)
5.0
We can sort the elements into ascending order using sort() method.
arr = np.array([[3,4,2], [1,2,9]])
m = np.matrix(arr)
m
matrix([[3, 4, 2],
[1, 2, 9]])
Matrix addition, subtraction, multiplication, division can be done by using +, -, * and / operators.
(DO NOT USE IDLE)
PROGRAMS
52. Do matrix multiplication and division.
53. Accept matrix from keyboard as a string and display its transpose.
54. Rewrite the above program to accept the matrix in matrix form.
NESTED LISTS
A list within another list is called a nested list. We know that a list contains several elements.
When we take a list as an element in another list, then that list is called a nested list. For example,
we have two lists ‘a’ and ‘b’ as:
a = [80, 90]
b = [10, 20, 30, a]
Observe that the list ‘a’ is inserted as an element in the list ‘b’ and hence ‘a’ is called a nested list.
Let us display the elements of ‘b’, now.
print(b)
52
[10, 20, 30, [80, 90]]
The last element [80, 90] represents a nested list. So, ‘b’ has 4 elements and they are:
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = [80, 90]
So, b[3] represents the nested list and if we want to display its elements separately, we can use a
for loop as:
for x in b[3]:
print(x)
PROGRAMS
55. Store names and marks as nested list. When a name is given, display marks.
LIST COMPREHENSIONS
List comprehensions represent creation of new lists from an iterable object (like a list, set, tuple,
dictionary or range) that satisfy a given condition. List comprehensions contain very compact code
usually a single statement that performs the task.
Example : We want to create a list with squares of integers from 1 to 10. We can write code as:
The preceding code will create ‘squares’ list with the elements as shown below:
This is called list comprehension. From this, we can understand that a list comprehension consists
of square braces containing an expression (i.e. x**2). After the expression, a for loop and then
zero or more if statements can be written. See the syntax:
Observe the square braces around these statements. They indicate that a list will be returned as a
result of the list comprehension.
53
NOTE: It is possible to do list comprehension with tuples also.
PROGRAMS
# 3.area of a circle - v1
r = float(input('Enter radius: '))
PI = 22/7
area = PI*r**2
print('Area= ', area)
54
'''
# area of a circle - v2
import math
r = float(input('Enter radius: '))
area = math.pi*r*r
print('Area= ', area)
'''
# 5. joining strings
str1, str2 = input('Enter two strings: ').split(',')
print("Total string: "+str1+str2)
# 6.cube value
num = float(input('Enter a number: '))
print('Cube= ', num**3)
lst.sort()
for i in lst:
print(i)
55
# 11.display numbers from 1 to 10
x=1
while(x<=10):
print(x)
x+=1
print("End")
56
else:
print('Not found')
57
print('Program name= ', sys.argv[0])
# 26.function definition
def sum(a, b) :
""" to find sum of two numbers """
c = a + b
print('Sum= ', c)
# call the function
sum(5, 10)
# call again
sum('Hello', 'Dear')
# 27.function definition
def sum_sub(a, b) :
""" to find result of addition
and subtraction """
c = a + b
d = a- b
return c, d
# call the function
c, d = sum_sub(5, 10)
print("Results = {} and {}".format(c, d))
58
# take a group of numbers from keyboard
print('Enter numbers: ')
lst = [float(x) for x in input().split(',')]
# call the function
sortnum(lst)
59
return 'How are U?'
return message
# call display() function and it returns message() function
# in the following code, var refers to the name: message.
var = display()
print(var())
# 36.recursive function
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result
n = int(input('Enter number: '))
print('Factorial = ', factorial(n))
60
# use mymodule.
import mymodule
x, y = [int(x) for x in input('Enter two nos: ').split()]
mymodule.add(x,y)
mymodule.sub(x,y)
61
arr4 = numpy.array(['anil', 'gopal', 'vikas'])
print(arr4)
# 52.matrix operations
62
import numpy as np
a = np.matrix([[1,2],[3,4]])
b = np.matrix([[2,2],[4,4]])
c = a*b
print(c)
d = a/2
print(d)
# 53.finding transpose
import numpy
r,c = [int(a) for a in input('How many rows cols? ').split(' ')]
str = input('Enter elements:\n')
m = numpy.matrix(str)
x = numpy.reshape(m, (r,c))
print('original\n', x)
print('transpose\n', x.transpose())
print('Enter elements:')
for i in range(r): # enter one row at a time
arr[i]= [float(x) for x in input().split(' ')]
m = numpy.matrix(arr)
print('original\n', m)
print('transpose\n', m.transpose())
print(evens1)
print(evens2)
63
x = [10, 20, 30]
y = [40, 50, 60]
# without using list comprehension
z = []
for i in range(len(x)):
z.append(x[i]+y[i])
print(z)
# now using list comprehension
z = [x[i]+y[i] for i in range(len(x))]
print(z)
# 59.to retrieve only the first letter of each word in the list
words = ['Apple', 'Grapes', 'Banana', 'Orange']
# without using list comprehension
lst = []
for i in words:
lst.append(i[0])
print(lst)
# now using list comprehension
lst = [i[0] for i in words]
print(lst)
64