Audishankara Python Material
Audishankara Python Material
[18CS601]
LECTURE NOTES
SYLLABUS
PYTHON PROGRAMMING
B. Tech VI Semester : Computer Science & Engineering
Course code Category Hours/week Credits Maximum Marks
18CS601 Core L T P C CIA SEE TOTAL
3 0 0 3 30 70 100
Contact Classes:60 Tutorial Classes: 0 Practical Classes: 0 Total Classes:60
OBJECTIVES:
The course should enable the students to:
1. The course is designed to provide Basic knowledge of Python.
2. Python programming is intended for software engineers, system analysts, program managers.
3. User support personnel who wish to learn the Python programming language.
Web References:
1. Online Version www.greenteapress.com/thinkpython2.pdf.
2. How to think like a computer Scientist, by Brad Miller and David Ranum. Online Version
www.interactivepython.org/runstone/static/thinkscpy/index.html.
3. https://realpython.com/python3-o bject-oriented-programming/
4. https://python. swaroopch.com/ oop.html
5. https://python-textbok.readthedocs.io/en/1.0/0bject_ Oriented_Programming.html
6. https://www.programiz.com/python-programming/
Outcomes:
At the end of the course students able to
1. Implement a given algorithm as a computer program in Python.
2. Adapt and combine standard algorithms to solve a given problem
3. Adequately use standard programming constructs: repetition, selection, functions, Composition,
modules, aggregated data (arrays, lists, etc.). Explain what a given program in Python does.
Identify and repair coding errors in a program.
4. Use library software for (e.g.) building a graphical user interface, web application, or
mathematical software.
UNIT-I
INTRODUCTION TO PYTHON & EXPRESSIONS
Introduction to Python: Why to Learn Python, Difference between C and Python, Python Environment
variables, Procedure for execution of Python program Values, Data Types and Expressions: Python
Identifiers, Reserved words, Lines and Indentation, Command Line arguments, Data types: Python
Numbers, Python Strings, Python Lists, Python Dictionary, Data type conversion. Variables, Statement in
Python, Data type conversions
INTRODUCTION TO PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991. It is used for:
➢ mathematics,
➢ system scripting.
Why Python?
➢ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
➢ Python has a simple syntax similar to the English language.
➢ Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
➢ Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
➢ Python can be treated in a procedural way, an object-oriented way or a functional way.
FEATURES OF PYTHON
➢ Easy to Learn and Use: Python is easy to learn and use. It is developer-friendly and
high level programming language.
➢ Free and Open Source: Python language is freely available at official web address. The
source-code is also available. Therefore it is open source.
Python Architecture:
Applications of python
Tkinter or Tk
wxWidgetM
Kivy (used for writing multitouch applications )
PyQt or Pyside
3) Console-based Application
➢ Console-based applications run from the command-line or shell. These applications are
computer program which are used commands to execute.
➢ This kind of application was more popular in the old generation of computers.
➢ Python can develop this kind of application very effectively. It is famous for having
REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for
the command-line applications.
➢ Python provides many free library or module which helps to build the command-line apps.
➢ It helps to parse argument and create console help text out-of-the-box. There are also
advance libraries that can develop independent console apps.
➢ Buildbot and Apache Gumps are used for automated continuous compilation and testing.
➢ Python language is the most suitable language for Artificial intelligence or machine
learning.
➢ It consists of many scientific and mathematical libraries, which makes easy to solve
complex calculations.
➢ Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy,
Scikit-learn, etc.
➢ If you have some basic knowledge of Python, you need to import libraries on the top of
the code. Few popular frameworks of machine libraries are given below.
SciPy
Scikit-learn
NumPy
Pandas
Matplotlib
6) Business Applications
➢ Business Applications differ from standard applications. E-commerce and ERP are an
example of a business application. This kind of application requires extensively,
scalability and readability, and Python provides all these features.
Gstreamer
Pyglet
QT Phonon
8) 3D CAD Applications
➢ The CAD (Computer-aided design) is used to design engineering related architecture. It is
used to develop the 3D representation of a part of a system. Python can create a 3D CAD
application by using the following functionalities.
Fandango (Popular )
CAMVOX
HeeksCNC
AnyCAD
RCAM
9) Enterprise Applications
➢ Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
OpenCV
Pillow
SimpleITK
➢ In this topic, we have described all types of applications where Python plays an essential
role in the development of these applications. In the next tutorial, we will learn more
concepts about Python.
C - Language Python
➢ An Imperative programming model is ➢An object-oriented programming model
basically followed by C. is basically followed by Python.
➢ Variables are declared in C. ➢ Python has no declaration.
➢ C doesn’t have native OOP. ➢Python has OOP which is a part of
language.
➢ Pointers are available in C language. ➢No pointers functionality is available in
Python.
➢ C is a compiled language. ➢ Python is an interpreted language.
➢ There is a limited number of built-in ➢There is a large library of built-in
functions available in C. functions in Python.
➢ Implementation of data structures ➢It is easy to implement data structures
requires its functions to be explicitly in Python with built-in insert, append
implemented. functions.
➢ C is compiled direct to machine code ➢Python is firstly compiled to a byte-
which is executed directly by the CPU code and then it is interpreted by a large
C program.
➢ Declaring of variable type in C is ➢There is no need to declare a type of
necessary condition. variable in Python.
➢ C does not have complex data ➢Python has some complex data
structures. structures.
➢ C is statically typed. ➢ Python is dynamically typed.
➢ Syntax of C is harder than python ➢ It is easy to learn, write and read
because of which programmers prefer to Python programs than C.
use python instead of C
➢ C programs are saved with .c ➢ Python programs are saved by .py
extension. extension.
➢ An assignment is allowed in a line. ➢ Assignment gives an error in line. For
example, a=5 gives an error in python.
Running Python
➢ Python is a well known high-level programming language. The Python script is basically
a file containing code written in Python. The file containing python script has the extension
‘.py’ or can also have the extension ‘.pyw’ if it is being run on a windows machine. To run a
python script, we need a python interpreter that needs to be downloaded and installed.
➢ we first have to check whether a python interpreter is installed on the system or not. So
in windows, open ‘cmd’ (Command Prompt) and type the following command.
Dept.CSE ,SANK 12 KARTIK J
KULKARNI
PYTHON PRORAMMING [18CS601]
Here are the ways with which we can run a Python script.
➢ Interactive Mode
➢ Command Line
➢ IDE (PyCharm)
You can start Python from Unix, DOS, or any other system that provides you a command-
line interpreter or shell window.
➢ Command Line
To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’
keyword before the file name in the command prompt.
or
or
Example:
➢ IDE (PyCharm)
Types of Errors
➢ Programming errors are called bugs and the process of tracking them down is called
debugging.
➢ Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic
errors.
1) Syntax Errors
➢ Python can only execute a program if the syntax is correct; otherwise, the interpreter
displays an error message. Syntax refers to the structure of a program and the rules about
that structure. For example, parentheses have to come in matching pairs, so (1+2) is 3
legal, (1+2)+ is syntax error
2) Runtime Errors:
➢ The second type of error is a runtime error, so called because the error does not appear
until after the program has started running. These errors are also called exceptions because
they usually indicate that something exceptional (and bad) has happened.
3) Semantic Errors
➢ The third type of error is the semantic error. If there is a semantic error in your
program, it will run successfully in the sense that the computer will not generate any error
messages, but it will not do the right thing. It will do something else. Specifically, it will
do what you told it to do.
➢ The problem is that the program you wrote is not the program you wanted to write.
The meaning of the program (its semantics) is wrong. Identifying semantic errors can be
tricky because it requires you to work backward by looking at the output of the program
and trying to figure out what it is doing.
➢ A value is one of the basic things a program works with, like a letter or a number. The
values we have seen so far are 1,2 and “Hello World”
➢ These values belong to different types: 2 is an integer, and ‘Hello world’ is a string,
so-called because it contains a “string” of letters. We means the interpreter can identify
strings because they are enclosed in quotation marks.
▪ >>> 1,00,000
▪ (1,0,0)
➢ Well, that’s not what we expected at all! Python interprets 1,00,000 as a comma
separated sequence of integers. This is the first example we have seen of a semantic
error: the code runs without producing an error message, but it doesn’t do the “right”
thing.
Identifiers
➢ Identifiers are used for identification Purpose. An identifier is a name given to entities
like class, functions, variables, etc. It helps to differentiate one entity from another.
Rules for Identifiers
➢ Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen all
are valid example.
➢ An identifier cannot start with a digit. 1variable, 1a, n%4, n 9 are invalid, but variable1 is
perfectly fine.
➢ Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
➢ Keywords cannot be used as identifiers.
➢ Identifier names are case sensitive(differentiating between capital and lower-case letters)
for example my name, and MyName is not the same.
➢ There is no length limit for python identifier but it is not recommended because redability
of the program is going to be down.
Keywords/Reserved Words
➢ Python Keywords are special reserved (fixed) words which convey a special meaning to
the compiler/interpreter.
➢ All the keywords except True, False and None are in lowercase and they must be written
as it is.
Example
import keyword
keyword.kwlist
Comments are very important while writing a program. It describes what's going on inside a
program so that a person looking at the source code does not have a hard time figuring it out.
In Python, we use the hash (#) symbol to start writing a comment.
Eg:#This is a comment
#print out Hello
print('Hello')
Output:
Hello
2) Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line.
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as multi-
line comment as well.
Example:
Output
Hello World
Python Indentation
Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation. A code block (body of a function, loop etc.) starts with
indentation.
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a
statement. The statements with the same indentation belong to the same group called a suite.
Eg: if True:
print('Hello')
Output:
Program-2
Output
Data Types
➢ Data type represent the type of data present inside the variable.
➢ In Python we cannot required to specify the type explicitly. Based on value provided, the
type will be assigned automatically. Hence python is dynamically typed language.
➢ Python contains following data types:
int, float, complex, bool, range, str, list, tuple, set, dict, None
1) Int datatype
➢ We can use int datatype to represent the whole numbers(integral numbers). Integral
Numbers means number without decimal points.
➢ In python2 we have long datatype to represent very large integral values. Eg:
908090800L, -0x1929292L
➢ In python3 there is no long type explicitly and we can represent long values also by
using int type only. Size is not fixed in python.
➢ Syntax: Variable Name= Integer Value (or) Decimal (or) Binary (or) Octal (or) Hexa
Decimal
➢ We can represent the int values in the following ways.
1. Decimal
2. Binary
3. Octal
4. Hexa
Base Conversions
Examples
2) Float Datatype:
We use float type to represent the floating point values (decimal values).
Eg: f=10.5
We can also represent floating point values by using exponential forms(scientic
notations)
Eg:a=1.2e3 a=6E+5 a=3.12E4
>>> a
1200.0
instead of e we can use E. The main advantage of exponential form is we can represent
big values in less memory.
Syntax: Variable Name= Float Values
Note: We can represent int values in decimal, binary octal and hexa decimal forms. But
we can represent the float values by using decimal form.
3) Complex Datatype:
➢ A complex number is of two parts one is real part and other one is imaginary part.
➢ Eg: 3+5j, 10+5.5j, 0.5+0.1j
➢ In the real part if we use int value that we can specify either by decimal, octal, binary
or hexadecimal form.
➢ But imaginary part should be specified only by using decimal form.
➢ Complex datatype has some inbuilt attributes to retrieve the imaginary part
➢ and real part. Eg: c=5+3j, c.real c.imag
➢ We can use complex datatype generally in scientific applications and EE Appli.
➢ Syntax: Variable Name= Complex Value
Examples
4) Bool Datatype
➢ We can use this datatype to represent boolean values. The boolean values are True and
False.
➢ Internally python True as 1 and False as 0.
➢ Syntax: Variable Name=Boolean value
5) Range Datatype
➢ Range Data Type represents a sequence of numbers. The elements present in range Data
type are not modifiable. i.e. range Data type is immutable.
➢ Range object does not support item assignment
➢ We can access elements present in the range data type by using index
➢ Syntax: list(range(values))
list(range(begin,end))
list(range(begin,end,step))
➢ Where step represents the increment or decrement the values in a range
Examples
6) Str Datatype
7) List Datatype
If we want to represent a group of values as a single entity where insertion order
required to preserve and duplicates are allowed then we should go for list data type.
Examples
Tuple data type is exactly same as list data type except that it is immutable. i.e we
cannot change values. Tuple elements can be represented within parenthesis ().
Examples
9) Set Datatype
If we want to represent a group of values without duplicates where order is not important
then we should go for set Data Type. Set elements are represented with in curly braces{}
1. Insertion order is not preserved
2. Duplicates are not allowed
3. Heterogeneous objects are allowed
4. Index concept is not applicable
5. It is mutable collection
6. Growable in nature
Examples
Examples
None means Nothing or No value associated. If the value is not available, then to handle
such type of cases None introduced. It is something like null value in Java.
Examples
Type Casting
➢ We can convert one type value to another type. This conversion is called Typecasting
or Type coersion.
➢ The following are various inbuilt functions for type casting.
1. int()
2. float()
3. complex()
4. bool()
5. str()
1) int()
We can use this function to convert values from other types to int
Example
>>> int(123.987)
123
>>> int(10+5j)
TypeError: can't convert complex to int
>>> int(True)
1
2) float():
We can use float() function to convert other type values to float type.
Example
>>>float(10)
10.0
>>>float(10+5j)
TypeError: can't convert complex to float
>>>float(True)
1.0
>>>float(False)
0.0
>>>float("10")
10.0
>>>float("10.5")
10.5
>>>float("ten")
ValueError: could not convert string to float: 'ten'
>>>float("0B1111")
ValueError: could not convert string to float: '0B1111'
3) complex()
complex(10)==>10+0j
complex(10.5)===>10.5+0j
complex(True)==>1+0j
complex(False)==>0j
complex("10")==>10+0j
complex("10.5")==>10.5+0j
complex("ten")
Example-2
complex(10,-2)==>10-2j
complex(True,False)==>1+0j
4) bool()
We can use this function to convert other type values to bool type.
The bool() method is used to return or convert a value to a Boolean value i.e., True or False.
Here are few cases, in which Python’s bool() method returns false. Except these all other
values return True.
If a False value is passed.
If None is passed.
If an empty sequence is passed, such as (), [], ”, etc
If Zero is passed in any numeric type, such as 0, 0.0 etc
If an empty mapping is passed, such as {}.
Example
bool(0)==>False
bool(1)==>True
bool(10)===>True
bool(10.5)===>True
bool(0.178)==>True
bool(0.0)==>False
bool(10-2j)==>True
bool(0+1.5j)==>True
bool(0+0j)==>False
bool("True")==>True
bool("False")==>True
bool("")==>False
5) str():
We can use this method to convert other type values to str type
Example
>>>str(10)
'10'
>>>str(10.5)
'10.5'
>>>str(10+5j)
'(10+5j)'
>>>str(True)
'True'
UNIT-II
FUNCTIONS AND
Functions and Modules: Introduction to functions, Types of Functions, Flow of Execution, Parameters
and arguments, Pass by reference and pass by value, Function arguments, Return Statement, Composition,
Recursion, Python Modules.
FUNCTIONS
TYPES OF FUNCTIONS:
Functions are classified into 3 types. They are
1. Built in fuctions
2. Anonymous functions
3. User defined functions
1. Built in functions
The Python interpreter has a number of functions and types built into it that are always
available. They are listed here in alphabetical order.
2. Anonymous Functions
The power of lambda is better shown when you use them as an anonymous function inside
another function.
Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Or, use the same function definition to make a function that always triples the number you
send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Or, use the same function definition to make both functions, in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Use lambda functions when an anonymous function is required for a short period of time.
You can define functions to provide the required functionality. Here are simple rules to
define a function in Python.
➢ Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
➢ Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
➢ The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
➢ The code block within every function starts with a colon (:) and is indented.
➢ The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
Example
The following function takes a string as input parameter and prints it on standard screen.
FLOW OF EXECUTION:
>>> math.sin(20)
0.9129452507276277
>>> math.pow(2,3)
8.0
import math
def print_twice(bruce):
print (bruce)
print (bruce)
print_twice('Spam')
print_twice(17)
print_twice(math.pi)
print_twice('Spam'*4)
>>> a = ‘hello'
>>> print_twice(a)
hello
hello
All parameters (arguments) in the Python language are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the
calling function. For example −
#!/usr/bin/python
There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.
#!/usr/bin/python
Function Arguments
You can call a function by using the following types of formal arguments −
➢ Required arguments
➢ Keyword arguments
➢ Default arguments
➢ Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition.
#!/usr/bin/python
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter
is able to use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways −
ve Dem
#!/usr/bin/python
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −
Demo
#!/usr/bin/python
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
#!/usr/bin/python
RETURN STATEMENT:
➢ Every function has the implicit return statement as the last instruction in the function
body
➢ This implicit return statement returns nothing to its caller.
➢ We can change this default value by explicitly using the return statement by which we
can return some value back to the caller.
➢ Syntax:
➢ 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
Example:
def cube(x):
z=x*x*x
return(z)
num=10
result=cube(num)
print("Cube of",num,"=",result)
def display(str):
print(str)
x=display("Hello World")
print(x)
Composition
While I don’t consider myself a functional programming expert, all those hours spent in
Haskell, Lisp and Scheme definitively changed my way of programming. So, after seeing a
lot of unnecessarily complex implementations of function composition in Python on the
Web, I decided to write this article to present a simple yet powerful solution that covers all
use cases. If you are familiar with function composition, you may want to go to the solution.
Function composition is a way of combining functions such that the result of each function is
passed as the argument of the next function. For example, the composition of two
functions f and g is denoted f(g(x)). x is the argument of g, the result of g is passed as the
argument of f and the result of the composition is the result of f.
Example:
Composing n functions
Now that we know how to compose two functions, it would be interesting to generalize it to
accept n functions. Since the solution is based on compose2, let’s first look at the
composition of three functions using compose2.
Do you see the pattern? First, we compose the first two functions, then we compose the
newly created function with the next one and so on.
Recursion
Python also accepts function recursion, which means a defined function can call itself.
The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
Modules
If you quit from the Python interpreter and enter it again, the definitions you have made
(functions and variables) are lost. Therefore, if you want to write a somewhat longer
program, you are better off using a text editor to prepare the input for the interpreter and
running it with that file as input instead. This is known as creating a script. As your program
gets longer, you may want to split it into several files for easier maintenance. You may also
want to use a handy function that you’ve written in several programs without copying its
definition into each program.
To support this, Python has a way to put definitions in a file and use them in a script or in an
interactive instance of the interpreter. Such a file is called a module; definitions from a
module can be imported into other modules or into the main module (the collection of
variables that you have access to in a script executed at the top level and in calculator mode).
Now enter the Python interpreter and import this module with the following command:
>>>
This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the module name fibo there. Using the module name you can access the
functions:
>>>
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo. name
If you intend to use a function often you can assign it to a local name:
>>>
UNIT-III
OPERATORS , CONTROL FLOW AND STRINGS
Operators and Control Flow: Operators, Conditional Statements, Iteration, Loop Control statements.
Strings: Strings, String Slices, Immutability, String operations, String Methods, String Modules.
Operators in python
Operator is a symbol that performs certain operations on operands.
1. Arithmetic Operators
3. Logical operators
4. Bitwise oeprators
5. Assignment operators
6. Ternary Operator
7. Special operators
1) Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication and division.
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ==>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
Output
a+b= 12
=8
a*b= 20
a/b= 5.0
a//b= 5
a%b= 0
a**b= 100
Note
➢ / operator always performs floating point arithmetic. Hence it will always returns float
value. But Floor division (//) can perform both floating point and integral arithmetic.
If arguments are int type then result is int type. If atleast one argument is float type
then result is float type.
➢ We can use +,* operators for str type also. If we want to use + operator for str type
then compulsory both arguments should be str type only otherwise we will get error.
➢ If we use * operator for str type then compulsory one argument should be int and
other argument should be str type.
2) Relational Operators
Relational operators compare the values. It either returns True or False according to the
condition.
> (greater than), >= (greaterthan or equal to), < (lessthan), <= (lessthan or equal to), ==
(double equal), != (not equal)
Program
a=10
b=20
print("a > b is ",a>b)
print("a >= b is ",a>=b)
print("a < b is ",a<b)
print("a <= b is ",a<=b)
print("a == b is ",a==b)
print("a != b is ",a!=b)
Output
a > b is False
a >= b is False
a < b is True
a <= b is True
a == b is False
a != b is True
Note
Chaining of relational operators is possible. In the chaining, if all comparisons returns True
then only result is True. If atleast one comparison returns False then the result is False
Eg:
1) 10<20 ==>True
2) 10<20<30 ==>True
3) 10<20<30<40 ==>True
4) 10<20<30<40>50 ==>False
3) Logical Operators
They allow a program to make a decision based on multiple conditions. Each operand is
considered a condition that can be evaluated to a true or false value.
and, or ,not
For boolean types behavior:
➢ and ==>If both arguments are True then only result is True
➢ or ==>If atleast one arugemnt is True then result is True
➢ not ==>complement
Program
a=10
b=20
c=0
print("a and b is ",a and b)
print("a or b is ",a or b)
print("not b is ",not b)
print("c and b is ",c and b)
print("c and b is ",c or b)
print("not c is", not c)
Output:
a and b is 20
a or b is 10
Dept. of CSE, 46 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
not b is False
c and b is 0
c and b is 20
not c is True
4) Bitwise Operators
➢ Bitwise operators acts on bits and performs bit by bit operation.We can apply these
operators bitwise. These operators are applicable only for int and boolean types. By
mistake if we are trying to apply for any other type then we will get Error.
➢ & (bitwise and),| (bitwise or), ^(bitwise xor), ~ (bitwise complement),<< (bitwise left
shift), >> (bitwise right shit)
➢ & ==> If both bits are 1 then only result is 1 otherwise result is 0
➢ | ==> If atleast one bit is 1 then result is 1 otherwise result is 0
➢ ^ ==>If bits are different then only result is 1 otherwise result is 0
➢ ~ ==>Bitwise complement operator 1==>0 & 0==>1
➢ << ==>Bitwise Left shift
➢ >> ==>Bitwise Right Shift
Note:
The most significant bit acts as sign bit. 0 value represents +ve number where as 1 represents
-ve value. Positive numbers will be represented directly in the memory where as -ve
numbers will be represented indirectly in 2's complement form.
Program
a=10
b=4
print("a & b =", a & b)
print("a | b =", a | b)
print("~a =", ~a)
print("a ^ b =", a ^ b)
print("a<<b=",a<<b)
print("a>>b=",a>>b)
Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14
a<<b= 160
a>>b= 0
The following is the list of all possible compound assignment operators in Python
Output:
Line 2 - Value of c is 21
Line 3 - Value of c is 441
Line 4 - Value of c is 21.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
6) Ternary Operator
Ternary operators also known as conditional expressions are operators that evaluate
something based on a condition being true or false.
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue will be considered.
Program
a,b=10,20
x=30 if a<b else 40
print(x)
Output:
30
Output:
Enter First Number:4
Enter Second Number:5
Minimum Value: 4
7) Special Operator
1. Identity Operator
We can use identity operators for address comparison. There are two identity operators are
available
1. is
2. is not
r1 is r2 -- returns True if both r1 and r2 are pointing to the same object
r1 is not r2 -- returns True if both r1 and r2 are not pointing to the same object
Program
a="durga"
b="durga"
print(id(a))
print(id(b))
print(a is b)
print(a is not b)
Output:
65621440
65621440
True
False
2. Membership Operator
➢ We can use Membership operators to check whether the given object present in the
given collection.(It may be String, List, Set, Tuple or Dict) .
➢ in- Returns True if the given object present in the specified location
➢ not in- Returns if the given object is not present in the specified location
Dept. of CSE, 49 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
Output:
True
False
True
True
➢ Decision making is required when we want to execute a code only if a certain condition
is satisfied.
➢ Syntax: iftest expression: statement(s)
Flowchart
Example
num = 3
if num > 0:
print(num,"isapositivenumber.") print("This is always printed.")
If-Else(Alternative Execution)
The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the
blocks.
Syntax
if test expression:
Body of if
else:
Body of else
FlowChart
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output
if...elif...else(Chained Conditionls)
The elif is short for else if. It allows us to check for multiple expressions.
Sometimes there are more than two possibilities and we need more than two branches.
One way to express a computation like that is a chained conditional.
If the condition for if is False, it checks the condition of the next elif block and so on. If
all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks Syntax:
if test expression:
Body of if
elif test expression:
Body of elif
else: Body of else
Flowchart
Example i = 20
if (i == 10):
print ("i is 10") elif (i == 15):
print ("i is 15") elif (i == 20):
print ("i is 20") else:
print ("i is not present")
Output
i is 20
Nested Conditionals
We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only
way to figure out the level of nesting.
The outer conditional contains two branches. The first branch contains a simple statement.
The second branch contains another if statement, which has two branches of its own.
Those two branches are both simple statements, although they could have been
conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals
become difficult to read very quickly.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s) else: statement(s)
else:
statement(s)
Example
num = float(input("Enter a number: ")) if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number") else:
print("Negative number")
Output
Enter a number: 5 Positive number Recursion
It is legal for one function to call another; it is also legal for a function to call itself.
A function that calls itself is recursive; the process is called recursion.
Example
def countdown(n):
if n<=0:
print("blatsoff")
else:
print(n)
countdown(n-1) countdown(3)
Output
3
2
1
Blastoff
The execution of countdown begins with n=3, and since n is greater than 0, it outputs the
value 3, and then calls itself...
The execution of countdown begins with n=2, and since n is greater than 0, it outputs the
value 2, and then calls itself...
The execution of countdown begins with n=1, and since n is greater than 0, it outputs the
value 1, and then calls itself...
The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the
word, “Blastoff!” and then returns.
Infinite Recursion
If a recursion never reaches a base case, it goes on making recursive calls forever, and the
program never terminates. This is known as infinite recursion
Example
def print_n(s,n):
if n<=0:
return 0
print(s)
print_n(s,n+1)
print(print_n(3,3))
Iterative Statements
➢ The for loop in Python is used to iterate over a sequence (list,tuple,string etc) or other
iterable objects. Iterating over a sequence is called traversal.
Syntax:
➢ for variable_name in sequence: body
➢ where sequence can be string or any collection. Body will be executed for every element
present in the sequence.
Program
Output
False
2. While Loop:
➢ The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
Syntax:
while test_expression:
Body of while
➢ In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until the test_expression evaluates to
False.
➢ In Python, the body of the while loop is determined through indentation.
Program
def word1(word):
i=0
while i<len(word)-1:
if word[i+1]<word[i]: return False
i=i+1 return True
print(word1('money'))
Output
False
Infinite Loop
An Infinite Loop in Python is a continuous repetitive conditional loop that gets executed until
an external factor interfere in the execution flow, like insufficient CPU memory, a failed
feature/ error code that stopped the execution, or a new feature in the other legacy systems that
needs code integration.
Program
i=0;
while True : i=i+1; print("Hello",i)
Output
Python programming language allows to use one loop inside another loop
Python allows to use for loop inside the another for loop
Syntax:
program
for i in range(4):
for j in range(4):
print("i=",i," j=",j)
Output
i= 0 j= 0
i= 0 j= 1
i= 0 j= 2
i= 0 j= 3
i= 1 j= 0
i= 1 j= 1
i= 1 j= 2
i= 1 j= 3
i= 2 j= 0
i= 2 j= 1
i= 2 j= 2
i= 2 j= 3
i= 3 j= 0
i= 3 j= 1
i= 3 j= 2
i= 3 j= 3
Python allows to use while loop inside the another while loop
Syntax:
while expression: while expression:
statement(s) statement(s)
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break j = j + 1
if (j > i/j) : print(i, " is prime") i = i + 1
print("Good bye!")
Output
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Good bye!
Strings:
String is a sequence
A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
Dept. of CSE, 59 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
fruit=‘banana’ letter=fruit[1]
➢ The second statement selects character number 1 from fruitt and assigns it to letter.
➢ The expression in brackets is called an index. The index indicates which character in the
sequence you want (hence the name).
Print (letter)
Output: a
➢ For most people, the first letter of ‘banana’ is b, not a. But for computer scientists, the
index is an offset from the beginning of the string, and the offset of the first letter is zero.
fruit=‘banana’
letter=fruit[0]
Print (letter)
Output: b
➢ So b is the 0th letter (“zero-eth”) of ‘banana’, a is the 1th letter (“one-eth”), and n is the 2th
(“two- eth”) letter.
➢ You can use any expression, including variables and operators, as an index, but the value
of the index has to be an integer. Otherwise you get:
letter= fruit[1.5]
TypeError: String indices must be integers not float
Program
>>> fruit='banana'
>>> fruit 'banana'
>>> letter=fruit[1]
>>> letter 'a'
>>> print(letter) a
>>> letter=fruit[0]
>>> letter 'b'
>>> print(letter) b
>>> letter=fruit[1.5]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module> letter=fruit[1.5]
TypeError: string indices must be integers
Len Function
➢ len is a built-in function that returns the number of characters in a string. fruit=‘banana’
len(fruit)
Output:6
Program
>>> fruit='banana'
>>> length=len(fruit)
>>> last=fruit[length]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module> last=fruit[length]
IndexError: string index out of range
>>> last=fruit[length-1]
>>> las
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module> las
NameError: name 'las' is not defined
>>> last 'a'
➢ A lot of computations involve processing a string one character at a time. Often they
start at the beginning, select each character in turn, do something to it, and continue
until the end. This pattern of processing is called a traversal. The ways to write a
traversal is with a for loop and while loop.
➢ This loop traverses the string and displays each letter on a line by itself.
➢ The loop condition is index<len(fruit), so when index is equal to the length of the
string, the condition is false, and the body of the loop is not executed.
➢ The last character accessed is the one with the index len(fruit)-1, which is the last
character in the string.
➢ Each time through the loop, the next character in the string is assigned to the variable
Program-1
Output
banana
Program-2
fruit='banana' index=0
while(index<len(fruit)): letter=fruit[index]
print(letter) index=index+1
Output
ba n a n a
Program-3
prefixies='JKLMNOPQ' suffix='ack'
for letter in prefixies: print(letter+suffix)
Output
String Slices
➢ A segment of a string is called a slice. Selecting a slice is similar to selecting a
character.
Program
s='monthy python'
print(s[0:5])
print(s[6:12])
fruit='banana'
print(fruit[:3])
print(fruit[3:])
print(fruit[3:3])
Output
greeting='Hello World'
new_greeting='j'+greeting[1:]
print(new_greeting)
Output
jello World
Searching
➢ In a sense, find is the opposite of the [] operator. Instead of taking an index and
extracting the corresponding character, it takes a character and finds the index where
that character appears. If the character is not found, the function returns -1
➢ This is the first example we have seen of a return statement inside a loop. If
word[index]==lettter, the function breaks out of the loop and returns immediately.
➢ If the character doesn’t appear in the string, the program exits the loop normally and
returns -1
➢ This pattern of computation—traversing a sequence and returning when we find what
we are looking for—is called a search.
Program
def find(word,letter):
index=0
while(index<len(word)):
if(word[index]==letter):return index
index=index+1
return -1
print(find('hello','l'))
Output
word='banana' count=0
for letter in word: if letter=='a':
count=count+1
print(letter,count)
Output
a3
String Methods
➢ A method is similar to a function—it takes arguments and returns a value—but the
syntax is different. For example, the method upper takes a string and returns a new
string with all uppercase letters.
➢ This form of dot notation specifies the name of the method, upper, and the name of the
string to apply the method to, word. The empty parentheses indicate that this method
takes no argument.
➢ A method call is called an invocation; in this case, we would say that we are invoking
upper on the word.
1. find()
Program-1
Output
9
-1
3
21
Dept. of CSE, 65 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
Program-2
s="durgaravipavanshiva"
print(s.find('a'))
print(s.find('a',7,15))
print(s.find('z',7,15))
Output
4
10
-1
2. rfind()
➢ rfind() method returns the highest index of the substring if found in given string.
➢ If not found then it returns -1.
Program
Output 8
3. index() method
index() method is exactly same as find() method except that if the specified substring is not
available then we will get ValueError.
Syntax: string.index(elmnt)
Program
Output
The index of e: 1
➢ The rindex() method returns the highest index of the substring inside the string (if
found). If the substring is not found, it raises an exception
Program-1
Output
Program-2
Output 8
➢ We can find the number of occurrences of substring present in the given string by using
count() method.
➢ s.count(substring) ==> It will search through out the string
➢ s.count(substring, begin, end) ===> It will search from begin index to end-1 index
program
s="abcabcabcabcadda" print(s.count('a'))
print(s.count('ab'))
print(s.count('a',3,7))
Output
6
4
2
➢ The replace() method returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Syntax: string.replace(oldvalue, newvalue, count)
➢ Once we creates string object, we cannot change the content. This non changeable
behaviour is nothing but immutability. If we are trying to change the content by using
any method, then with those changes a new object will be created and changes won't be
happened in existing object.
➢ Hence with replace() method also a new object got created but existing object won't be
changed.
Program-1
Output
Program-2
txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three", 2)
print(x)
Output
Three three was a race horse, two two was one too
Splitting of Strings
split() method returns a list of strings after breaking the given string by the specified
separator.
Syntax: str.split(separator, maxsplit)
Program
Joining of Strings
➢ The join() string method returns a string by joining all the elements of an iterable,
separated by a string separator.
➢ The join() method provides a flexible way to create strings from iterable objects. It joins
each element of an iterable (such as list, string, and tuple) by a string separator (the
string on which the join() method is called) and returns the concatenated string.
Syntax: string.join(iterable)
Program
Output
1, 2, 3, 4
1, 2, 3, 4
s1.join(s2): 1abc2abc3 s2.join(s1): a123b123c
Program
Output
program
print('Durga786'.isalnum())
print('durga786'.isalpha())
print('durga'.isalpha())
print('durga'.isdigit())
print('786786'.isdigit())
print('abc'.islower())
print('Abc'.islower())
print('abc123'.islower())
print('ABC'.isupper())
print('Learning python is Easy'.istitle())
print('Learning Python Is Easy'.istitle())
print(' '.isspace())
Output
True False True False True True False True True False True True
In Operator:
➢ The word in is a boolean operator that takes two strings and returns True if the first
appears as a substring in the second.
➢ With well-chosen variable names, Python sometimes reads like English. You could read
this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second)
word, print (the) letter.”
Program
Output
aes
➢ Python does not handle uppercase and lowercase letters the same way that people do.
All the uppercase letters come before all the lowercase letters.
➢ A common way to address this problem is to convert strings to a standard format, such
as all lowercase, before performing the comparison. Keep that in mind in case you have
to defend yourself against a man armed with a Pineapple.
Program
word="orange"
if word=='banana': print('All right, bananas')
if word<'banana':
print('your word,'+word+',comes before banana') else:
print('your word,'+word+',comes after banana')
Output
STRING MODULES:
➢ String Module consist of a number of useful constants, classes and functions.
➢ These functions are used to manipulate strings.
➢ To see the content of string module, we can use dir() with the module name as the
argument as shown below,
>>> dir(str)
[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ', ' eq ',
' format ', ' ge ', ' getattribute ', ' getitem ', ' getnewargs ', ' gt ', ' hash ',
' init ', ' init_subclass ', ' iter ', ' le ', ' len ', ' lt ', ' mod ', ' mul ',
' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' rmod ', ' rmul ',
' setattr ', ' sizeof ', ' str ', ' subclasshook ', 'capitalize', 'casefold', 'center', 'count',
'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
List is a sequence:
➢ Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they
can be any type. The values in a list are called elements or sometimes items.
➢ There are several ways to create a new list; the simplest is to enclose the elements in square
brackets ([ and ]):
➢ [10,20,30,40] [‘a’,’b’,’c’,’d’]
➢ The first example is a list of four integers. The second is a list of three strings.
➢ The elements of a list don’t have to be the same type. The following list contains a string, a
float, an integer, and another list.
➢ Eg:[‘spam’,30,40.5,[1,2]]
➢ A list within another list is nested.
➢ A list that contains no elements is called an empty list; you can create one with empty brackets
[ ].
Eg:
Cheeses=[‘Cheddar’,’Edam’,’Gouda’]
print(cheeses[0])
Output:
Eg:
Unlike strings, lists are mutable. When the bracket operator appears on the left side of an
assignment, it identifies the element of the list that will be assigned.
numbers=[17,123]
numbers[1]=5
print(numbers)
Output:
[17,5]
Traversing a list:
➢ The most common way to traverse the 0elements of a list is with a for loop. The syntax is the
same as for strings.
Eg: for cheese in cheeses: print(cheese)
➢ This works well if you only need to read the elements of the list. But if you want to write or
update the elements, you need the indices. A common way to do that is to combine the
functions range and len.
for i in range(len(numbers)): numbers[i]=[i]*2
➢ This loop traverses the list and updates each element. len returns the number of elements in the
list. range returns a list of indices from 0 to n- 1, where n is the length of the list.
➢ Each time through the loop i gets the index of the next element. The assignment statement in
the body uses i to read the old value of the element and to assign the new value.
➢ A for loop over an empty list never executes the body.
Eg: for x in []:
print(“this never happens”)
➢ Although a list can contain another list, the nested list still counts as a single element. The
length of this list is four.
[‘spam’,1,[‘sam’,’hari’,’robert’],[1,2,3]]
Program-1
cheeses=['cheddar','Edam','Gouda']
for cheese in cheeses:
print(cheese)
Program-2
numbers=[12,13,14,15]
for i in range(len(numbers)): numbers[i]=[i]*2
print(numbers)
Output
List Operations
➢ The most conventional method to perform the list concatenation, the use of “+”
operator can easily add the whole of one list behind the other list and hence perform
the concatenation.
Program-1
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
# using + operator to concat test_list3 = test_list3 + test_list4
# Printing concatenated list
print ("Concatenated list using + : " + str(test_list3))
Output
➢ Sequences datatypes (both mutable and immutable) support a repetition operator *. The
repetition operator * will make multiple copies of that particular object and combines them
together. When * is used with an integer it performs multiplication but with list, tuple or strings
it performs a repetition
Program-2
l1= [1,2,3]
print(l1*3)
[1,2,3,1,2,3,1,2,3]
Nested List
➢ A list can contain any sort object, even another list (sublist), which in turn can contain
sublists themselves, and so on. This is known as nested list.
➢ A nested list is created by placing a comma-separated sequence of sublists.
➢ Eg: L = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', 'h']
➢ Access individual items in a nested list using multiple indexes.
➢ Access a nested list by negative indexing as well.
➢ Negative indexes count backward from the end of the list. So, L[-1] refers to the last
item, L[-2] is the second-last, and so on.
Program-1
print(L[2])
print(L[2][2])
print(L[2][2][0])
Output
Program-2
Output
List Slices
➢ To access a range of items in a list, you need to slice a list
➢ The way to do this is to use the simple slicing operator : With this operator you can
Program-1
Output
Program-2
Output
Program-3
Output
['c', 'd']
Program-4
Program-5
Output
['a', 1, 2, 3, 'e']
List Methods
1. count()
The count() method returns the number of times the specified element appears in the list.
Syntax: list.count(element)
Program
Output
2. index()
The index() method returns the index of the specified element in the list.
Syntax: list.index(element, start, end)
If the element is not found, a ValueError exception is raised.
Output
3. remove()
This method is used to remove specified item from the list. If the item present multiple times
then only first occurrence will be removed.
Syntax: list.remove(element)
If the specified item not present in list then we will get ValueError
Program
n=[10,20,10,30]
n.remove(10) print(n)
Output
4. pop()
It removes and returns the last element of the list. This is only function which manipulates
list and returns some element
Syntax: list.pop(index)
Program
n=[10,20,10,30]
n.pop(2)
n
n.pop()
10
[10,20,30]
30
5. reverse()
Syntax: list.reverse()
Program
Output
Original List: ['Windows', 'macOS', 'Linux'] Updated List: ['Linux', 'macOS', 'Windows']
6. sort()
In list by default insertion order is preserved. If want to sort the elements of list according to
default natural sorting order then we should go for sort() method.
Syntax: list.sort(key=..., reverse=...)
For numbers ==>default natural sorting order is Ascending Order
For Strings ==> default natural sorting order is Alphabetical Order
To use sort() function, compulsory list should contain only homogeneous elements. otherwise
we will get TypeError
Program
n=[20,5,15,10,0]
n.sort()
n
s=["Dog","Banana","Cat","Apple"]
s.sort()
s n=[20,10,"A","B"]
n.sort() n=[20,5,15,10,0]
n.sort(reverse=True)
n
7. clear()
Program
n=[20,5,15,10,0]
n.clear()
n
Output
[]
8. append()
Syntax:list.append(item)
Program
Output
9. extend()
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of
the list.
Syntax: list.extend(iterable)
Output
Map function
The map() function applies a given function to each item of an iterable (list, tuple etc.) and
returns a list of the results.
Syntax: map(function, iterable, ...)
The map() function applies a given to function to each item of an iterable and returns a list of
the results.
The returned value from map() (map object) can then be passed to functions like list() (to create
a list), set() (to create a set) and so on.
Program
Output
Reduce function
➢ An operation like that combines a sequence of elements into a single value is sometimes
called reduces.
Syntax: reduce(function,sequence[,initial])
➢ The reduce() function accepts a function and a sequence and returns a single value
calculated as follows:
➢ Initially, the function is called with the first two items from the sequence and the result
is returned.
Program
Output
10
Filter Functions
➢ The filter() method filters the given sequence with the help of a function that tests each
element in the sequence to be true or not.
Syntax: filter(function, iterable(s))
➢ filter() method returns an iterator that passed the function check for each element in the
iterable.
➢ filter() method is equivalent to:
➢ # when function is defined (element for element in iterable if function(element))
➢ # when function is None (element for element in iterable if element)
Program
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o'] def filterVowels(letter):
vowels = ['a', 'e', 'i', 'o', 'u'] if(letter in vowels):
return True
else:
return False
filteredVowels = filter(filterVowels, letters) print('The filtered vowels are:')
for vowel in filteredVowels: print(vowel)
Output
Deleting Elements
There are several ways to delete elements from a list. The deleting elements of the methods are
are pop, remove and del keyword.
The deleting elements(pop, remove) methods are discussed in list methods concept are in
above.
➢ del keyword
The del keyword is used to delete objects. In Python everything is an object, so the del keyword
can also be used to delete variables, lists, or parts of a list etc.
Syntax: del obj_name
Program-1
Output
[‘banana’, ‘cherry’]
Program-2
Output
Eg: s=‘spam’
t=list(s) print(t)
Output: [‘s’,’p’,’a’,’m’]
Dept. of CSE, 85 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
➢ Because list is the name of a built-in function, you should avoid using it as a variable name. I
also avoid l because it looks too much like 1. So that’s why I use t.
➢ The list function breaks a string into individual letters. If you want to break a string into
words, we can use the split method.
Eg: s=“learning python is easy” print(s.split())
Output: [‘learning’,’python’, ‘is’, ‘easy’]
➢ An optional argument called a delimiter specifies which characters to use as word
boundaries. The following example uses a hyphen as a delimiter.
Eg: s=‘spam-spam-spam’ delimiter=‘-’ s.split(delimiter)
Output: ['spam', 'spam', 'spam']
➢ join is the inverse of split. It takes a list of strings and concatenates the elements. join is a
string method, so you have to invoke it on the delimiter and pass the list as a parameter.
Eg: t=[‘learning’,’python’,’is’,’very’,’easy’] delimiter=‘’
delimiter.join(t)
Output: 'learning-python-is-very-easy'
But when you create two lists, you get two objects
Eg: A=[1,2,3]
B=[1,2,3]
A is B
Output: False
➢ In this case we would say that the two lists are equivalent, because they have the same
elements, but not identical, because they are not the same object.
➢ If two objects are identical, they are also equivalent, but if they are equivalent, they are
not necessarily identical.
➢ Until now, we have been using “object” and “value” interchangeably, but it is more
precise to say that an object has a value.
➢ If you execute [1,2,3], we get a list object whose value is a sequence of integers. If
another list has the same elements, we say it has the same value, but it is not the same
object.
Aliasing
If a refers to an object and you assign b=a, then both variables refer to the same object.
Eg: a=[1,2,3]
b=a
b is a
Output: True
The association of a variable with an object is called a reference. In this example, there are two
references to the same object.
An object with more than one reference has more than one name, so we say that the object is
aliased.
If the aliased object is mutable, changes made with one alias affect the other.
b[0]=17
print(a)
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing
when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
a=“banana”
b=“banana”
It almost never makes a difference whether a and b refer to the same string or not.
List Arguments
When you pass a list to a function, the function gets a reference to the list. If the function
modifies a list parameter, the caller sees the change. For example, delete_head removes the first
element from a list.
Program
def delete_head(t):
del t[0] letters=[‘a’,’b’,’c’] delete_head(letters)
print(letters)
Output
['b', 'c']
➢ The parameter t and the variable letters are aliases for the same object.
➢ Since the list is shared by two frames, I drew it between them.
➢ It is important to distinguish between operations that modify lists and operations that
create new lists.
Program
t=[1,2]
t1=t.append(3)
print(t)
t2=t+[4]
print(t2)
Output
[1, 2, 3]
[1, 2, 3, 4]
This difference is important when you write functions that are supposed to modify lists. For
example, this function does not delete the head of a list.
Eg: def bad_delete_head(t):
t=t[1:] #wrong
The slice operator creates a new list and the assignment makes t refer to it, but none of that has
any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list. For example, tail returns
all but the first element of a list:
Eg: def tail(t):
return t[1:]
This function leaves the original list unmodified. Here’s how it is used.
Program
def tail(t):
return t[1:]
letters=['a','b','c']
rest=tail(letters)
print(rest)
Output
['b', 'c']
list2=list1
print("List 1 as:",list1)
print("List 2 as:",list2)
list3=list1[2:5]
print("List 3 as:",list3)
Output:
List 1 as: [1, 2, 3, 4, 5]
Eg
>>> t='a','b','c','d','e'
>>> t
('a', 'b', 'c', 'd', 'e')
Eg
>>> t=('a','b','c','d','e')
>>> t
('a', 'b', 'c', 'd', 'e')
Eg
>>> t='a',
>>> t ('a',)
>>> type(t)
<class 'tuple'>
Eg
>>>t1=(‘a’)
>>>type(t1)
<class ‘str’>
Another way to create a tuple is the built-in function tuple. With no argument, it creates an
empty tuple.
Eg-1
>>> t=tuple()
>>> print(t) ()
Eg-2
>>> a=1,2,3,4,5
>>> t=tuple(a)
>>> t
(1, 2, 3, 4, 5)
If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the
sequence.
Eg
>>> t=tuple('lupins')
>>> t
('l', 'u', 'p', 'i', 'n', 's')
Because tuple is the name of a built-in function, you should avoid using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an element.
Eg-1
>>> t=('a','b','c','d','e')
Eg
>>> t=('a','b','c','d','e')
>>> t[1:3] ('b', 'c')
>>> t[-1:-3] ()
>>> t[1:7] ('b', 'c', 'd', 'e')
>>> t[-3:-1]('c', 'd')
But if you try to modify one of the elements of the tuple, you get an error.
Eg
>>> t=('a','b','c','d','e')
>>> t[0]='A'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module> t[0]='A'
TypeError: 'tuple' object does not support item assignment
We can’t modify the elements of a tuple, but you can replace one tuple with another.
Eg
Output
Tuple Assignment
It is often useful to swap the values of two variables. With conventional assignments, you have
to use a temporary variable. For example, to swap a and b.
temp=a
a=b
b=temp
Eg
a,b=b,a
The left side is a tuple of variables; the right side is a tuple of expressions. Each value is
assigned to its respective variable. All the expressions on the right side are evaluated before any
of the assignments.
The number of variables on the left and the number of values on the right have to be thesame.
Eg
a,b=1,2,3
Output
More generally, the right side can be any kind of sequence (string, list or tuple). For example,
to split an email address into a user name and a domain, we could write
Eg
addr=‘monthypthon.org’ Uname,domain=addr.split(‘@’)
The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain.
Eg
print(uname) print(domain)
Output
monty python.org
➢ The built-in function divmod takes two arguments and returns a tuple of two values, the
quotient and remainder. You can store the result as a tuple.
Eg
t=divmod(7,3) print(t)
Output
(2,1)
Eg
Output
def min_max(t):
return min(t), max(t)
t=divmod(7,3)
print(min_max(t))
Output
(1, 2)
min and max are built-in functions that find the largest and smallest elements of a sequence.
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
➢ Key-value pairs
➢ Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3)(‘b’,4)]
X=dict(‘A’=1,’B’ =2)
Example:
Methods that are available with dictionary are tabulated below. Some of them have already been
used in the above examples.
Method Description
Return a new dictionary with keys from seq and value equal to v
fromkeys(seq[, v])
(defaults to None).
Return the value of key. If key doesnot exit, return d (defaults to
get(key[,d])
None).
If key is in the dictionary, return its value. If not, insert key with a
setdefault(key[,d])
value of d and return d(defaults to None)
Dictionary operations:
Output:
'ASCET'
Output:
ASCET
college 2004
Output:
brand model year
>>> for i in
dict1.items():
print(i)
Output:
('brand', 'ASCET')
('model', 'college')
('year', 2004)
Add/change values: You can change the value of a specific item by referring to its key name
Ouput:
college
>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y 4
List of Dictionaries:
## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name':
'charlie'}]
## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]
Comprehension:
Dictionary comprehensions can be used to create dictionaries from arbitrary key and value
expressions:
Program
>>> z={x: x**2 for x in (2,4,6)}
>>> z
Output:
{2: 4, 4: 16, 6: 36}
Program
>>> dict11 = {x: x*x for x in range(6)}
>>> dict11
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
List allows duplicate elements Tuple allows duplicate elements Set will not allow duplicate elements
but keys are not duplicated
List can use nested among all Tuple can use nested among all Dictonary can use nested among all
Example: [1, 2, 3, 4, 5] Example: (1, 2, 3, 4, 5) Example: {1, 2, 3, 4, 5}
List is mutable i.e we can Tuple is immutable i.e we can Dictionary is mutable. But Keys are
make any changes in list. not make any changes in tuple not duplicated.
Creating an empty list l=[] Creating an empty Tuple t=() Creating an empty dictionary d={}
Used in JSON format Used to insert records in the Used to create a data frame with
Useful for Array operations database through SQL query at a lists
Used in Databases time Used in JSON
Ex:(1.’sravan’, 34).(2.’geek’, 35)
Used in parentheses checker
Introduction to Files:
A file is some information or data which stays in the computer storage devices. Python gives you
easy ways to manipulate these files. Generally files divide in two categories, text file and
binary file. Text files are simple text where as the binary files contain binary data which is only
readable by computer.
Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python bydefault.
Binary files: In this type of file, there is no terminator for a line and the data is stored after
converting it into machine understandable binary language.
➢ We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or operation
we want to do on the file
➢ Here we used "w" letter in our argument, which indicates write and the plus sign that
means it will create a file if it does not exist in library
➢ The available option beside "w" are "r" for read and "a" for append and plus sign means
if it is not there then create it
File Modes in Python:
Mode Description
'x' Creates a new file. If file already exists, the operation fails.
'+' This will open a file for reading and writing (updating)
The following image shows how to create and open a text file in notepad from command prompt
(or)
a=open(“one.txt”,”r”)
print(a.read())
a.close()
Output:
C:/Users/ASCET/AppData/Local/Programs/Python/Python38-32/filess/f1.py welcome to
python programming
(or)
Note: All the program files and text files need to saved together in a particular file then only the
program performs the operations in the given file mode
f.close() ---- This will close the instance of the file somefile.txt
stored # Write a python program to open and write “hello world” into
a file?
f=open("1.txt","a")
f.write("hello world")
f.close()
Output:
(or)
Note: In the above program the 1.txt file is created automatically and adds hello world into txt file
If we keep on executing the same program for more than one time then it append the data that many
times
# Write a python program to write the content “hi python programming” for the existing file.
f=open("1.txt",'w')
f.close()
Output:
In the above program the hello txt file consist of data like
But when we try to write some data on to the same file it overwrites and saves with the current data
(check output)
# Write a python program to open and write the content to file and read it.
fo=open("abc.txt","w+")
fo.write("Python Programming")
print(fo.read())
fo.close()
Output:
(or)
ZeroDivisionError:
ZeroDivisionError in Python indicates that the second argument used in a division (or modulo)
operation was zero.
OverflowError:
OverflowError in Python indicates that an arithmetic operation has exceeded the limits of the
current Python runtime. This is typically due to excessively large float values, as integer values
that are too big will opt to raise memory errors instead.
ImportError:
It is raised when you try to import a module which does not exist. This may happen if you made
a typing mistake in the module name or the module doesn't exist in its standard path. In the
example below, a module named "non_existing_module" is being imported but it doesn't exist,
hence an import error exception is raised.
An IndexError exception is raised when you refer a sequence which is out of range. In the
example below, the list abc contains only 3 entries, but the 4th index is being accessed, which
will result an IndexError exception.
TypeError:
When two unrelated type of objects are combined, TypeErrorexception is raised.In example
below, an int and a string is added, which will result in TypeError exception.
IndentationError:
Unexpected indent. As mentioned in the "expected an indentedblock" section, Python not only
insists on indentation, it insists on consistentindentation. You are free to choose the number of
spaces of indentation to use, but you then need to stick with it.
Syntax errors:
These are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a way
to successfully execute a piece of code containing syntax errors.
Run-time error:
A run-time error happens when Python understands what you are saying, but runs into trouble
when following your instructions.
Key Error :
Python raises a KeyError whenever a dict() object is requested (using the format a
= adict[key]) and the key is not in the dictionary.
Value Error:
In Python, a value is the information that is stored within a certain object. To encounter a
ValueError in Python means that is a problem with the content of the object you tried to assign
the value to.
Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly, from
Exception class.
➢ ArrayIndexOutOfBoundException.
➢ ClassNotFoundException.
➢ FileNotFoundException.
➢ IOException.
➢ InterruptedException.
➢ NoSuchFieldException.
➢ NoSuchMethodException
Handling Exceptions:
The cause of an exception is often external to the program itself. For example, an incorrect input,
a malfunctioning IO device etc. Because the program abruptly terminates on encountering an
exception, it may cause damage to system resources, such as files. Hence, the exceptions should
be properly handled so that an abrupt termination of the program is prevented.
Python uses try and except keywords to handle exceptions. Both keywords are followed by
indented blocks.
Syntax:
try :
#executed when error in try block Typically we see, most of the times
Syntactical errors (wrong spelling, colon ( : ) missing ….), At developer level and compile
level it gives errors.
Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may obtained.
Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but if the user say
6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by the system, it is
(mistake) done by the user.
➢ You should be able to understand the mistakes; the error might be done by user, DB
connection or server.
➢ Whenever there is an error execution should not stop.
Ex: Banking Transaction
1. The aim is execution should not stop even though an error occurs.
Dept. of CSE, 107 Dr. N. Krishna
SANK Kumar
PYTHON PRORAMMING [18CS601]
To overcome this we handle exceptions using except keyword
a=5
b=0
try:
print(a/b) except Exception:
print("number can not be divided by zero") print("bye")
Output:
For example if you want to print the message like what is an error in a program then we
use “e” which is the representation or object of an exception.
except Exception as e:
Output:
C:/Users/ASCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex5.py
(Type of error)
I don’t want to print bye but I want to close the file whenever it is opened. a=5
b=2
try:
print("resource opened") print(a/b) print("resource closed")
except Exception as e: