Computational Thinking
© CS-DEPT DPS MATHURA ROAD
and Programming - 1
Python - Data Types
XI
Programs
© CS-DEPT DPS MATHURA ROAD
1. Write a program to input the radius of a circle and then display the area and
the circumference of the circle.
2. Write a program to input the marks (out of 100) of a student in 5 subjects
and then display the total marks along with the percentage.
3. Write a program to input a number n and then display n2, n3 and n4
4. Write a program to input the values of principal, rate and time and then
print the value of simple interest. SI = (P*R*T)/100
5. Write a program to input the temperature in Celsius and convert to
Fahrenheit using the formula:
F = C*9/5 + 32
2
XI
Programs
6. Write a program to calculate the BMI(Body Mass Index) of a person.
© CS-DEPT DPS MATHURA ROAD
Input the weight of the person in kg and height in meters. BMI is calculated
as kg/m2
7. Find outputs of the following commands in Python:
(i) print("Hello") (ii) print(2+3,34-67)
(iii) print("2+3",2+3) (iv) print ('2+3',2+3,sep="=")
(v) print(2**3,3**2,sep='*') (vi) print(2**3, 2**-3, -2**3, (-2)**3, sep=" and ")
3
XI
Programs
8. Find error(s), if any, in the following statements:
© CS-DEPT DPS MATHURA ROAD
(i) print("three') (ii) Print(3) (iii) print(44'+'56)
(iv) print(3,2 sep=': ') (v) print "wisdom" (vi) print['33+44']
(vii) PRINT("15 August 1947")
Write a program to find distance in kilometers if distance is given in
metres.
8000 8kms
4
XI
Error in a Program
● Error/Bug: Any malfunction, which either “stops the normal execution of the
© CS-DEPT DPS MATHURA ROAD
program” OR “program execution with wrong results” is known as an error/bug
in the program. Removal of Bug from a program is known as debugging.
There are different types of errors in a Python program:
Syntax error: Like other programming languages, 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.
For example, parentheses must be in pairs, so the expression (10 + 12) is
syntactically correct, whereas (7 + 11 is not due to absence of right
parenthesis. Such errors need to be removed before the execution of the
program
5
XI
Syntax Errors - Examples
CODE WITH ERROR MESSAGE CORRECTED CODE
© CS-DEPT DPS MATHURA ROAD
0 = Sum SyntaxError: cannot assign Sum = 0
to literal
A + B = C SyntaxError: cannot assign C = A + B
to operator
School = "DPS’ SyntaxError: EOL while School = "DPS"
scanning string literal
A=10,B=20 SyntaxError: cannot assign A=10;B=20 OR
to literal A,B = 10,20
print("Good")) SyntaxError: unmatched ')' print("Good")
6
XI
Errors in a Program
A logical error is a bug in the program that causes it to behave incorrectly. A
© CS-DEPT DPS MATHURA ROAD
logical error 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.
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.
7
XI
Errors in a Program
A logical error is a bug in the program that causes it to behave incorrectly. A logical
© CS-DEPT DPS MATHURA ROAD
error 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. The only evidence
to the existence of logical errors is the wrong output.
To calculate the perimeter of a To calculate the average of 3
rectangle subjects
Perimeter = 2*(Length * Avg = Math + English +
Breadth) Incorrect Science/3 Incorrect
Correct Statement Correct Statement
Perimeter = 2*(Length + Breadth) Avg = (Math + English +
Science)/3 8
XI
Errors in a Program
A runtime error causes abnormal termination of program while it is executing.
© CS-DEPT DPS MATHURA ROAD
Runtime error is when the statement is correct syntactically, but the interpreter
cannot execute it. Runtime errors do not appear until after the program starts
running or executing. For example, we have a statement having division operation in
the program. By mistake, if the denominator entered is zero then it will give a
runtime error like “division by zero”.
A=int(input("Numerator")) The program shown above will throw
B=int(input("Denominator")) an Exception (ZeroDivisionError),
C=A/B if user enters 0 for the variable B.
print(C) The program shown above will throw an Exception
(ValueError), if user enters a non numeric value
for example Hello for any of the variables A or B.
9
XI
Standard Data Types of Python
Data can be of many types viz. Character, integer, real, string etc. Numbers
© CS-DEPT DPS MATHURA ROAD
without fractions indicate integer data, number with fractions represent real
data, True and False indicate boolean data, anything enclosed within quotes
indicate string data in Python. Since the data to be dealt with are of many types,
a programming language must be capable to handle all types of data.
10
XI
Different Data Types in Python
Every value in Python has a datatype. Python has the following built-in core data
© CS-DEPT DPS MATHURA ROAD
types:
DATA TYPES IN PYTHON
NUMBERS SEQUENCES SETS NONE MAPPINGS
INTEGER COMPLEX STRINGS
DICTIONARIES
FLOATING
LISTS
POINT NUMBERS
BOOLEAN
TUPLES
11
XI
Data Types in Python - Number
Number data types stores numeric values only. It is further classified into int,
© CS-DEPT DPS MATHURA ROAD
float and complex.
Type/Class Description Examples
int Integer numbers -12,-3,0,99,370
float Real or floating numbers -8.09,90.87,8E+9,7.33E-9
complex Complex numbers 8 - 9j, 2 + 3j
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting
of two constants, True and False. Boolean True is non-zero, non-null and non-empty
and Boolean False is the value zero.
12
XI
Number Data Type
int - These are whole numbers, having no fractional parts. They are numeric values
© CS-DEPT DPS MATHURA ROAD
with no decimal point. They can be positive or negative.
float - A number containing a decimal point or an exponent sign represents float data
type. The float data type can include both positive and negative floating point
numbers. The fractional number can be written in two forms:
● Fractional form (normal decimal notation) e.g. 3.2901, 0.009 etc.
● Exponent Notation e.g. 3.50062E09, 0.43E-02 etc.
They have two advantages over integers, they represent values between the integers
and they represent larger range of values. But they also suffer from one
disadvantage, that the floating point operations are usually slower than integer
operations. In Python, they have a precision of 15 digits (double precision). 13
XI
Number Data Type (contd…)
complex - Mathematically, a complex number is a number of the form A+Bi, where A
© CS-DEPT DPS MATHURA ROAD
represents the real part and i is the imaginary number. The real and imaginary part
of a complex number are floating point number.
Python represents complex number using complex data type by specifying the
number in the form real + imag j i.e the imaginary part of the number in Python is
represented by j (instead of i).
For example for Complex data, 3 + 4j , 3 denotes the real part and 4 denotes the
imaginary part. The real and imaginary part of the complex number is stored as a
float.
14
XI
Number Data Type (contd…)
The range of the numbers represented through the numeric data type is given
© CS-DEPT DPS MATHURA ROAD
below:
Data Type Range
int (Integer) An unlimited range, subject to the memory
availability
float (Floating point An unlimited range, subject to the memory
numbers) availability
complex (Complex Same as the floating point numbers as the
numbers) real and imaginary parts are float values
bool (Boolean) Only two values - True and False
15
XI
Sequence Data Types
A Python sequence is an ordered collection of items where each item is indexed by
© CS-DEPT DPS MATHURA ROAD
an integer. There are three Sequence data types in Python, namely:
● String
● Tuple
● Lists
16
XI
String Data Type
A string data type lets you hold string data i.e, any number of valid characters
© CS-DEPT DPS MATHURA ROAD
enclosed in a set of quotation marks. A string can hold any type of known characters
ie., letters, numbers and special characters.
A Python string is a sequence of characters and each character can be individually
accessed using its index. Strings are stored as individual characters in contiguous
locations, with two way index for each location.
➢ 0, 1, 2,.... In the forward direction
➢ -1, -2, -3.... In the backward direction
For example : “computer science”, ‘DPS MATHURA ROAD’
17
XI
List Data Type
© CS-DEPT DPS MATHURA ROAD
List represents a list of comma separated values of any data type between
square brackets ([ ]).
>>> L=[1,2,3,4,5]
>>> print(L)
[1, 2, 3, 4, 5]
>>> type(L)
<class 'list'>
18
XI
Tuple Data Type
© CS-DEPT DPS MATHURA ROAD
A Tuple is a ordered collection of elements that cannot be changed i.e.
they are not modifiable (immutable). Tuples are group of comma
separated values of any data type within parentheses().
19
XI
NONE
None is a special data type with a single value. It is used to signify the absence of
© CS-DEPT DPS MATHURA ROAD
value in a situation. None supports no special operations, and it is neither False nor 0
(zero).
>>> a=None
>>> type(a)
<class 'NoneType'>
20
XI
Mapping - Dictionary Data Type
Mapping is an unordered data type in Python. Currently, there is only one
© CS-DEPT DPS MATHURA ROAD
standard mapping data type in Python called dictionary. A dictionary is an
unordered set of comma separated key:value pairs, within { }, with the
requirement that within a dictionary, no two keys can be the same (there are
unique keys within a dictionary)
key value
21
XI
Mutable and Immutable Data Types
© CS-DEPT DPS MATHURA ROAD
22
XI
Mutable and Immutable Data Types
● Variables whose values can be changed after they are created and
© CS-DEPT DPS MATHURA ROAD
assigned are called mutable.
● Variables whose values cannot be changed after they are created and
assigned are called immutable. In Python, the following data types are
immutable :
integers, floating point numbers, string, boolean, tuples
● 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.
● Python data types can be classified into mutable and immutable.
23
XI
Mutable and Immutable Data Types
Consider there are three variables as shown:
© CS-DEPT DPS MATHURA ROAD
Variable names are only indicators or references to value objects, ie. data
values.The variables themselves do not store any values, they are not
storage containers. It appears from the above statements that the value of
the variables are changing, but it is not so.
24
XI
Mutable and Immutable Data Types
In fact the variable names are made to refer to new immutable integer
© CS-DEPT DPS MATHURA ROAD
objects. Changing in place means changing or modifying the same value in the
same memory location.
Each time you change a variable’s
value, its reference memory
address also changes. These
variables are NOT STORAGE
CONTAINERS, they are not fixed
memory address where the value
changes. Hence they are
IMMUTABLE.
25
XI
Mutable and Immutable Data Types
Mutable data types
© CS-DEPT DPS MATHURA ROAD
There are three mutable data types in Python: lists, dictionaries and sets.
Thus we see from this code that
values are modified but still
memory address of mutable data
type remains same.
26
XI
© CS-DEPT DPS MATHURA ROAD
THANK YOU!
DEPARTMENT OF COMPUTER SCIENCE
27
XI