You are on page 1of 32

Page :1

Semester III
XXXXA11– Python Programming
Course Number: 14
Contact Hours per Week: 4T
Number of Credits: 4
Number of Contact Hours: 64
Course Evaluation: Internal – 20 Marks + External – 80 Marks
Outcome of the Course:

Objectives of the Course:

Prerequisites:

Course Outline
UNIT I [16T]
Introduction to python, features, IDLE, python interpreter, Writing and executing python
scripts, comments, identifiers, keywords, variables, data type, operators, operator
precedence and associativity, statements, expressions, user inputs, type function, eval
function, print function.
UNIT II [16T]
Boolean expressions, Simple if statement, if-elif-else statement, compound boolean
expressions, nesting, multi way decisions. Loops: The while statement, range functions, the
for statement, nested loops, break and continue statements, infinite loops.
UNIT III [16T]
Functions, built-in functions, mathematical functions, date time functions, random numbers,
writing user defined functions, composition of functions, parameter and arguments, default
parameters, function calls, return statement, using global variables, recursion.
UNIT IV [16T]
String and string operations, List- creating list, accessing, updating and deleting elements
from a list, basic list operations. Tuple- creating and accessing tuples in python, basic tuple
operations. Dictionary, built in methods to access, update and delete dictionary values. Set
and basic operations on a set.
References:
1. E. Balaguruswamy, Introduction to Computing and Problem Solving Using Python
2. Richard L. Halterman, Learning To Program With Python
3. Martin C. Brown, Python: The Complete Reference.
Page :2

Module 1
Introduction to python
Python is a high-level, interpreted, interactive and object-oriented scripting
language created by Guido Van Rossum at the National Research Institute for
Mathematics and Computer Science in Netherlands. It was released in 1991.
Python got its name from a BBC Comedy series from seventies named „Monty
Pythons Flying Circus‟.

Python Logo
The logo was designed by Tim Parkin. The Python logo is composed of an
iconic emblem with a wordmark on its right. The emblem depicts a two-colored
snakes image, which was based on the ancient Mayan drawings. They usually
represented a python with a shortened tail and a big head.

Features
1. Easy to Use : Python has few keywords, simple structure, and a clearly
defined syntax. So It is very easy to use.
2. High Level Language : Python is high level programming language.
3. Interpreted : Python code is interpreted by interpreter line by line at a
time. Python interpreter converts the python code to the bytecode. These
bytecodes are created by a compiler present inside the interpreter. Interpreter
first compiles the python code to the byte code which is also called as the
intermediate code, then the code is used to run on the virtual machine. In the
virtual machine, the library modules of the python get added and then the code
is ready to run on a machine. Steps for interpretation of python source code:
Page :3

1. Source code: Python Code


2. Compiler: Enters inside the compiler to generate the bytecode
3. Bytecode: Intermediate code or low-level code
4. Virtual Machine: Here the code gets the support from the library modules.
Python is an interpreted language, which means the source code of a Python
program is converted into bytecode that is then executed by the Python virtual
machine. This bytecode is saved in the file named same as the source file but
with a different extension named as “pyc”.
4. Platform Independent : It is platform independent programming
language, its code easily run on any platform such as Windows, Linux, Unix ,
Macintosh etc. Thus, Python is a portable language.
5. Open Source : Python is open source so you can freely download and
use. Python is distributed as open-source software. Open-source software (OSS)
is software that is distributed with source code that may be read or modified by
users. The OSS community generally agrees that open-source software should
meet the following criteria:
 The program must be freely distributed
 Source code must be included with the program
 Anyone must be able to modify the source code
 Modified versions of the source code may be redistributed
A large programming community is actively involved in the development and
support of Python libraries for various applications such as web frameworks,
mathematical computing and data science. Python source code is available
under the GNU General Public License (GPL).
6. GUI Programming : You can design Graphical user interfaces using
Python.
7. Large standard library: Python comes with a large standard library that
includes codes and functions which we can use while writing code in Python.
8. Automatic memory management: Python supports automatic memory
management which means the memory is cleared and freed automatically.
9. Database API : A standard DB-API( Database Application Programming
Interface) for database connectivity has been defined in Python. It can be
enabled using any data source (Oracle, MySQL, SQLite etc.) as a backend to the
Python program for storage, retrieval and processing of data.
Versions
Python 1.0 was released in November 1994.
Python 2.0 was released in 2000
Page :4

Python 3.0 was released in 2008 etc


