Chapter 5
Getting Started with Python
Introduction to Python
Program: An ordered set of instructions to be executed by a computer to carry out a specific task is
called a program.
Programming language: The language used to specify this set of instructions to the computer is
called a programming language.
Machine language: Computers understand the language of 0s and 1s which is called machine
language or low level language.
Examples for high level languages: Python, C++, Visual Basic, PHP, Java
Source code: A program written in a high-level language is called source code.
Python uses an interpreter to convert its instructions into machine language, so that it can be
understood by the computer.
An interpreter processes the program statements one by one, first translating and then
executing.
This process is continued until an error is encountered or the whole program is executed
successfully.
A compiler translates the entire source code, as a whole, into the object code.
Features of Python
It is a high level language.
It is a free and open source language.
It is an interpreted language, as programs are executed by an interpreter.
Programs are easy to understand as they have a clearly defined syntax and relatively simple
structure.
It is case-sensitive. For example, NUMBER and number are not same in Python.
It is portable and platform independent, means it can run on various operating systems and
hardware platforms.
It has a rich library of predefined functions.
It is also helpful in web development.
Many popular web services and applications are built using Python.
It uses indentation for blocks and nested blocks.
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.
The symbol >>> is the Python prompt, which indicates that the interpreter is ready to take
instructions. We can type commands or statements on this prompt to execute them using a Python
interpreter.
Execution Modes
There are two ways to use the Python interpreter:
a) Interactive mode
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
o To work in the interactive mode, we can simply type a Python statement on the >>>
prompt directly.
o As soon as we press enter, the interpreter executes the statement and displays the
result(s).
o Working in the interactive mode is convenient for testing a single line code for instant
execution.
o 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
We can write a Python program in a file, save it and then use the interpreter to execute it.
Python scripts are saved as files where file name has extension “.py”.
By default, the Python scripts are saved in the Python installation folder.
a) Type the file name along with the path at the prompt.
b) While working in the script mode, after saving the file, click [Run]->[Run Module] from the
menu
c) The output appears on shell
Python Keywords
These are reserved words.
Each keyword has a specific meaning to the Python interpreter.
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.
Identifiers
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.
We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
A variable in a program is uniquely identified by a name (identifier).
It refers to an object — an item or element that is stored in the memory.
It can be a string, numeric or any combination of alphanumeric characters.
In Python we can use an assignment statement to create new variables and assign specific
values to them.
It is implicit in Python, means variables are automatically declared and defined when they are
assigned a value the first time.
It must always be assigned values before they are used in expressions as otherwise it will lead
to an error in the program.
Comments
Comments are used to add a remark or a note in the source code. Comments are not executed
by interpreter.
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.
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.
Everything is an object
Python treats every value or data item whether numeric, string, or other type as an object.
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.
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.
Number
It stores numerical values only.
Boolean
It is a subtype of integer.
It is a unique data type, consisting of two constants, True and False.
True value is non-zero, non-null and non-empty.
Boolean False is the value zero.
Sequence
It 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.
(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 or in double quotation marks.
The quotes are not a part of the string, they are used to mark the beginning and end of the
string for the interpreter.
We cannot perform numerical operations on strings, even when the string contains a numeric
value
(B) List
It is a sequence of items separated by commas.
The items are enclosed in square brackets [ ].
Example: >>> list1 = [5, 3.4, "New Delhi", "20C", 45]
>>> print(list1)
5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
It is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
Once created, we cannot change the tuple.
Example: >>> tuple1 = (10, 20, "Apple", 3.4, 'a')
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Set
It is an unordered collection of items separated by commas.
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: >>> 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}
None
It 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
Mapping
It is an unordered data type in Python.
(A) Dictionary
It 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
Mutable Data Types
Variables whose values can be changed after they are created and assigned are called mutable.
Immutable Data Types
Variables whose values cannot be changed after they are created and assigned are called
immutable.
When an attempt is made to update the value of an immutable variable, the old variable is
destroyed and a new variable is created by the same name in memory.
Classification of data types
Object and its identifier
Variables with same value have same identifier
Operator
An operator is used to perform specific mathematical or logical operation on values.
Operands
The values that the operators work on are called operands.
1 Arithmetic Operator
These are used to perform the four basic arithmetic operations as well as modular division,
floor division and exponentiation.
2 Relational Operators
These compares the values of the operands on its either side and determines the relationship
among them.
3 Assignment Operators
These operators assign or change the value of the variable on its left.
4 Logical Operators
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 special values.
5 Identity Operators
These are used to determine whether the value of a variable is of a certain type or not.
These can also be used to determine whether two variables are referring to the same object or
not.
6 Membership Operators
These are used to check if a value is a member of the given sequence or not.
Expressions
It is defined as a combination of constants, variables, and operators.
It 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.
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.
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.
Input Statement
In Python, we have the input() function for taking the user input.
The input() function prompts the user to enter data.
It accepts all user input as string.
The user may enter a number or a string but the input() function treats them as strings only.
The syntax for input() is:
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'>
>>> age = int( input("Enter your age:"))
Enter your age: 19
>>> type(age)
<class 'int'>
Output Statement
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:
print(value [, ..., sep = ' ', end = '\n'])
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.
we use + (plus) between two strings to concatenate them.
Type conversion
We can change the data type of a variable in Python from one type to another is called type
conversion.
1 Explicit Conversion
It is also called type casting.
It happens when the programmer forced to change the datatype in the python program.
Program of explicit type conversion from int to float.
num1 = 10
num2 = 20
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:30
<class 'int'>
30.0
<class 'float'>
Program of explicit type conversion from float to int
num1 = 10.2
num2 = 20.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Output:30.8
<class 'float'>
30
<class 'int'>
Program of type conversion between numbers and strings
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice )
Implicit Conversion
It is also known as coercion.
It happens when data type conversion is done automatically by Python and is not instructed by
the programmer.
Program to show implicit conversion from int to float.
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float and an integer
print(sum1)
print(type(sum1))
Output: 30.0
<class 'float'>
Debugging
A programmer can make mistakes while writing a program, and hence, the program may not
execute or may generate wrong output.
The process of identifying and removing such mistakes, also known as bugs or errors, from a
program is called debugging.
Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
1. Syntax Errors
Python has its own rules that determine its syntax.
The interpreter interprets the statements only if it is syntactically (as per the rules of Python)
correct.
If any syntax error is present, the interpreter shows error message(s) and stops the execution
there.
2. Logical Errors
It is a bug in the program that causes it to behave incorrectly.
It produces an undesired output but without abrupt termination of the execution of the
program.
Since the program interprets successfully even when logical errors are present in it, it is
sometimes difficult to identify these errors.
These errors are also called semantic errors.
3 Runtime Errors
It causes abnormal termination of program while it is executing.
It is when the statement is correct syntactically, but the interpreter cannot execute it.
It do not appear until after the program starts running or executing.
Example of a program which generates runtime error.
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to runtime error
print(num1/num2)