Ge3151 Unit Ii
Ge3151 Unit Ii
UNIT II
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.
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.
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
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.
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.
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.
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,
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
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')
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'}
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.
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)
Python accepts string as default data type. Conversion may require for all other types.
Syntax:
print (expression/constant/variable)
print (“Statement”,variable_name)
print (“Statement %formatting function” %variable_name)
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
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
Bitwise operators: Bitwise operators act on operands as if they were string of binary digits. It
operates bit by bit, hence the name.
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
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
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)
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:
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