Latest versions
 Python 2.0 - 16 Oct 2000
 Python 2.1 - 17 Apr 2001
 Python 2.2 - 21 Dec 2001
 Python 2.3 - 29 Jul 2003
 Python 2.4 - 30 Nov 2004
 Python 2.5 - 19 Sep 2006
 Python 2.6 - 01 Oct 2008
 Python 2.7 - 03 Jul 2010
 Python 3.0 - 03 Dec 2008
 Python 3.1 - 27 Jun 2009
 Python 3.2 - 20 Feb 2011
 Python 3.3 - 29 Sep 2012
 Python 3.4 - 16 Mar 2014
 Python 3.5 - 13 Sep 2015
 Python 3.6 - 23 Dec 2016
 Python 3.7 - 27 Jun 2018
 Python 3.8 - 14 Oct 2019
 Python 3.9 - 05 Oct 2020
Two major Python versions are Python 2 and Python 3. Both are quite
different.
Python Libraries
A Python library is a collection of modules. It is written in C, and handles
functionality like I/O and other core modules. More than 200 core modules is
available with standard library.
Page :5

 Matplotlib: Matplotlib helps with data analyzing, and is a numerical


plotting library.
 Pandas: Pandas provides fast, expressive, and flexible data structures to
easily work with structured and time-series data.
 NumPy: Numpy is considered as one of the most popular machine
learning library in Python.
 Pyglet: Pyglet is an excellent choice for an object-oriented programming
interface in developing games.
 PyGame: PyGame provides an extremely easy interface to the Simple
Directmedia Library (SDL) platform-independent graphic, audio, and
input libraries.
 Pillow : Pillow is a friendly Python Imaging Library for manipulating
images
 Django : Django is a high-level Python web framework that enables rapid
development of secure and maintainable websites.
Application Areas of Python
1. Web Applications
Web application framework libraries like django, Pyramid, Flask etc. make it
very easy to develop and deploy simple as well as complex web applications.
These frameworks are used extensively by various IT companies.
2. Game Development
Python is also used in the development of interactive games. PyGame which
provides functionality and a library for game development.
3. Data Science and Data Visualization
Huge amount of data is being generated today by web applications, mobile
applications and other devices. Companies need business insights from this data.
Python libraries like NumPy, Pandas and Matplotlib are extensively used in the
process of data analysis, including the collection, processing and cleansing of
data sets, applying mathematical algorithms and generating visualizations for
the benefit of users.

You can even visualize the data libraries such as Matplotlib, Seaborn, which are
helpful in plotting graphs and much more.
Page :6

4. Desktop GUI
Python can be used to program desktop applications. It provides
the Tkinter library that can be used to develop user interfaces.
5. Web Scraping Applications
Python can be used to pull a large amount of data from websites which can then
be helpful in various real-world processes such as price comparison, job listings,
research and development and much more. Python has a library called
BeautifulSoup which can be used to pull such data and be used accordingly.
6. Business Applications
Business Applications are different than our normal applications covering
domains such as e-commerce, ERP and many more. They require applications
which are scalable, extensible and easily readable and Python provides us with
all these features. Platforms such as Tryton can be used to develop such business
applications.
7. Audio and Video Applications
Python can be used to develop applications that can multi-task and also output
media. Video and audio applications such as TimPlayer, Cplay have been
developed using Python libraries and they provide better stability and
performance compared to other media players. MoviePy is one of the library file
for reading and writing all audio and video formats.
8. Embedded Applications
Python is based on C which means that it can be used to create Embedded
C software for embedded applications. This helps us to perform higher-level
applications on smaller devices which can compute Python.

The most well-known embedded application could be the Raspberry Pi which


uses Python for its computing. It can be used as a computer or like a simple
embedded board to perform high-level computations.
9. Image Processing
Page :7

Library file for image processing is Pillow, OpenCV etc. The OpenCV library is
commonly used for face detection and gesture recognition.
10. Machine Learning and Artificial Intelligence
Machine Learning and Artificial Intelligence are the most promising careers for
the future. We make the computer learn based on past experiences through the
data stored, create algorithms which makes the computer learn by itself.
Libraries for this are Pandas, NumPy etc. Some of the real-world applications
of machine learning include medical diagnosis, statistical arbitrage, sales
prediction etc.
Google, Facebook, Netflix, Dropbox etc use python in their applications.
IDE
An IDE (or Integrated Development Environment) is a program dedicated to
software development. IDEs contains several tools like :
 An editor designed to handle code (with, for example, syntax highlighting
and auto-completion)
 Build, execution, and debugging tools
