0% found this document useful (0 votes)
15 views17 pages

Ge3151 Unit Ii

The document provides an overview of Python programming, covering data types, expressions, and statements, as well as the characteristics of a good program. It explains the Python interpreter, its features, and the differences between interactive and script modes, along with various data types such as integers, floats, strings, lists, tuples, sets, and dictionaries. Additionally, it highlights the advantages of Python and its applications in various domains.

Uploaded by

SHEEBA M C CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views17 pages

Ge3151 Unit Ii

The document provides an overview of Python programming, covering data types, expressions, and statements, as well as the characteristics of a good program. It explains the Python interpreter, its features, and the differences between interactive and script modes, along with various data types such as integers, floats, strings, lists, tuples, sets, and dictionaries. Additionally, it highlights the advantages of Python and its applications in various domains.

Uploaded by

SHEEBA M C CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

1

UNIT II

DATA, EXPRESSIONS, STATEMENTS

Python interpreter and interactive mode; values and types: int, float, Boolean, string, and list;
variables, expressions, statements, tuple assignment, precedence of operators, comments;
Illustrative programs: exchange the values of two variables, circulate the values of n variables,
distance between two points.

Introduction
Programming:
Program: A program is a sequence of instructions that specifies how to perform a computation.
The computation might be something mathematical, such as solving a system of equations or
finding the roots of a polynomial, but it can also be a symbolic computation, such as searching
and replacing text in a document or something graphical, like processing an image or playing a
video.
There are few basic instructions appear in every programming language:
• input: Get data from the keyboard, a file, or some other device.
• output: Display data on the screen or send data to a file or other device.
• math: Perform basic mathematical operations like addition and multiplication.
• conditional execution: Check for certain conditions and execute the appropriate code.
• repetition: Perform some action repeatedly, usually with some variation.

Characteristics of a Good Program: The following important characteristics should be followed


while writing a program.
• Accuracy
• Clarity
• Efficiency
• Modularity
• User Friendly
• Reliable
• Portable

Programming language:
High-level languages are much easier to write and more problem oriented. Low-level
languages sometimes referred to as “machine languages” or “assembly languages. Compiler is
the software used to translate a complete program written in a high-level language into low level
language. The high-level program is called the source code, and the translated program is called
the object code or the executable. Once a program is compiled, we can execute it repeatedly
without further translation. Interpreter is also software; it reads the source code line by line and
converts them into object code.

Bug: An error in a program.


Debugging: The process of finding and removing any of the three kinds of programming
errors.
Syntax: The structure of a program.
Syntax error: An error in a program that makes it impossible to parse (and therefore
impossible to interpret).
Exception: An error that is detected while the program is running.

Unit II Data Types, Expressions, Statements 1


2

Semantics: The meaning of a program


Semantic error: An error in a program that makes it do something other than what the
programmer intended

PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-level
programming language. It was created by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in Netherlands during 1985- 1990. Python got its name from
“Monty Python’s flying circus”, which is a British comedy series. Python was released in the year
2000.

Features:
❖ Python is interpreted: Python is processed at runtime by the interpreter. No need to
compile Python program before executing it.
❖ Python is Interactive: We can use Python prompt and interact with the interpreter directly
to write our programs.
❖ Python is Object-Oriented: Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
❖ Python is a Beginner's Language: Python is a great language for the beginner- level
programmers and supports the development of a wide range of applications.
❖ Easy-to-learn: Python is clearly defined and easily readable. The structure of the program
is very simple. It uses few keywords.
❖ Easy-to-maintain: Python's source code is fair.
❖ Portable: Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
❖ Interpreted: Python is processed at runtime by the interpreter. So, there is no need to
compile a program before executing it. We can simply run the program.
❖ Extensible: Programmers can embed python within their C, C++, Java script, ActiveX,
etc.
❖ Free and Open Source: Anyone can freely distribute it, read the source code, and edit it.
❖ High Level Language: When writing programs, programmers concentrate on solutions
of the current problem, no need to worry about the low-level details.
❖ Scalable: Python provides a better structure and support for large programs than shell
scripting.

Application:
❖ Embedded scripting language
❖ 3D software
❖ Web Development
❖ Image processing and graphic Design Application
❖ GUI based desktop application
❖ Science and Computational application
❖ Games
❖ Enterprise and business applications
❖ Operating System
❖ Language Development
❖ Prototyping
❖ Network Programming

Companies Used:
Unit II Data Types, Expressions, Statements 2
3

