UNIT-4 Python Programming
UNIT-4 Python Programming
Page 1 of 18
Page 2 of 18
Page 3 of 18
Page 4 of 18
Working with Python
To write and run (execute) a Python program, we need to have a Python interpreter installed on our computer
or we can use any online Python interpreter. The interpreter is also called Python shell. A sample screen of
Python interpreter is shown in Figure. Here, the symbol >>> is called Python prompt, which indicates that the
interpreter is ready to receive instructions. We can type commands or statements on this prompt for execution.
Execution Modes
There are two ways to run a program using the Python interpreter:
1. Interactive mode
2. Script mode
(A) Interactive Mode
In the interactive mode, we can 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
Working in the interactive mode is convenient for testing a single line code for instant execution. But in the
interactive mode, we cannot save the statements for future use and we have to retype the statements to run
them again.
(B) Script Mode
In the script mode, we can write a Python program in a file, save it and then use the interpreter to execute the
program from the file. Such program files have a .py extension and they are also known as scripts. Python has
a built-in editor called IDLE which can be used to create programs. After opening the IDLE, we can click
File>New File to create a new file, then write our program on that file and save it with a desired name. By
default, the Python scripts are saved in the Python installation folder.
# IDLE : Integrated Development and Learning Environment
To execute a Python program in script mode,
a) Open the program using an editor, for example IDLE as shown in Figure
Page 5 of 18
b) In IDLE, go to [Run]->[Run Module] to execute the prog3-1.py as shown in Figure
Character set is a set of valid characters recognized by Python. A character represents any letter, digit or any
other symbol. Python uses the traditional ASCII character set. However, the latest version recognizes the
Unicode character set. The ASCII character set is a subset of the Unicode character set. Python supports the
following character sets:
Letters: A-Z, a-z
Digits: 0-9
Special Symbols: space + -/*\*( ) { } [ ] //=l= == <>,"" , ;: % !# ? $&^ <= >= @
Whitespaces: Blank space (‘ ‘) , tabs (\t), carriage return, newline, formfeed
Other Characters: All other 256 ASCII and Unicode characters
TOKENS
A token is the smallest element of a Python script that is meaningful to the interpreter.
The following categories of tokens exist:
Identifiers, keywords, literals, operators and delimiters/punctuators.
Page 6 of 18
Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As Python is
case sensitive, keywords must be written exactly as given in Table
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:
1.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.
2.It can be of any length. (However, it is preferred to keep it short and meaningful).
3.It should not be a keyword or reserved word given in Table 3.1.
4.We cannot use special symbols like !, @, #, $, %, etc. in identifiers.
Variables
Variable is an identifier whose value can change. For example variable age can have different value for
different person. Variable name should be unique in a program. Value of a variable can be string (for example,
‘b’, ‘Global Citizen’), number (for example 10,71,80.52) or any combination of alphanumeric (alphabets and
numbers for example ‘b10’) characters. In Python, we can use an assignment statement to create new variables
and assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Variables must always be assigned values before they are used in the program, otherwise it will lead to an
error. Wherever a variable name occurs in the program, the interpreter replaces it with the value of that
particular variable.
Literals/Constants
A fixed numeric or non-numeric value is called a literal. It can be defined as a number, text, or other data
that represents values to be stored in variables. They are also known as constants. Python supports the
following types of literals:
1. String Literals for example, a = "abc", b ="Independence", etc. alphanumeric/ text values
2. Numeric Literals for example, p = 2, a =1000, etc. integer values
3. Floating Literals - for example, salary = 15000.00, area =1.2,etc. decimal values
4. Boolean Literals – for example, value = True, value2 = False, etc.
5. Collection Literals -for example, list1 = [1,2,3,4,5], group = (10,20,30,40,50), etc.
Therefore, literals are data items that have fixed value.
Operators
An operator is a symbol or a word that performs some kind of operation on the given values and returns the
result. Examples of operators are: +,**,/, etc. Python operators have been discussed briefly later in the
chapter.
Page 7 of 18
Punctuators/Delimiters
Delimiters are the symbols which can be used as separators of values or to enclose some values.
Examples of delimiters are: ( ) { } [ ] , ; :
Note: # symbol used to insert comments is not a token. Any comment itself is not a token.
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data which a variable
can hold and the operations that can be performed on those data. Following figure enlists the data types
available in Python.
Number
Number data type stores numerical values only. It is further classified into three different types: int, float and
complex.
Numeric data types
Type/ Class Description Examples
int integer numbers -12, -3, 0, 123, 2
float floating point numbers -2.04, 4.0, 14.23
complex complex numbers 3 + 4i, 2 - 2i
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants, True and
False. Boolean True
Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer value. Three
types of sequence data types available in Python are Strings, Lists and Tuples. A brief introduction to these
data types is as follows:
(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 (for example ‘Hello’) or in double quotation
marks (for example “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. For
example str2 is a numeric string.
(B) List
List is a sequence of items separated by commas and items are enclosed in square brackets [ ]. Note that items
may be of different datea types.
For example,
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45] #print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
Page 8 of 18
(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 items in the tuple. Similar to List,
items may be of different data types.
For 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')
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data type in
Python called Dictionary.
Dictionary
Dictionary in Python holds data items in key-value pairs and Items 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. Keys are usually of string type and their values can
be of any data type. In order to access any value in the dictionary, we have to specify its key in square brackets
[ ].
For example,
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
Operators
An operator is used to perform specific mathematical or logical operation on values. The values that the
operator works on are called operands. For example, in the expression 10 + num, the value 10, and the variable
num are operands and the + (plus) sign is an operator.
Arithmetic Operators
Page 9 of 18
/ RELATIONAL OPERATORS
Page 10 of 18
PRECENDENCE
NOT
AND
OR
Page 11 of 18
There come situations in real life when we need to make some decisions and based on these decisions, we
need to decide what should we do next. Similar situations arise in programming also where we need to make
some decisions and based on these decisions we will execute the next block of code.
Decision making statements in programming languages decide the direction of flow of program execution.
Decision making statements available in Python are:
● if statement
● if..else statements
● if-elif ladder
If Statement
The if statement is used to check a condition: if the condition is true, we run a block of statements (called the
if-block).
Syntax:
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the text expression is
True.
If the text expression is False, the statement(s) is not executed.
Page 12 of 18
Note:
1) In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the
first unindented line marks the end.
2) Python interprets non-zero values as True. None and 0 are interpreted as False.
Example :
#Check if the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
num = -1
if num > 0:
print(num, “is a positive number.”)
print(“this is always printed”)
3 is a positive number
This is always printed
This is also always printed.
In the above example, num > 0 is the test expression. The body of if is executed only if this evaluates to
True.
When variable num is equal to 3, test expression is true and body inside body of if is executed.
If variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test
expression.
Page 13 of 18
Python if...else Statement
Syntax of if...else
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only when test condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
Example of if...else
#A program to check if a person can vote
age = input(“Enter Your Age”)
if age >= 18:
print(“You are eligible to vote”)
else:
print(“You are not eligible to vote”)
In the above example, when if the age entered by the person is greater than or equal to 18, he/she can vote.
Otherwise, the person is not eligible to vote.
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False, it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Page 14 of 18
Flowchart of if...elif...else
Example of if...elif...else
#To check the grade of a student
Marks = 60
if marks > 75:
print("You get an A grade")
elif marks > 60:
print("You get a B grade")
else:
print("You get a C grade")
We can have an if...elif...else statement inside another if...elif...else statement. This is called nesting in
computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out
the level of nesting. This can get confusing, so must be avoided if it can be.
Python Nested if Example
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero
LOOPING STATEMENTS
The For Loop
The for..in statement is another looping statement which iterates over a sequence of objects i.e. go through
each item in a sequence. A sequence is just an ordered collection of items.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest
of the code using indentation.
Page 16 of 18
Example: Python for Loop
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression
evaluates to True. After one iteration, the test expression is checked again. This process continues until the
test_expression evaluates to False. In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end. Python interprets any non-zero
value as True. None and 0 are interpreted as False.
Flowchart of while Loop
Page 17 of 18
Example: Python while Loop
Enter n: 10
The sum is 55
In the above program, the test expression will be True as long as our counter variable i is less than or equal
to n (10 in our program).
We need to increase the value of the counter variable in the body of the loop. This is very important (and
mostly forgotten). Failing to do so will result in an infinite loop (never ending loop).
Finally, the result is displayed.
Page 18 of 18