The different IDE‟e for python are IDLE, Jupyter Notebook etc.
IDLE
IDLE (Integrated Development and Learning Environment) is an integrated
development environment (IDE) for Python. Guido Van Rossum named Python
from comedy series named Monty Python while the name IDLE was chosen to
pay tribute to Eric Idle, who was one of the Monty Python's founding
members. The Python installer for Windows contains the IDLE module by
default. IDLE is not available by default in Python distributions for Linux. It
needs to be installed using the respective package managers. IDLE can be
used to execute a single statement just like Python Shell and also to create,
modify, and execute Python scripts. IDLE provides a fully-featured text editor
to create Python script that includes features like syntax highlighting,
autocompletion, and smart indent. It also has a debugger with stepping and
breakpoints features.
To start an IDLE interactive shell, search for the IDLE icon in the start menu
and double click on it. This will open IDLE, where you can write and execute
the Python scripts. The shell is the default mode of operation for Python IDLE.
Page :8

This is a blank Python interpreter window which is used to execute a single


Python command and display the result. it is not advisable to write multiple
lines of code that have functions/classes in the IDLE shell. To write multiple
lines select File option of IDLE and click on New File.
Creating a File
To start a new Python file, select File → New File from the menu bar. This will
open a blank file in the editor.

There are also two numbers in the bottom right corner of the window:
1. Ln: shows the line number that your cursor is on.
2. Col: shows the column number that your cursor is on.
These numbers helps to find errors more quickly.
Enter multiple statements and save the file with extension .py using File ->
Save. Example Prg1.py. It is easy to write, test and run Python scripts in
IDLE. A Python script is a collection of commands in a file designed to be
executed like a program.
Executing a File
To execute a file in IDLE, simply press the F5 key on your keyboard. You can
also select Run → Run Module from the menu bar. Both option will restart the
Page :9

Python interpreter and then run the code that you‟ve written with a fresh
interpreter. To interrupt the execution of your program, then you can press
ctrl+c in the interpreter.
Automatic Indentation
IDLE will automatically indent your code when it needs to start a new block.
This usually happens after you type a colon (:). When you hit the enter key after
the colon, your cursor will automatically move over a certain number of spaces
and begin a new code block. You can configure how many spaces the cursor
will move in the settings, but the default is the standard four spaces. The
developers of Python agreed on a standard style for well-written Python code,
and this includes rules on indentation, whitespace, and more. This standard style
was formalized and it is now known as PEP 8.
Code Completion and Call Tips
Code completion helps you save typing time by trying to finish your code for
you. Python IDLE has basic code completion functionality. It can only
autocomplete the names of functions and classes. To use auto completion in the
editor, just press the tab key after a sequence of text. Python IDLE will also
provide call tips. A call tip is like a hint for a certain part of your code to help
you remember what that element needs. After you type the left parenthesis to
begin a function call, a call tip will appear if you don‟t type anything for a few
seconds. The call tip will display as a popup note, reminding you how to append
to a list.
Debugging in IDLE
A bug is an unexpected problem in your program. Python IDLE provides some
basic tools that will helps you to debug your programs.
Interpreter DEBUG Mode
If you want to run your code with the built-in debugger, select Debug →
Debugger from the Python IDLE menu bar. In the interpreter, you should
see [DEBUG ON] appear just before the prompt (>>>), which means the
interpreter is ready and waiting. When you execute your Python file, the
debugger window will appear. In the debugging window, you can inspect the
values of your local and global variables as your code executes.
Checkboxes in the debug window
1. Globals: your program‟s global information
2. Locals: your program‟s local information during execution
3. Stack: the functions that run during execution
4. Source: your file in the IDLE editor
Page :10

Breakpoints
A breakpoint is a line of code that you‟ve identified as a place where the
interpreter should pause while running your code. They will only work
when DEBUG mode is turned on, so make sure that you‟ve done that first. To
set a breakpoint, right-click on the line of code that you wish to pause. This will
highlight the line of code in yellow as a visual indication of a set breakpoint.
You can set as many breakpoints in your code as you like. To undo a
breakpoint, right-click the same line again and select Clear Breakpoint. Once
you‟ve set your breakpoints and turned on DEBUG mode, you can run your
code as you would normally. The debugger window will pop up, and you can
start stepping through your code manually.
Errors and Exceptions
Python IDLE also provides a tool called a stack viewer. You can access it under
the Debug option in the menu bar. This tool will show you the trace back of an
error as it appears on the stack of the last error or exception that Python IDLE
encountered while running your code. When an unexpected error occurs, you
might find it helpful to take a look at the stack.
Customizing Python IDLE
To access the customization window, select Options → Configure IDLE from
the menu bar. To preview the result of a change you want to make, press Apply.
When you‟re done customizing Python IDLE, press OK to save all of your
changes. If you don‟t want to save your changes, then simply press Cancel.
There are 5 areas of Python IDLE that you can customize:
1. Fonts/Tabs
2. Highlights
3. Keys
4. General
5. Extensions
Fonts/Tabs
The first tab allows you to change things like font color, font size, and font
style.
Highlights
The second customization tab will let you change highlights. Python
IDLE allows you to fully customize the appearance of your Python code. It
comes pre-installed with three different highlight themes:
1. IDLE Day
2. IDLE Night
Page :11