❖ Bit Torrent file sharing


❖ Google search engine, YouTube
❖ Intel, Cisco, HP, IBM
❖ i–Robot
❖ NASA
❖ Facebook, Drop box, etc.,

2.1. PYTHON INTERPRETER AND INTERACTIVE MODE:


Interpreter: To execute a program in a high-level language by translating it one line at a time.
Compiler: To translate a program written in a high-level language into a low-level language all
at once, in preparation for later execution.
Python is an example of a high-level language; some of the other high-level languages are
C, C++, Perl, and Java. Programs written in a high-level language have to be processed before
they can run. Python is considered an interpreted language because Python programs are executed
by an interpreter.

Advantages of python:
• Readability: If the software has a highly readable code, then it is easier to maintain.
• Portability: Platform independent.
• Vast support of libraries: It has large collection of in-built functionalities.
• Software integration: It can easily extend, communicate and integrate with other
languages.
• Developer productivity: It is a dynamically typed language i.e., no need to declare variables
explicitly.
• Python programs run immediately i.e., without taking much time to link and compile.

IDLE: Integrated Development and Learning Environment.


The IDLE tool is included in python’s installation package. It offers more efficient platform for
write code and work interactively with python. We can access IDLE on the same folder or
command line icon or on the start menu. By clicking on the IDLE icon, it displays the python shell
window. It comprises of python shell (allows users to access different features of IDLE through
its drop-down menu) and python editor (allows us to work in script mode).
Features of IDLE:
❖ Multi-window text editor with syntax highlighting.
❖ Auto completion with smart indentation.
❖ Python shell to display output with syntax highlighting.

Python Interpreter: It is a program that reads and executes Python code. It uses 2 modes of
Execution.
1. Interactive mode
2. Script mode

1. Interactive mode: Interactive Mode, as the name suggests, allows us to interact with OS.
When we type Python statement, interpreter displays the result(s) immediately. Eg: >>>
1+1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for us to enter code.
If we type 1 + 1, the interpreter replies 2.

Unit II Data Types, Expressions, Statements 3


4

Eg: >>> print ('Hello, World!')


Hello, World!
Advantages:
• Python, in interactive mode, is good enough to learn; experiment or explore.
• Working in interactive mode is convenient for beginners and for testing small pieces of
code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them.

2. Script mode: In script mode, we type python program in a file and then use interpreter to
execute the content of the file. Scripts can be saved to disk for future use. Python scripts have the
extension .py (meaning that the filename ends with .py).
We can save the code with filename.py and run the interpreter in script mode to execute the script.
In a file filename.py
print(1) x=2 Output
print(x) >>>1
2
Interactive mode Script mode
A way of using the Python interpreter by typing A way of using the Python interpreter to read and
commands and expressions at the prompt execute statements in a script
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, we can If we are very clear about the code, we can use
use interactive mode. script mode.
We cannot save the statements for further We can save the statements for further use
use and we have to retype all the statements to and we no need to retype all the statements to re-
re-run them. run them.
We can see the results immediately. We can’t see the results immediately.

2.2. VALUES AND TYPES


Programming languages contain data in terms of input and output and any kind of data can
be presented in terms of value.
Values
A value is one of the basic things of a program. There are different values integers, float and
strings. The numbers with a decimal point belong to a type called float. The values written in
quotes will be considered as string, even it‟s an integer. If type of value is not known it can be
interpreted as an in-built method called type. Syntax to know the type of any value is type(value)
Eg:
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>

Data types in Python:

Unit II Data Types, Expressions, Statements 4


5

Every value in Python has a data type. It is a set of values, and the allowable operations on
those values. In Python programming, data types are actually classes and variables are instance
(object) of these classes.

Numbers:
Number data type stores Numerical Values. This data type is immutable [i.e. values/items cannot
be changed]. Python supports integers, floating point numbers and complex numbers. They are
defined as,

Integers Float Complex


Integer is a combination of It consists of a whole number, They are of the form a+bj
positive and negative decimal point and fractional part. where a and b are floats and
numbers including zero. j represents the square root
In a program, integer literals The float function converts a string of
are written without commas into a floating-point number. -1(which is an
and a leading minus sign to >>>float(‟34.78‟) imaginary number)
indicate a negative value. 34.78
The int function converts a The real part of the number
string or a number into a is a and the imaginary part
whole number of the number is b
>>>int(23.56) 23
>>>int(„145‟) 145
Ex: 28 Ex:32.45 Ex: 3+7j
>>>17 >>>8.3e1 >>>2+3j
17 83.0 (2+3j)
>>>-23
-23

