Unit 2 Ge3151 PSPP New
Unit 2 Ge3151 PSPP New
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.
1. INTRODUCTION TO PYTHON:
Python is interpreted: Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter
directly to write your 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.
Python Features:
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 fairly easy-to-maintain.
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. You can simply run the program.
Extensible: Programmers can embed python within their C,C++,JavaScript, 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.
Applications:
31
Python interpreter:
Compiler Interpreter
Compiler Takes Entire program as input Interpreter Takes Single instruction as input
Python Interpreter is a program that reads and executes Python code. It uses 2 modes of Execution.
1. Interactive mode
2. Script mode
Interactive mode:
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.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you to enter code. If you
type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
32
This is an example of a print statement. It displays a result on the screen. In this case, the result is the words.
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
Save the code with filename.py and run the interpreter in script mode to execute the script.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further use and we we can save the statements for further use and we no
have to retype all the statements to re-run them. need to retype all the statements to re-run them.
We can see the results immediately. We can’t see the code immediately.
33
2. VALUES AND DATATYPES
Value:
Value can be any letter, number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to different datatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
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,
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)
datatypes.
There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
34
Strings:
A String in Python consists of a series or sequence of characters - letters, numbers, and special
characters.
Strings are marked by quotes:
Single quotes(' ') E.g., 'This a string in single quotes'
double quotes(" ") E.g., "'This a string in double quotes'"
triple quotes(""" """) E.g., """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.
Indexing:
Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of different
data types.
Indexing >>>print(s[2]) Accessing the item in the
o position0
>>>print(s[6]) Accessing the item in the
O position2
Slicing( ending >>>print(s[2:]) - Displaying items from 2ndtill
position -1) od morning last.
35
st
Slice operator is used >>>print(s[:4]) - Displaying items from 1
to extract part of a Good
position till 3rd.
data
type
Lists
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 datatypes.
Operations on list:
Indexing
Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion
36
6.78, 9]
Repetition >>>list2*3 Creates new strings, concatenating
['god', 6.78, 9, 'god', 6.78, 9, 'god', multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index value
>>>print( list1)
[‘python’, 7.79, 45, ‘hello’]
Inserting an element >>>list1.insert(2,"program") Inserting an element in 2ndposition
>>> print(list1)
['python', 7.79, 'program', 45,
'hello']
Removing an element >>>list1.remove(45) Removing an element by
>>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
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, you 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.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) python Accessing the item in the
>>>t[2] position0
101 Accessing the item in the
position2
Altering the tuple data type leads to error. Following error occurs when user tries to do.
37
>>>t[0]="a"
Trace back (most recent call last):
File "<stdin>", line 1, in < module>
Type Error: 'tuple' object does not support item assignment
Set
A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable
(cannot be changed).
A set is created by placing all the items (elements) inside curly braces {} , separated by comma, or by using the
built-in set() function.
# Python program to
# demonstrate sets
Output:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Dictionaries:
Lists are ordered sets of objects, whereas dictionaries are unorderedsets.
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 key- value pair)
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists.
38
If you try to access a key which doesn't exist, you will get an error message:
39
3.Variables,Keywords Expressions, Statements, Comments, Docstring ,Lines And Indentation,
Quotation In Python, Tuple Assignment:
VARIABLES:
A variable allows us to store a value by assigning it to a name, which can be used later.
Named memory locations to store values.
Programmers generally choose names for their variables that are meaningful.
It can be of any length. No space is allowed.
We don't need to declare a variable before using it. In Python, we simply assign a value to a variable
and it will exist.
>>> a=b=c=100
Assigning multiple values to multiple variables:
>>>a,b,c=2,4,"ram"
KEYWORDS:
Keywords are the reserved words in Python.
We cannot use a keyword as name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
Keywords are case sensitive.
IDENTIFIERS:
Identifier is the name given to entities like class, functions, variables etc. in Python.
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 (_).
all are valid example.
An identifier cannot start with a digit.
Keywords cannot be used as identifiers.
Cannot use special symbols like!, @, #, $, % etc. in our identifier.
Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable
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.
Expressions:
-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:
>>> 42
42
>>> a=2
>>>a+3+2 7
>>> z=("hi"+"friend")
>>>print(z) hifriend
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”)
40
Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. Conversion is required for type.
COMMENTS:
A hash sign (#) is the beginning of a comment.
Anything written after # in a line is ignored by interpreter.
Eg: percentage = (minute * 100)/60 # calculating percentage of an hour
Python does not have multiple-line commenting feature. You have to comment each line
individually as follows:
Example:
# This is a comment.
# This is a comment, too.
# I said that already.
Most of the programming languages like C, C++, Java use braces { } to define a block of code. But,
python uses indentation.
Blocks of code are denoted by line indentation.
It is a space given to the block of codes for class and function definitions or flow control.
Example:
a=3 b=1
if a>b:
print("a is greater")
else:
print("b is greater")
QUOTATION INPYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. Anything that is
represented using quotations are considered as string.
41
TUPLE ASSIGNMENT
Example:
-It is useful to swap the values of two variables. With conventional assignment statements, we have to use a
temporary variable. For example, to swap a and b:
(a, b) = (b, a)
-In tuple unpacking, the values in a tuple on the right are ‘unpacked ‘into the variables/names on the
right:
42
Example:
-To split an email address in to user name and a domain
>>>mailid='[email protected]'
>>>name,domain=mailid.split('@')
>>>print name god
>>> print (domain) abc.org
4.OPERATORS:
Operators are the constructs which can manipulate the value of operands.
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
Ternary Operators
o Unary Operators
Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5
% Modulus Divides left hand operand by right hand operand and returns remainder b%a=0
// Floor Division - The division of operands where the result is the quotient 5//2=2
in which the digits after the decimal point are removed
43
Examples Output:
a=10 a+b=15
b=5 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)
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)
44
Comparison (Relational)Operators:
Comparison operators are used to compare values.
It either returns True or False according to the condition. Assume, a=10 and b=5
!= If values of two operands are not equal, then condition becomes true. (a!=b) is
true
> If the value of left operand is greater than the value of right operand, then (a > b) is not
condition becomes true. true.
< If the value of left operand is less than the value of right operand, then (a < b) is true.
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right (a >= b) is not
operand, then condition becomes true. true.
<= If the value of left operand is less than or equal to the value of right (a <= b) is
operand, then condition becomes true. true.
Example
Output: a>b=>True
a=10 a<b=> False
b=5 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
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
45
Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to c += a is
leftoperand equivalent to c
=c+a
-= Subtract It subtracts right operand from the left operand and assign the result c -= a is
AND to left operand equivalent to c
= c -a
*= Multiply It multiplies right operand with the left operand and assign the c *= a is
AND result to left operand equivalent to c
= c *a
/= Divide It divides left operand with the right operand and assign the result c /= a is
AND to left operand equivalent to c
= c /ac
/= a is
equivalent to c
= c /a
%= Modulus It takes modulus using two operands and assign the result to left c %= a is
AND operand equivalent to c
=c%a
//= Floor It performs floor division on operators and assign value to the left c //= a is
Division operand equivalent to c
= c // a
46
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
Line 4 - Value of c is 52.0
Line 5 - Value of c is2
Line 6 - Value of c is 2097152
Line 7 - Value of c is99864
Logical Operators:
-Logical operators are the and, or, not operators.
Example Output
a = True x and y is False
b = False x or y is True
print('a and b is', a and b) not x is False
print('a or b is' ,a or b)
print('not a is', not a)
47
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual bits
Example: Let x = 10 (0000 1010 in binary)and
y = 4 (0000 0100 in binary)
Example
a = 60 # 60 = 0011 1100
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple, dictionary or
not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators areused.
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False
Identity Operators:
i) They are used to check if two values (or variables) are located on the same part of the
memory.
Example
x=5
y=5
x2 = ‘Hello'
y2= 'Hello'
print(x1 is not y1) print(x2 is y2)
Output:
False
True
Ternary Operator
Ternary operators are also known as conditional expressions are operators that evaluate something based on a
condition being true or false.
Syntax: [on_true] if [expression] else [on_false]
Eg: x = 10
y=8
x if x>y else y
Unary Operator
A unary operator is an operator which works on a single operand. Python support unary minus operator(-). When
an operand is preceded by a minus sign, then the unary operator negates its value.
Eg: x=100
y=-(x)
print(y)
Output: -100
Lambda operator or Lambda function
A lambda function is a small anonymous function.A lambda function can take any number of arguments, but can only
have one expression.
Syntax
lambda arguments : expression
eg:
x = lambda a, b : a * b
print(x(5, 6))
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description
() Parentheses
~+- Complement, unary plus and minus (method names for the
last two are +@ and -@)
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2
a=9-4+6-1 1+6 m=- 43||0||-2 m=1||-
a=5+6-1 a=11- A=10-1+6 2 m=1
1 a=10 A=9+6 A=15
8.ILLUSTRATIVE PROGRAMS
3. What is IDLE?
Integrated Development Learning Environment (IDLE) is a graphical user interface which is
completely written in Python. It is bundled with the default implementation of the python language and also
comes with optional part of the Python packaging.
4. Differentiate between interactive and script mode.
7. Outline the logic to swap the contents of two identifiers without using third variable.
Swap two numbers Output:
a=2;b=3
print(a,b) (2, 3)
a = a+b (3, 2)
b= a-b >>>
a= a-b
print(a,b)
Example Output
a = True a and b is False
b = False a or b is True
print('a and b is',a and b) not a is False
print('a or b is',a or b)
print('not a is',not a)
A value is one of the basic things in a programs like a letter or a number. The values are belonging to different
types. For example
>>> type(‘Hello’)
<type ‘str’>
>>> type(17)
<type ‘float’>
11.Define variables.
A variable is a name that refers to a value. They can contain both letters and numbers but they do not begin
with a letter. The underscore ‘_’ can appear in a name.
Example:
>>> n=176
A Boolean expression is an expression that is either true (or) false. The Operator == which compares two operands
and produces True if they are equal otherwise it is false.
>>> 5==5
True
>>> 5==6
False
13.Define List.
A List is a sequence of values. The values are characters in a list they can be of any type. The values in a list are
called elements.
Examples
Character List