3. IDLE New
You can select from these pre-installed themes or create your own custom
theme from the window:
Keys
The third customization tab lets you map different key presses to actions,
also known as keyboard shortcuts. User can create your own keyboard
shortcuts, or you can use the ones that come with IDLE.
General
The fourth tab of the customization is used to change the window size and
whether the shell or the file editor opens first when you start Python IDLE.
Extensions
The fifth tab of the customization window lets you add extensions to Python
IDLE. Extensions allow you to add new features to the editor and the interpreter
window.
Python Interpreter: Shell/REPL
Python is an interpreter language. It means it executes the code line by line.
Python provides a Python Shell, which is used to execute a single Python
command and display the result. It is also known as REPL (Read, Evaluate,
Print, Loop), where it reads the command, evaluates the command, prints the
result, and loop it back to read the command again. To run the Python Shell,
open the command prompt on Windows write „python‟ and press enter. A
Python Prompt comprising of three greater-than symbols >>> appears, as
shown below.

Python Shell/REPL
Now, you can enter a single statement and get the result. For example, enter a
simple expression like 3 + 2, press enter and it will display the result in the
next line, as shown below.
Page :12

Execute Python Script


As you have seen above, Python Shell executes a single statement. To execute
multiple statements, create a Python file with extension .py, and write Python
scripts (multiple statements).
Writing and executing python scripts
A programming language is a language used to write set of instructions to
perform a task and it is compiled. A scripting language is a programming
language that uses an Interpreter to translate its source code. The interpreter
reads and executes each line of code one at a time, just like a SCRIPT for a play.
Python uses an interpreter to translate and run its code and that's why it's called
a scripting language
A Python script is a file which contains commands, functions and various
imported modules. Python interpreter is responsible for executing the Python
scripts. Python interpreter is a piece of software which works between
the Python program and computer hardware . Different ways to run Python
Script are
1. Interactive Mode
2. Command Line/prompt
3. IDE
Interactive Mode
In Interactive Mode, you can run your script line by line in a sequence. To
enter in an interactive mode, you will have to open Command Prompt on your
windows machine and type „python‟ and press Enter.
Page :13

Interactive mode
Example of working in interactive mode
Page :14

Exit() is used to return to command prompt.

Command Prompt
Python scripts files can also run using command line/prompt. To include
multiple lines within a script open Notepad or any text editor. After entering
script save the file with extension .py(example prg1.py saved in e:).
To run this „.py‟ file in command line, we have to write „python‟ keyword
before the file name in the command prompt.

IDE
IDE allows to execute single line or multiple lines. IDLE is the default IDE for
Windows OS. To start a new Python file, select File → New File from the menu
bar. This will open a window which contains ‘Format’ and ‘Run’ menu
instead of ‘Shell’ and ‘Debug’ menu. After entering sequences save the file
with extension .py. To execute a file in IDLE, simply press the F5 key on your
keyboard. You can also select Run → Run Module from the menu bar. Both
option will restart the Python interpreter and then run the code that you‟ve
written with a fresh interpreter.
Page :15

Data types
Data types are the classification or categorization of data items. In Python
programming everything is treated as object. Data types are actually classes
and variables are instance (object) of these classes. Following are the standard
or built-in data type of Python:
1. Numeric
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
1. Numeric
Numeric data type represent the data which has numeric value. Numeric value
can be integer, floating number or complex numbers. These values are defined
as int, float and complex class in Python.
1.1 Integers – This value is represented by int class. It contains positive or
negative whole numbers (without fraction or decimal). In Python there is no
limit to how long an integer value can be.
 The following strings can be prepended to an integer value to indicate a