Boolean
It has values either True or False. Internally true value represented as 1 and false as 0. It is used to
compare two values.
Eg:
>>>4==8
False
>>>4<8 True

Sequence:
A sequence is an ordered collection of items, indexed by positive integers. It is a combination of
mutable (value can be changed) and immutable (values cannot be changed) data types.
There are three types of sequence data type available in Python, they are
1. String
2. List

Unit II Data Types, Expressions, Statements 5


6

3. Tuple String
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters. Strings are marked by quotes:
• single quotes (' ') Eg, 'This a string in single quotes'
• double quotes (" ") Eg, "'This a string in double quotes'"
• triple quotes (""" """) Eg, This is a paragraph. It is made up of multiple lines and
sentences.""”
Individual character in a string is accessed using a subscript (index). Characters can be
accessed using indexing and slicing operations. Strings are immutable i.e. the contents of the string
cannot be changed after it is created.
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """. Eg:
>>> s = "This is a string"
>>> s = „‟‟a multiline‟‟‟
The str function is used to convert a number into a string.
>>>str(34.23)
‟34.23‟
List
❖ List is an ordered sequence of items. Values in the list are called elements / items.
❖ It can be written as a list of comma-separated items (values) between square brackets [ ].
❖ Items in the lists can be of different data types. Eg:
>>> a = [‟spam‟, ‟eggs‟, 100, 1234] >>>
a
Output: [‟spam‟, ‟eggs‟, 100, 1234]
We can use a list‟s constructor to create a list.
Create an empty list L1=list()
Create a list with any integers L2=list([3,5,2])
Create a list using built-in range L3=list(range(0,5)). Creates a list with elements from 0 to 5.
Tuple:
A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square
brackets.
A tuple is an immutable list. i.e., once a tuple has been created, we can't add elements to a tuple
or remove elements from the tuple.
Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used. Tuples
can be used as keys in dictionaries, while lists can't.
Eg:
Tuple with string values
>>> T=("Sun","Mon","Wed")
>>> print(T)
('Sun', 'Mon', 'Wed')

Tuple with single character


>>>T=("P","Y","T","H","O","N")
>>> print(T)
('P', 'Y', 'T', 'H', 'O', 'N')
Sets:
A set is an unordered collection of items. Every element is unique and cannot be changed. A
set is created by placing all the items (elements) inside curly braces{}, separated by comma.

Unit II Data Types, Expressions, Statements 6


7

Eg:
>>> x=set("PYTHON PROGRAMMING")
>>> print(x)
set(['N', 'M', 'H', 'P', 'R', 'I', 'T', 'O', 'G', 'Y', 'A', ' '])
>>> a={5,2,3,1,4}
>>> print(a)
set([1, 2, 3, 4, 5])
>>> print(type(a))
<class 'set'>
>>> b=set([5,7,3,9,7,2,9,1])
>>>print(b)
set([1,2,3,5,7,9])

Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unordered sets.
❖ Dictionary is created by using curly brackets. i,e. {}
❖ Dictionaries are accessed via keys and not via their position.
❖ A dictionary is an associative array (also known as hashes). Any key of the dictionary is
associated (or mapped) to a value.
❖ The values of a dictionary can be any Python data type. So dictionaries are unordered
key-value-pairs(The association of a key and a value is called a keyvalue pair )
❖ Dictionaries don't support the sequence operation of the sequence data types like strings,
tuples and lists.
Eg:
>>> food = {"ham":"yes", "egg" : "yes", "rate":450 }
>>>print(food)
{'rate': 450, 'egg': 'yes', 'ham': 'yes'}

We can access the item only with keys


>>>>print(food["rate"])
450

2.3 VARIABLES, EXPRESSIONS AND STATEMENTS


Python Identifiers
In Python, identifier is the name given to entities like class, functions, variables etc., It
helps differentiating one entity from another.

Rules for writing identifiers


1. 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.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. Identifier can be of any length.

Variables
A variable is a name that refers to a value. A variable is a location in memory used to store
some data (value). They are given unique names to differentiate between different memory
locations. The assignment operator (=) to assign values to a variable.

Unit II Data Types, Expressions, Statements 7


8

An assignment statement creates new variables and gives them values:


Rules for naming variables:
• Variable names can be uppercase letters or lower-case letters.
• Variable names can be at any length
• They can contain both letters and numbers, but they can’t begin with a number.
• The underscore (_ ) character can appear in a name. It is often used in names with multiple
words. Eg:my_name
• No blank spaces are allowed between variable name.
• A variable name cannot be any one of the keywords or special characters.
• Variable names are case-sensitive

Assigning value to variable:


Value should be given on the right side of assignment operator (=) and variable on left side.
>>> message = „something‟
>>> n = 17
>>> pi = 3.1415926535897932
The type of a variable is the type of the value it refers to.
Eg:
>>> type(n)
<type 'int'>
Assigning a single value to several variables simultaneously:
>>> a=b=c=100
>>> print(a,b,c)
100 100 100
Assigning multiple values to multiple variables:
>>> a,b,c=10,12.5,"ABC"
>>> print(a,b,c)
10 12.5 ABC
If we give an illegal name to a variable, we get a syntax error.
Eg: 76trom = 'big parade'
Syntax Error: invalid syntax
Keywords: The interpreter uses keywords to recognize the structure of the program, and they
cannot be used as variable names. Python 2 has 31 keywords. Python 3 has 33 keywords.
and del from not while
as elif global or with
assert else if pass False
break except import print True
class exec in raise yield
continue finally is return
def for lambda try
Expressions and statements
An expression is a combination of values, variables, and operators. A value all by itself is
considered an expression, and also a variable. So the following are all legal expressions:
Eg:
>>> 42
42
>>> a=2
>>> a+3+2

Unit II Data Types, Expressions, Statements 8


9

7
>>> z=("hi"+"friend")
>>> print(z)
hifriend

Statements:
Instructions that a Python interpreter can execute are called statements. A statement is a
unit of code that the Python interpreter can execute. Two kinds of statement: print and assignment.
Eg:
>>> n = 17
>>> print(n)
Here, the first line is an assignment statement that gives a value to n. The second line is a print
statement that displays the value of n. Eg:
a=1+2+3+\
4+5+6+\
7+8+9
In Python, end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\).
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 and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that
block. Generally, four whitespaces are used for indentation and is preferred over tabs. Here is an
example.

Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change
dynamically. It is defined within parentheses () where items are separated by commas.
Eg:
>>> t = (5,'program', 1+3j)
>>> a=(5,7.9,10)

Tuple assignment
➢ An assignment to all of the elements in a tuple using a single assignment statement.
➢ Python has a very powerful tuple assignment feature that allows a tuple of variables on
the left of an assignment to be assigned values from a tuple on the right of the assignment.
➢ The left side is a tuple of variables; the right side is a tuple of values.
➢ Each value is assigned to its respective variable.
➢ All the expressions on the right side are evaluated before any of the assignments. This
feature makes tuple assignment quite versatile.
Unit II Data Types, Expressions, Statements 9
10

➢ Naturally, the number of variables on the left and the number of values on the right have
to be the same.

Examples:
>>> T1=(10,20,30)
>>> T2=(100,200,300,400)
>>>print T1
(10,20,30)
>>>print T2
(100,200,300,400)
>>>T1,T2=T2,T1
>>>print T1
(100,200,300,400)
>>>Print T2
(10,20,30)

One way to think of tuple assignment is as tuple packing/unpacking. In tuple


packing, the values on the left are „packed‟ together in a tuple:
>>> b = ("George", 25, "20000") # tuple packing
In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
>>> b = ("George", 25, "20000") # tuple packing
>>> (name, age, salary) = b # tuple unpacking
>>> name
'George'
>>> age
25
>>> salary
'20000'
The right side can be any kind of sequence (string, list, tuple)
>>> (a, b, c, d) = (1, 2, 3)
ValueError: need more than 3 values to unpack
Comments
Comments indicate Information in a program that is meant for other programmers (or
anyone reading the source code) and has no effect on the execution of the program. In Python, we
use the hash (#) symbol to start writing a comment.
Eg:
#This is a comment
#print out Hello
print('Hello')
Input and output
INPUT: Input is data entered by user (end user) in the program. In python, input () function is
available for input.

Syntax for input() is: variable = input (“data”)


>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3

Unit II Data Types, Expressions, Statements 10


11

Python accepts string as default data type. Conversion may require for all other types.

OUTPUT: Output can be displayed to the user using print statement.

Syntax:
print (expression/constant/variable)
print (“Statement”,variable_name)
print (“Statement %formatting function” %variable_name)

After all values are printed, it defaults into a new line.


The file is the object where the values are printed and its default value is sys.stdout.
Example:
>>> print ("Hello")
Hello

PRECEDENCE OF OPERATORS

OPERATORS:
An operator is a symbol that represents an operation performed on one or more operands. An
operand is a quantity on which an operation is performed.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operators:
Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

1. Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x / y

% Modulus - remainder of the division of left operand by the x % y


right
// Floor division – division of operands where the result is the x//y
quotient in which the digits after the decimal points are
removed.
** Exponent - left operand raised to the power of right x**y

Unit II Data Types, Expressions, Statements 11


12

Example: Arithmetic operators in Python


x = 15 y = 4
# Output: x / y = 3.75
print('x / y =',x/y)
# Output: x // y = 3
print('x // y =',x//y)
# Output: x ** y = 50625
print('x ** y =',x**y)
Examples Output:
a=10
b=5 a+b= 15
print("a+b=",a+b) a-b= 5
print("a-b=",a-b) a*b= 50
print("a*b=",a*b) a/b= 2.0
print("a/b=",a/b) a%b= 0
print("a%b=",a%b) a//b= 2
print("a//b=",a//b) a**b= 100000
print("a**b=",a**b)

Comparison operators: Comparison operators are used to compare values. It either returns True
or False according to the condition.
Operator Meaning Example
Greater than - True if left operand is greater than the right x>y
>
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x==y
!= Not equal to - True if operands are not equal x!=y
Greater than or equal to - True if left operand is greater than x>=y
>= or equal to the right
Less than or equal to - True if left operand is less than or equal x<=y
<= to the right

Example Output:
a=10 b=5
print("a>b=>",a>b) a>b=> True
print("a<b=>",a<b) a>b=> False
print("a==b=>",a==b) a==b=> False
print("a!=b=>",a!=b) a!=b=> True
print("a<=b=>",a<=b) a>=b=> False
print("a>=b=>",a>=b) a>=b=> True

Logical operators: Logical operators are used to compare and evaluate logical operations. Python
supports three logical operators: and, or, not

Operator Meaning Example


And True if both the operands are true x and y
Or True if either of the operands is true x or y

Unit II Data Types, Expressions, Statements 12


13

Not True if operand is false (complements the operand) not x


Example: x,y=10,10
print((x>=y) and
(x==y)) x=11 y=5
print((x>y) and (y>x))
print((x>y) or (y>x))
print(not(x>y))
Output
True # (10>=10)(true) and (10==10) (true) so it returns true
False # (10>5) (true) and (5>10) (false) so it returns false
True #(10>5) (true) or (5 is not >10) (false) so it returns true.
False # not(10>5), not true is false

Bitwise operators: Bitwise operators act on operands as if they were string of binary digits. It
operates bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x& y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x>> 2 = 2 (0000 0010)
<< Bitwise left shift x<< 2 = 40 (0010 1000)

Example Output
a = 60 # 60 = 00111100 Line 1 - Value of c is 12
b = 13 # 13 = 0000 1101 Line 2 - Value of c is 61
c=0 Line3 - Value of c is 49
c=a&b #12= 0000 1100 Line 4 -Value of c is -61
print "Line 1 - Value of c is ", c Line 5- Value of c is 240
Line 6 - Value of c is 15
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c=~a #-61=1100 0011


print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000


print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111


print "Line 6 - Value of c is ", c

Unit II Data Types, Expressions, Statements 13


14

Assignment operators
Assignment operators are used in Python to assign values to variables. a = 5 is a simple assignment
operator that assigns the value 5 on the right to the variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable and
later assigns the same. It is equivalent to a = a + 5.
Operator Description Example
= Assigns values from right side operands to left side c = a + b
operand Assigns value of a+ b
into c
+= It adds right operand to the left operand and assign c += a is equivalent
the result to left operand to c = c + a
-= It subtracts right operand from the left operand and c -= a is equivalent
assign the result to left operand to c = c - a
*= It multiplies right operand with the left operand and c *= a is
assign the result to left operand equivalent to c = c * a
/= It divides left operand with the right operand and c /= a is equivalent to
assign the result to left operand c=c/a
c /= a is equivalent
to c = c / a
%= It takes modulus using two operands and c %= a is equivalent
assign the result to left operand to c = c % a
**= Performs exponential (power) c **= a is equivalent
calculation on operators and assign value to the left to c = c ** a
operand
//= It performs floor division on operators and assign c //= a is equivalent
value to the left operand to c = c //a
Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c = 2 c %= a
print("Line 5 - Value of c is ", c)
c **= a
print("Line 6 - Value of c is ", c)
c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092

Unit II Data Types, Expressions, Statements 14


15

Line 4 - Value of c is 52.0


Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

Special operators: Python language offers some special type of operators like the identity
operator or the membership operator.
Identity operators is and is not are the identity operators in Python. They are used to check if
two values (or variables) are located on the same part of the memory. Two variables that are equal,
does not imply that they are identical.
Operator Meaning
is True if the operands are identical (refer to the same object)
is not True if the operands are not identical (do not refer to the same object)

Example: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
# Output: False
print(x1 is not y1)
# Output: True
print(x2 is y2)
# Output: False
print(x3 is y3)
Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical.
Same is the case with x2 and y2 (strings).
But x3 and y3 are list. They are equal but not identical. Since list are mutable (can be changed),
interpreter locates them separately in memory although they are equal.
Membership operators in and not in are the membership operators in Python. They are used to
test
whether a value or variable is found in a sequence (string, list, tuple, set and dictionary). In a
dictionary we can only test for presence of key, not the value.
Operator Meaning Example
In True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

Example: Membership operators in Python


x = 'Hello world'
y = {1:'a',2:'b'}
# Output: True
print('H' in x)
# Output: True
print('hello' not in x)
# Output: True
print(1 in y)
# Output: False

Unit II Data Types, Expressions, Statements 15


16

print('a' in y)
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Precedence of Operators
The order of evaluation depends on the rules of precedence. The acronym PEMDAS is a
useful way to remember the rules:

Parentheses have the highest precedence


Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27.
Multiplication and Division have the same precedence, which is higher than Addition and
Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right
Operator precedence in python
Sl.No Operator Description
1. ** Exponentiation (raise to the power)
2. ~, + ,- Complement, unary plus, and minus
3. * , /, %, // Multiply, divide, modulus, and floor division
4. +,- Addition and subtraction
5. << ,>> Right and left bitwise shift
6 & Bitwise „AND‟
7. ^ ,| Bitwise exclusive „OR‟ and regular „OR‟
8. <=,< >,>= Comparison operator
9. == , != Equality operators
10 =%,=/,=//,=,=+,=*,=** Assignment operators
11. not Logical operator not
12 and Logical operator and
13 or Logical operator or

Examples:
A=9-12/3+3*2-1 A=2*3+4%5-3/2+6 find m=?
a=? A=6+4%5-3/2+6 m=-43||8&&0||-2
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||0||-2
a=9-4+6-1 A=6+4-1+6 m=1||-2 m=1
a=5+6-1 A=10-1+6
a=11-1 a=10 A=9+6
A=15
a=2,b=12,c=1 a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c d=a<b>c-1 a=6+4-1+6 a=10-
d=2<12>1 d=2<12>1-1 1+6 a=15
d=1>1 d=0 d=2<12>0
d=1>0 d=1

Illustrative Programs
1. Exchange the values of two variables (or) Swapping of Output
values

Unit II Data Types, Expressions, Statements 16


17

x=input(“Enter value of x:‟) Enter value of x: 55


y= input(“Enter value of y:‟) Enter value of y: 84
temp=x
x=y The value of x after swapping:84
y=temp The value of y after swapping:55
print(“ The value of x after swapping:”,x)
print(“ The value of y after swapping:”,y)
2.i Circulate the values of n variables(list) Output
a=list(input("enter the list")) enter the list '1234'
print(a) for i in ['1', '2', '3', '4']
range(1,len(a),1): ['2', '3', '4', '1']
print(a[i:]+a[:i]) ['3', '4', '1', '2']
['4', '1', '2', '3']
3.Finding distance between two points
The formula for distance between two point (x1, y1) and (x2, y2) is

import math x1=input(“Enter the value for x1:”) Output


y1=input(“Enter the value for y1:”) Enter the value for x1: 7
x2=input(“Enter the value for x2:”) Enter the value for y1: 6
y2=input(“Enter the value for y2:”) Enter the value for x2: 5
distance=math.sqrt((x2-x1)**2)+((y2-y1)**2) Enter the value for y2: 7
print(“The distance between two points:” distance) The distance between two points:2.5
Python Program to calculate the square root Output
num = int(input('Enter a number: ')) Enter a number: 81
num_sqrt = num ** 0.5 The square root of 81 is 9
print('The square root of “,num,” is” ,num_sqrt)

Unit II Data Types, Expressions, Statements 17

You might also like