Chapter-5 (Getting Started With Python)
Chapter-5 (Getting Started With Python)
We have wri en algorithms for different problems in Chapter 4. Let us now move a step further
and create programs using any version of Python 3. But before learning about Python programming
language, let us understand what is a programming language and how it works.
An ordered set of instruc ons to be executed by a computer to carry out a specific task is
called a program, and the language used to specify this set of instruc ons to the computer is
called a programming language.
As we know that computers understand the language of 0s and 1s which is called machine language
or low- l e v e l language. However, it is difficult for humans to write or comprehend instruc ons
using 0s and 1s. This led to the advent of high-level programming languages like Python, C++, Visual
Basic, PHP, Java that are easier to manage by humans but are not directly understood by the
computer.
A program wri en in a high-level language is called source code. Recall from Chapter 1
that language translators like compilers and interpreters are needed to translate the source
code into machine language. Python uses an interpreter to convert its instruc ons into
machine language, so that it can be understood by the computer.
Features of Python
Working in the interac ve mode is convenient for tes ng a single line code for instant execu on.
But in the interac ve mode, we cannot save the statements for future use and we have to retype
the statements to run them again.
Script mode: Script mode allows us to write more than one instruc on in a file called Python
source code file that can be executed.
In the 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 installa on folder.
While working in the script mode, a er saving the file, click [Run]->[Run Module] from the
menu as shown in Figure.
Python source code file
Execu on of Python in Script mode using IDLE
Python Keywords:
Keywords are reserved words. Also known as pre-defined word.
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 in Table.
Identifiers:
Name given to programming element known as Identifier.
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 keyword Table.
We cannot use special symbols like !, @, #, $, %, etc., in identifiers.
Variables
A variable is basically a named storage location in a program that holds data, which can change
(or “vary”) while the program is running.
In Python we can use an assignment operator to create new variables and assign specific values
to them.
Example:
gender = 'M'
message = "Keep Smiling"
price = 987.9
Comments
comments are lines in a program that are not executed by the interpreter.
They are added with the purpose of making the source code easier for humans to
understand.
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.
Data Types
Number
Number data type stores numerical values only. It is further classified into three different types:
int, float and complex.
Type/ Class Description Examples
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.
Example >>> var1 = True
>>> num1 = 10 >>> type(var1)
>>> type(num1) <class 'bool'>
<class 'int'>
>>> float1 = -1921.9
>>> num2 = -1210 >>> type(float1)
>>> type(num2) <class 'float'>
<class 'int'>
>>> var2 = -3+7.2j
>>> type(var2)
<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.
Sequence
Tuple is a sequence of items separated by comma and items are enclosed in parenthesis (
).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')
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.
#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}
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
Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping
data type in Python called dic onary.
Dictionary
Dic onary in Python holds data items in key-value pairs. Items in a dic onary are enclosed in curly
brackets { }. Dic onaries permit faster access to data. Every key is separated from its value using
a colon (:) sign. The key: value pairs of a dic onary 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
dic onary, we have to specify its key in square brackets [ ].
#Create a dic onary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Mutable and Immutable Data Types
Variables whose values can be changed a er they are created and assigned are called
mutable.
Variables whose values cannot be changed a er they are created and assigned are called
immutable. When an a empt 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.
OPERATORS
An operator is used to perform specific opera on (mathema cal or logical) on values.
Arithme c Operators
Python supports arithme c operators that are used to perform the four basic arithme c
opera ons as well as modular division, floor division and exponen a on.
Arithme c Operators in Python
'HelloIndia'
-1
30
81
!= Not equal to If values of two operands are not >>> num1 != num2
equal, then condi on is True,
True
otherwise it is False
>>> str1 != str2
True
>>> num1 != num3
False
> Greater than If the value of the le -side >>> num1 > num2
operand is greater than the value
True
of the right- side operand, then
condi on is True, otherwise it is >>> str1 > str2
False
True
< Less than If the value of the le -side >>> num1 < num3
operand is less than the value of
False
the right- side operand, then
condi on is True, otherwise it is >>> str2 < str1
False
True
>= Greater than If the value of the le -side >>> num1 >= num2
or equal to operand is greater than or equal
True
to the value of the right-side
operand, then condi on is True, >>> num2 >= num3
otherwise it is False
False
<= Less than or If the value of the le operand is >>> num1 <= num2
equal to less than or equal to the value of
False
the right operand, then is True
otherwise it is False >>> num2 <= num3
True
>>> str1 <= str2
False
Assignment Operators
Assignment operator assigns or changes the value of the variable on its le .
Assignment operators in Python
12
>>> num2
2
>>> str1 = 'Hello'
>>> str2 = 'India'
>>> str1 += str2
>>> str1
'HelloIndia'
Logical Operators
There are three logical operators supported by Python. These operators (and, or, not) are to be
wri en in lower case only. The logical operator evaluates to either True or False based on the logical
operands on either side.
Logical operators in Python
and Logical AND If both the operands are >>> True and True
True, then condi on
True
becomes True
>>> num1 = 10
>>> num2 = -20
>>> bool(num1 and num2)
True
>>> True and False
False
>>> num3 = 0
>>> bool(num1 and num3)
False
>>> False and False
False
or Logical OR If any of the two >>> True or True
operands are True, then
True
condi on becomes True
>>> True or False
True
>>> bool(num1 or num3)
True
>>> False or False
False
Iden ty Operators
Iden ty operators are used to determine whether the value of a variable is of a certain type or not.
Iden ty operators can also be used to determine whether two variables are referring to the
same object or not. There are two iden ty operators.
Precedence of Operators
Evalua on 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.
Precedence of all operators in Python
11 or
Note:
Some mes, a program needs to interact with the users to get some input data or informa on from
the end user and process it to give the desired output. In Python, we have the input () func on for
taking the user input. The input() func on 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() func on treats them as
strings only. The syntax for input()is:
input ([Prompt])
The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it
to the variable on le -hand side of the assignment operator (=). Entering data for the input
func on is terminated by pressing the enter key.
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19
>>> type(age)
<class 'str'>
#func on int() to convert string to integer
>>> age = int( input("Enter your age:")) Enter your age: 19
>>> type(age)
<class 'int'>
OUTPUT
Python uses the print() func on to output data to standard output device — the screen.
Statement Output
print("Hello") Hello
print(10*2.5) 25.0
Explicit conversion, also called type cas ng 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 informa on since we are forcing
an expression to be of a specific type.
For example, conver ng a floa ng value of x = 20.67 into an integer type, i.e., int(x) will
discard the frac onal part .67.
Function Description
Output:
30
<class 'int'>
30.0
<class 'float'>
Program of explicit type conversion from float to int.
num1 = 10.2
num2 = 20.6
print(num3) Output:
print(type(num3)) 30.8
print(num4) 30
Implicit Conversion
when data type conversion is done automa cally by Python and is not instructed by the
programmer.
Program to show implicit conversion from int to float.
#Implicit type conversion from int to float
DEBUGGING
The process of iden fying and solving errors known as debugging.
Errors occurring in programs can be categorised as:
Syntax errors
Logical errors
Run me errors
Syntax errors
Like other programming languages, Python has its own rules that determine its syntax.
The interpreter interprets the statements only if it is syntac cally (as per the rules of
Python) correct.
If any syntax error is present, the interpreter shows error message(s) and stops the execu on
there.
For example, parentheses must be in pairs, so the expression (10 + 12) is syntac cally
correct, whereas (7 + 11 is not due to absence of right parenthesis. Such errors need to be
removed before the execu on of the program.
Logical Errors
A logical error produces an undesired output but without abrupt termina on of the
execu on of the program.
Since the program interprets successfully even when logical errors are present in it, it is
some mes difficult to iden fy these errors.
The only evidence to the existence of logical errors is the wrong output.
For example, if we wish to find the average of two numbers 10 and 12 and we write the
code as 10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not
the average of 10 and 12. The correct code to find the average should have been (10 +
12)/2 to give the correct output as 11.
Logical errors are also called seman c errors as they occur when the meaning of the program
(its seman cs) is not correct.
Run me Error