base other than 10:
Prefix Interpretation Base
0b (zero + lowercase letter 'b') Binary 2
0B (zero + uppercase letter 'B')
0o (zero + lowercase letter 'o') Octal 8
0O (zero + uppercase letter 'O')
0x (zero + lowercase letter 'x') Hexadecimal 16
0X (zero + uppercase letter 'X')
Example:
>>> print(0o10)
8
>>> print(0x10)
16
>>> print(0b10)
2
All the above data types are belongs to int class.
1.2 Float – This value is represented by float class. It is a real number with
floating point representation. It is specified by a decimal point.
>>> type(4.2)
Page :16

<class 'float'>
1.3 Complex Numbers – Complex number is represented by complex class. It
is specified as (real part) + (imaginary part)j. For example – 2+3j
Example:
>>> type(2+3j)
<class 'complex'>
>>>n=12+5J
>>>print(n)
(12+5J)
2. Sequence Type
In Python, sequence is the ordered collection of similar or different data types.
Sequences allows to store multiple values in an organized and efficient fashion.
There are several sequence types in Python –
 String
 List
 Tuple
2.1 String
In Python, Strings are arrays of bytes representing Unicode characters. In
python there is no character data type, a character is a string of length one. It is
represented by str class. String literals are given using Single quotes, double
quotes and triple double quotes.
Example
>>> course=‟bca‟
>>>print(course)
bca
>>> type(course)
<class 'str'>
>>> course=”bca”
>>>print(course)
bca
>>> type(course)
<class 'str'>

>>> course=”””Semester III


…Bca
…Python”””
>>>print(course)
Page :17

