Python Notes Module i
Python Notes Module i
Execution Modes
There are two ways to use the Python interpreter:
a) Interactive mode
VIJAYA GOPINATH M
b) Script mode
Interactive mode allows execution of individual statement instantaneously. Whereas, Script
mode allows us to write more than one instruction in a file called Python source code file that
can be executed.
(a) Interactive Mode
To work in the interactive mode, we can simply type a Python statement on the >>> prompt
directly. As soon as we press enter, the interpreter executes the statement and displays the
result(s), as shown in Figure
b) While working in the script mode, after saving the file, click [Run]->[Run Module] from the
menu as shown in Figure.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
PYTHON KEYWORDS
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter,
and we can use a keyword in our program only for the purpose for which it has been defined.
As Python is case sensitive, keywords must be written exactly as given below :
IDENTIFIERS
In programming languages, identifiers are names used to identify a variable, function, or other
entities in a program. The rules for naming an identifier in Python are as follows:
• The name should begin with an uppercase or a lowercase alphabet or an underscore sign (_).
This may be followed by any combination of characters a–z, A–Z, 0–9 or underscore (_). Thus,
an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• It should not be a keyword or reserved word given in the above Table.
• We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
For example,
1. To find the average of marks obtained by a student in three subjects, we can choose the
identifiers as marks1, marks2, marks3 and avg rather than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3
2. Similarly, to calculate the area of a rectangle, we can use identifier names, such as area,
length, breadth instead of single alphabets as identifiers for clarity and more readability.
area = length * breadth
VARIABLES
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to
an object — an item or element that is stored in the memory. Value of a variable can be a string
(e.g., ‘a’, ‘Hello World’), numeric (e.g., 345) or any combination of alphanumeric characters
CD67). In Python we can use an assignment statement to create new variables and assign
specific values to them.
Example : gender = 'M'
message = "Keep Smiling"
price = 987.9
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
Output:
Hello World
User Number is 100
The variable message holds string type value and so its content is assigned within double
quotes " " (can also be within single quotes ' '), whereas the value of variable userNo is not
enclosed in quotes as it is a numeric value.
Variable declaration is implicit in Python, means variables are automatically declared and
defined when they are assigned a value the first time. Variables must always be assigned values
before they are used in expressions as otherwise it will lead to an error in the program.
Wherever a variable name occurs in an expression, the interpreter replaces it with the value of
that particular variable.
Write a Python program to find the area of a rectangle given that its length is 10 units and
breadth is 20 units.
COMMENTS
Comments are used to add a remark or a note in the source code. Comments are not executed
by interpreter. They are added with the purpose of making the source code easier for humans
to understand. They are used primarily to document the meaning and purpose of source code
and its input and output requirements, so that we can remember later how it functions and
how to use it. For large and complex software, it may require programmers to work in teams
and sometimes, a program written by one programmer is required to be used or maintained by
another programmer. In such situations, documentations in the form of comments are needed
to understand the working of the program. In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
EVERYTHING IS AN OBJECT
Python treats every value or data item whether numeric, string, or other type (discussed in the
next section) as an object in the sense that it can be assigned to some variable or can be passed
to a function as an argument. Every object in Python is assigned a unique identity (ID) which
remains the same for the lifetime of that object. This ID is akin to the memory address of the
object. The function id() returns the identity of an object.
Example
>>> num1 = 20
>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1
#are same as both refers to object 20
DATA TYPES
Every value belongs to a specific data type in Python. Data type identifies the type of data
values a variable can hold and the operations that can be performed on that data.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
1. Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero, non-null and non-empty. Boolean
False is the value zero.
To determine the data type of the variable using built-in function type().
Example:
>>> num1 = 10
>>> type(num1)
<class 'int'>
>>> num2 = -1210
>>> type(num2)
<class 'int'>
>>> var1 = True
>>> type(var1)
<class 'bool'>
>>> float1 = -1921.9
>>> type(float1)
<class 'float'>
>>> float2 = -9.8*10**2
>>> print(float2, type(float2))
-980.0000000000001 <class 'float'>
>>> var2 = -3+7.2j
>>> print(var2, type(var2))
(-3+7.2j) <class 'complex'>
Variables of simple data types like integers, float, boolean, etc., hold single values. But such
variables are not useful to hold a long list of information, for example, names of the months in a
year, names of students in a class, names and numbers in a phone book or the list of artefacts
in a museum. For this, Python provides data types like tuples, lists, dictionaries and sets.
2. Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples. We will
learn about each of them in detail in later chapters. A brief introduction to these data types is
as follows:
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters
including spaces. String values are enclosed either in single quotation marks (e.g., ‘Hello’) or in
double quotation marks (e.g.“Hello”). The quotes are not a part of the string, they are used to
mark the beginning and end of the string for the interpreter. For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even when the string contains a numeric
value, as in str2.
(B) List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].
Example
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in brackets [ ]. Once created, we cannot change the
tuple.
Example
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
3. Set
Set is an unordered collection of items separated by commas and the items are enclosed in
curly brackets { }. A set is similar to list, except that it cannot have duplicate entries. Once
created, elements of a set cannot be changed.
Example
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2)
{1, 2, 3}
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
4. None
None is a special data type with a single value. It is used to signify the absence of value in a
situation. None supports no special operations, and it is neither same as False nor 0 (zero).
Example
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
5. Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data type in
Python called dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in
curly brackets { }. Dictionaries permit faster access to data. Every key is separated from its value
using a colon (:) sign. The key : value pairs of a dictionary can be accessed using the key. The
keys are usually strings and their values can be any data type. In order to access any value in the
dictionary, we have to specify its key in square brackets [ ].
Example
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Let us now see what happens when an attempt is made to update the value of a variable.
>>> num1 = 300
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
This statement will create an object with value 300 and the object is referenced by the identifier
num1 as shown in following Figure I.
>>> num2 = num1
The statement num2 = num1 will make num2 refer to the value 300, also being referred by
num1, and stored at memory location number, say 1000. So, num1 shares the referenced location
with num2 as shown in Figure II
In this manner Python makes the assignment effective by copying only the reference, and not the
data:
>>> num1
= num2 +
100
This statement 1 num1 = num2 + 100 links the variable num1 to a new object stored at
memory location number say 2200 having a value 400. As num1 is an integer, which is an
immutable type, it is rebuilt, as shown in following Figure.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
OPERATORS
An operator is used to perform specific mathematical or logical operation on values. Python
supports several kinds of operators whose categorisation is briefly explained below:
1. Arithmetic Operators
Python supports arithmetic operators that are used to perform the four basic arithmetic operations
as well as modular division, floor division and exponentiation.
Arithmetic Operators in Python
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
2. Relational Operators
Relational operator compares the values of the operands on its either side and determines the
relationship among them. Assume the Python variables num1 = 10, num2 = 0, num3 = 10,
str1 = "Good", str2 = "Afternoon" for the following examples:
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
3. Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
Assignment operators in Python
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
4. Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are to be
written in lower case only. The logical operator evaluates to either True or False based on the
logical operands on either side. Every value is logically either True or False. By default, all
values are True except None, False, 0 (zero), empty collections "", (), [], {}, and few other
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
special values. So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically
True.
Logical operators in Python
5. Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or
not. Identity operators can also be used to determine whether two variables are referring to the
same object or not. There are two identity operators.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
6. Membership Operators
Membership operators are used to check if a value is a member of the given sequence or not
EXPRESSIONS
An expression is defined as a combination of constants, variables, and operators. An expression
always evaluates to a value. A value or a standalone variable is also considered as an expression
but a standalone operator is not an expression. Some examples of valid expressions are given
below.
(i) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"
Precedence of Operators
Evaluation of the expression is based on precedence of operators. When an expression contains
different kinds of operators, precedence determines which operator should be applied first.
Higher precedence operator is evaluated before the lower precedence operator. Most of the
operators studied till now are binary operators. Binary operators are operators with two operands.
The unary operators need only one operand, and they have a higher precedence than the binary
operators. The minus (-) as well as + (plus) operators can act as both unary and binary operators,
but not is a unary logical operator.
Note:
a) Parenthesis can be used to override the precedence of operators. The expression within () is evaluated first.
b) For operators with equal precedence, the expression is evaluated from left to right.
The following table lists precedence of all operators from highest to lowest.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
STATEMENT
In Python, a statement is a unit of code that the Python interpreter can execute.
Example
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
4 64
input ([Prompt])
Prompt is the string we may like to display on the screen prior to taking the input, and it is
optional. When a prompt is specified, first it is displayed on the screen after which the user can
enter data. The input() takes exactly what is typed from the keyboard, converts it into a string
and assigns it to the variable on left-hand side of the assignment operator (=). Entering data for
the input function is terminated by pressing the enter key.
Example
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
The variable fname will get the string ‘Arnab’, entered by the user. Similarly, the variable age
will get the string ‘19’. We can typecast or change the datatype of the string data accepted from
user to an appropriate numeric value. For example, the following statement will convert the
accepted string to an integer. If the user enters any non-numeric value, an error will be generated.
Example
#function int() to convert string to integer
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<class 'int'>
Python uses the print() function to output data to standard output device — the screen. The
function print() evaluates the expression before displaying it on the screen. The print()outputs a
complete line and then moves to the next line for subsequent output. The syntax for print() is:
• sep: The optional parameter sep is a separator between the output values. We can use a
character, integer or a string as a separator. The default separator is space.
• end: This is also optional and it allows us to specify any string to be appended after the last
value. The default is a new line.
Example
The third print function in the above example is concatenating strings, and we use + (plus)
between two strings to concatenate them. The fourth print function also appears to be
concatenating strings but uses commas (,) between strings. Actually, here we are passing
multiple arguments, separated by commas to the print function. As arguments can be of different
types, hence the print function accepts integer (16) along with strings here. But in case the print
statement has values of different types and ‘+’ is used instead of comma, it will generate an
error.
TYPE CONVERSION
Consider the following program
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
The program was expected to display double the value of the number received and store in
variable num1. So if a user enters 2 and expects the program to display 4 as the output, the
program displays the following result:
This is because the value returned by the input function is a string ("2") by default. As a result, in
statement num1 = num1 * 2, num1 has string value and * acts as repetition operator which
results in output as "22". To get 4 as output, we need to convert the data type of the value
entered by the user to integer. Thus, we modify the program as follows:
As and when required, we can change the data type of a variable in Python from one type to
another. Such data type conversion can happen in two ways: either explicitly (forced) when the
programmer specifies for the interpreter to convert a data type to another type; or implicitly,
when the interpreter understands such a need by itself and does the type conversion
automatically.
Explicit Conversion
Explicit conversion, also called type casting happens when data type conversion takes place
because the programmer forced it in the program. The general form of an explicit data type
conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are forcing an
expression to be of a specific type. For example, converting a floating value of x = 2 0.67 into
an integer type, i.e., int(x) will discard the fractional part .67. Following are some of the
functions in Python that are used for explicitly converting an expression or a variable to a
different type.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
On execution, above program gives an informing that the interpreter cannot convert an integer
value to string implicitly. It may appear quite intuitive that the program should convert the
integer value to a string depending upon the usage. However, the interpreter may not decide on
its own when to convert as there is a risk of loss of information. Python provides the mechanism
of the explicit type conversion so that one can clearly state the desired outcome. Program works
perfectly using explicit type casting:
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)
lOMoARcPSD|49918191
Implicit Conversion
Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.
Output:
30.0
<class 'float'>
In the above example, an integer value stored in variable num1 is added to a float value stored in
variable num2, and the result was automatically converted to a float value stored in variable
sum1 without explicitly telling the interpreter. This is an example of implicit data conversion.
Why was the float value not converted to an integer instead? This is due to type promotion that
allows performing operations (whenever possible) by converting data into a wider-sized data
type without any loss of information.
VIJAYA GOPINATH M
Downloaded by Jithu Girish (jithugirish3424@gmail.com)