Semester III
Bca
Python
>>> type(course)
<class 'str'>
2.2 List
Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of
the same type.
2.3 Tuple
Tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be
modified after it is created. It is represented by tuple class.
3.Boolean
Boolean data type can store either True or False:
>>>grade=True
>>>print(grade)
True
>>> type(grade)
<class 'bool'>
4. Set
Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
5. Dictionary
Dictionary in Python is an unordered collection of data values, used to store
data values like a map, which unlike other Data Types that hold only single
value as an element, Dictionary holds key:value pair. Key-value is provided in
the dictionary to make it more optimized. Each key-value pair in a Dictionary
is separated by a colon :, whereas each key is separated by a „comma‟.
Comments
Comments can be used to explain Python code. Comments can be used to make
the code more readable. Comments can be used to prevent execution when
testing code. Two types of comments are
Single-line comments begins with a hash(#) symbol and is useful in
mentioning that the whole line should be considered as a comment until the end
of line.
Page :18

Example
#This is a comment
print("Hello, World!") # output
A Multi line comment is useful when we need to comment on many lines. In
python, triple double quote("""and single quote(„ „ „)are used for multi-line
commenting.
Example
"""a=10
b=10"""
a=20
print(a)
Python Tokens
Python tokens are keywords, identifiers, literals and operators.
Identifiers
Identifiers represents user-defined names, variables, modules, and other objects.
Rules
 An identifier can be a sequence of lower case (or) upper case (or) integers
(or) a combination of any.
 The identifier name should start with the lower case or upper case or _. (It
must not start with digits)
 The identifier name should not be a keyword.
 Only Underscore (_) is allowed to use as a special character in identifier
names.
 The length of the identifier name should not be more than 79 characters
 Example: name,roll_no, _salary
Keywords
These are the reserved words with special meaning. User cannot use them as
constants or variables or any other identifier names.
and exec Not as finally
or assert for pass break
from print class global raise
continue if return def import
try del in while elif
is with else lambda yield
excep
Variables
Page :19

A variable is a name given to a memory location. It is the basic unit of storage


in a program. The value stored in a variable can be changed during program
execution. Python variables do not need declaration before using them. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.The operand to the left of the
= operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.
Rules for creating variables in Python:
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
 Variable names are case-sensitive (name, Name and NAME are three
different variables).
 The reserved words(keywords) cannot be used naming the variable.
Literals
Literals are used to define the data as a variable (or ) constants. Python has 6
literals tokens.
String :
The string is a sequence of characters defined between quotes. (single double
and tripple double quotes are used to define the string literals.).
Na-„BCA‟, na=”BCA”, na=”””BCA”””
Numeric:
These are immutable (unchangeable ) literals. We basically have 3 different
numerical types namely integer, float, and complex
a=10
b=10.50
c=12+5J
Boolean:
This has only two values either True or False.
status=True
Collection literals :
A collection literal is a syntactic expression form that evaluates to an aggregate
type such as array list (or) Map. Python supports 2 types of collection literal
tokens
Page :20

List Literals :
Lists holds the heterogeneous data types. List is the most versatile data type in
python. Python literals are separated by a comma in []. If a comma is not
provided between the values, the output does not contain spaces
Example :
List = [„a‟,‟b‟,‟c‟]
Print(list)
Output :
[„a‟,‟b‟,‟c‟]
Tuples :
Tuples were similar to list. Tuples cannot change the values. Beside, tuples are
enclosed in parenthesis. whereas lists are enclosed in square brackets.
tuple =('abcd',786,2.23,'john',70.2)
Operators
An Operator is a symbol used to perform an action. Different operators are
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Arithmetic Operators
Assume variable a holds the value 2 and variable b holds the value 4, then
Operator Description Example
+ Addition Adds values on either side of the a + b = 6
operator.
- Subtraction Subtracts right hand operand from a –b = -2
left hand operand.
* Multiplication Multiplies values on either side of a * b = 8
the operator
/ Division Divides left hand operand by right a/b = 0.5
hand operand
% Modulus Divides left hand operand by right a%b=2
hand operand and returns
remainder
** Exponent Performs exponential (power) a**b =16 (2*2*2*2)
Page :21

calculation on operators
// Floor Division The division of operands where a=5,b=4
the result is the quotient in which a/b=1.25
the digits after the decimal point a//b=1
are removed
Relational/Comparison Operators
These operators compare the values on either side of them and decide the
relation among them. They are also called Relational operators. Assume variable
a holds the value 10 and variable b holds the value 20
Operator Description Examp
== Equal to If values of two (a == b) - False
operands are equal, then 10==20
the condition returns
True otherwise False
!= Not Equal To If values of two (a!=b) – True
operands are not equal, 10!=20
then the condition
returns True otherwise
False
> Greater than If the value of left (a > b) False
operand is greater than 10>20
the value of right
operand, then condition
returns True otherwise
False.
< Less than If the value of left (a < b) True
operand is less than the 10<20
value of right
operand, then condition
becomes true.
>= If the value of left (a >= b) False
operand is greater than 10>=20
or equal to the
value of right operand,
then condition becomes
true.
<= If the value of left (a <= b) True
Page :22

operand is less than or 10<=20


equal to the value
of right operand, then
condition becomes true.
Assignment Operator
Assignment operator is used to assign a value from right side to left side. Right
side can be value, constant or expression.
Operator Description Example
= (Assignment) Assigns values from right a=10
side operands to left side b=5
operand c = a + b assigns res=a+b - 15
value of a + b into c
+= (Addition AND) It adds right operand to a=10
the left operand and a+=5 - 15
assign the result to left
operand.
-= (Subtract AND) It subtracts right operand a=10
from the left operand and a-=5 - 5
assign the result to left
operand
*= (Multiply AND) It multiplies right a=10
operand with the left a*=5 - 50
operand and assign the
result to left operand
/= (Divide AND) It divides left operand a=10
with the right operand a/=5 - 2.0
and assign the result to
left operand
%= (Modulus AND) It takes modulus using a=10
two operands and assign a%=5 - 0
the result to left operand
**= (Exponent AND) Performs exponential a=10
(power) calculation on a**=3 - 1000
operators and assign
value to the left operand
//= (Floor Division) It performs floor division a=10
on operators and assign a//=3 - 3
Page :23

value to the left operand

Logical Operators
Logical operators are used to combine two or more relational expressions. It
returns a Boolean value True or False
Operator Description Example
and (Logical AND) If both the operands are a=10
true then condition b=20
. becomes true otherwise b>==10 and b==20
false True
or (Logical OR) If any of the two a=10
operands are true then b=20
condition becomes true. a>=10 or b==20
True

not (Logical NOT) Used to reverse the


logical state of its
operand.
Bitwise Operators
In Python, bitwise operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then operations are
performed on bit by bit. Then the result is returned in decimal format. Python
bitwise operators work only on integers. Pyhton's built-in function bin() can be
used to obtain binary representation of an integer number. The following
Bitwise operators are supported by Python language
Operator Description Example A=10
B=4
& Binary AND Operator copies a bit to the (a & b) 0000 1010
result, if it exists in both 0000 0100
operands 0000 0000 =0
| Binary OR It copies a bit, if it exists in (a | b) 0000 1010
either operand 0000 0100
0000 1110 =14
^ Binary XOR It copies the bit ,if it is set in (a ^ b) 0000 1010
one operand but not both. 0000 0100
0000 1110=14
.~ Binary Ones Bitwise complement of n will (~a) 0000 1010
Page :24

Complement be -(n+1). ~ 0000 1010=


+ 1
-0000 1011
=-11
<< Binary Left The left operand‟s value is a << = 2 0000 1010<<2
Shift moved left by the number of 0010 1000=40
bits specified by the right
operand.
>> Binary Right The left operand‟s value is a >> = 2 0000 1010>>2
Shift moved right by the number of 0000 0010=2
. bits specified by the right
operand
Membership Operators
Python‟s membership operators test for membership in a sequence, such as lists,
or tuples. -
Operator Description Example
in Evaluates to true, if it finds a a=3
variable in the specified sequence b=[1,2,3]
and false otherwise. a in b True
not in Evaluates to true, if it does not a=10
find a variable in the specified b=[1,2,3]
sequence and false otherwise a not in b True
Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description Example
is Evaluates to true if the variables a=10
on either side of the operator b=”bca”
point to the same object and false a is b False
otherwise.
is not Evaluates to false if the variables a=10
on either side of the operator b=”bca”
point to the same object and true a is not b True
otherwise
Operator Precedence and Associativity of Python Operators
The combination of values, variables, operators, and function calls is termed as
an expression. Each operator has a precedence. This precedence is used to
determine how an expression involving more than one operator is evaluated.
Page :25

The operator with high precedence is evaluated first. Associativity is the order
in which an expression is evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right associativity. Assignment
and exponent have right to left associativity. For example, multiplication and
floor division have the same precedence. Hence, if both of them are present in
an expression, the left one is evaluated first.
Operatorr Name Associativity

() Parenthesis Left to right


** Exponent Right to left
~ Bitwise NOT Left to right
Multiplication, Division, Modulo,
*, /, %, // Left to right
Floor Division
+, – Addition, Subtraction Left to right
>>, << Bitwise right and left shift Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
==, !=, >, <, >=, <= Comparison Left to right
=, +=, -=, *=, /=, %=,
Assignment Right to left
**=, //=
is, is not Identity Left to right
In, not in Membership Left to right
and, or, not Logical Left to right
In the above-given table, only exponent and assignment operators have the right
to left associativity. All the other operators follow left to right associativity.
Page :26

Variables
Python has no command for declaring a variable. Variables are created when
you assign a value to it. Data type of variable is determined based on data given
by user. So Python is known as dynamically typed language.
Example
x= 5
y = "Hello, World!"
Python allows you to assign a single value to several variables simultaneously.
Example
a =b =c =1
Here, an integer object is created with the value 1, and all the three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables.
a,b,c =1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and
b and one string object with the value "john" is assigned to the variable c
Statement
A statement is an instruction that the Python interpreter can execute. We have
normally two basic statements, the assignment statement and the print statement.
Some other kinds of statements that are if statements, while statements, and for
statements generally called as control flows.
Example :
An assignment statement creates new variables and gives them values:
>>> x=10
Page :27

Expression
An expression is a combination of variables, operators, values. An expression is
evaluated using assignment operator.
sum=a+b+c
avg=sum/3
Lines and Indentation
Python does not use braces({}) to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation.
Example
If True:
print("Answer")
print("True")
else:
print"(Answer")
print("False")
in Python all the continuous lines indented with the same number of spaces
would form a block.
Type Casting in python
The process of converting the value of one data type (integer, string, float, etc.)
to another data type is called type conversion. Python has two types of type
conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to
another data type.
Example 1
a=10
b=20.5
res=a+b
print(res) - 30.5 //float number
Example 2
a=10
b=20+5j
res=a+b
print(res) - 30+5j # Complex number
Explicit Type Conversion
Page :28

In Explicit Type Conversion, users convert the data type of an object to required
data type. This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax :
<required_ datatype><expression>
Typecasting can be done by assigning the required data type function to the
expression.
Methods for type casting
1. 1.int(a,base) : This function converts any data type to integer. „Base‟
specifies the base in which string is if data type is string.
a=”12”
print(int(a)) – 12
a=”1010”
c=int(a,2)
print(c) -10
2. float() : This function is used to convert any data type to a floating point
number.
a=10
print((float(a))
10.0
3. ord() : This function is used to convert only a single character to integer.
a=”6”
print(ord(a)) - 54
4. hex() : This function is to convert integer to hexadecimal string.
a=”17”
print(hex(a)) – 0x11
5. oct() : This function is to convert integer to octal string.
a=”17”
print(oct(a)) – 0o21
6. str() : Used to convert integer into a string.
n=12
print(str(n))
7. complex(real,imag) : : This function converts real numbers to
complex(real,imag) number.
a=complex(10,5)
print(a) - (10+5j)
Page :29

8. chr(number) : : This function converts number to its corresponding


ASCII character.
n=65
print(chr(n)) – A
Eval()
eval is a built-in- function used in python. eval function parses the expression
argument and evaluates it as a python expression. In simple words, the eval
function evaluates the “String” like a python expression and returns the result as
an integer.
Syntax:
eval(expression, [globals[, locals]])
The arguments or parameters of eval function are strings, also optionally global
and locals can be used as an argument inside eval function, but the globals must
be represented as a dictionary and the locals as a mapped object. The return
value would be the result of the evaluated expression.
Example:
a=”10+20+30”
res=eval(a)
print(“Result of string expression using eval():”,res)
output
Result of string expression using eval():60
Type casting using eval()
eval() is used to perform the type casting automatically.
Example
Without using eval()
a=int(input(“Enter no:”)) # input() reads number and treats it as a string. This
string is type casted to int.
a=float(input(“Enter no:”)) # input() reads number and treats it as a string. This
string is type casted to int.
using eval()
a=eval(input(“Enter no:”)) #given no is 10
print(a) #10
print(type(a)) # <class „int‟>
a=eval(input(“Enter no:”)) #given no is 10.50
print(a) #10.5
print(type(a)) # <class „float‟>
Input functions of Python 2.x
Page :30

Python provides us with two inbuilt functions to read the input from the
keyboard.
1.raw_input(prompt) : This function works in older version (like Python 2.x).
This function takes exactly what is typed from the keyboard, convert it to string
and then return it to the variable in which we want to store.
Syntax:raw_input(prompt)
Example
na= raw_input("Enter your name : ")
Here, na is a variable which will get the string value, typed by user during the
execution of program. Typing of data for the raw_input() function is terminated
by enter key. We can use raw_input() to enter numeric data also. In that case we
use typecasting.
2. input(prompt) : This function first takes the input from the user and then
evaluates the expression. Python automatically identifies whether user entered a
string or a number or list.
Syntax:input(prompt)
Example:
na=input(“Enter name:”)
Input functions of Python3.x
input(prompt) : Python provides the function input() to read data from user.
input has an optional parameter, which is the prompt string. If the input function
is called, the program flow will be stopped until the user has given an input and
has ended the input with the return key. The text of the optional parameter, i.e.
the prompt, will be printed on the screen. Whatever you enter as input, input
function convert it into a string. if you enter an integer value
still input() function convert it into a string. The given input is known as
raw_input and the eval function is needed to convert into another
datatype(typecasting)
syntax:input(prompt)
Example
#input()
na=input("Enter name:")
mark1=eval(input("Enter mark1:"))
mark2=eval(input("Enter mark2:"))
mark3=eval(input("Enter mark3:"))
total=mark1+mark2+mark3
print("Name:",na);
Page :31

print("Mark1",mark1);
print("Mark2:",mark2);
print("Mark3:",mark3);
print("Total:",total);
output
Enter name:Anu
Enter mark1:23
Enter mark2:34
Enter mark3:45.5
Name: Anu
Mark1 23
Mark2: 34
Mark3: 45.5
Total: 102.5

Output function
print() : print() is used to display output on the screen.
Syntax: print(value(s), sep= „ „, end = „\n‟, file=file, flush=flush)
value(s) : Any value, and as many as you like. All will be converted to string
before printed.
sep=’separator’ : (Optional) Specify how to separate the objects, if there is
more than one. Default is space.
end=’end’: (Optional) Specify what to print at the end. Default is new line „\n‟
file : (Optional) An object with a write method. Default is sys.stdout(monitor)
flush : (Optional) A Boolean, specifying if the output is flushed (True) or
buffered (False). Default: False
Example
#usage of print()
print("hello","welcome")
age=20
print("Your age is",age)
Page :32

course="bca"
print("Your age is",age,"Course is",course)
print("Your age is",age,"Course is",course,sep="--") #using separator
print("Your age is",age,"Course is",course,sep="*",end="\t",flush="true")
#using separator and end
print("Your age is",age,"Course is",course,end="----------") #using end
print("completed")
output
hello welcome
Your age is 20
Your age is 20 Course is bca
Your age is--20--Course is--bca
Your age is*20*Course is*bca Your age is 20 Course is bca----------
completed
type() function
type() method returns class type of the argument(object) passed as parameter.
type() function is mostly used for debugging purposes.
Syntax :
type(object)
Example
a=20
b=34.5
c=20+5j
na="bca"
print("Type of a=",type(a))
print("Type of b=",type(b))
print("Type of c",type(c))
output
Type of a= <class 'int'>
Type of b= <class 'float'>
Type of c <class 'complex'>
*************

You might also like