Class 11 Computer Science Chapter 06 ยท 29 min read

๐Ÿ”ข Data Handling

Unit 1 ยท Ch 6 Sep 29, 2026
Chapter Quiz

Every program you will ever write does just ONE thing at its heart โ€” it takes data, works on it, and produces a result! ๐Ÿ“ฅโš™๏ธ๐Ÿ“ค But how does Python know that 25 is a number and "25" is text? Why does 7 / 2 give 3.5 but 7 // 2 gives 3? Why can you change a list but NOT a string? This chapter answers these BIG questions: What types of data can Python store? What are mutable and immutable types? How do operators and expressions work? How does Python convert one type into another? Let's handle some data! ๐Ÿ๐Ÿ”ข

๐Ÿ’ก How to use these notes

Focus especially on Mutable vs Immutable types, Division operators (/, //, %), Operator Precedence, is vs ==, and Type Conversion โ€” these produce MANY output-based questions every year!


6.1 ๐Ÿ Introduction

Data Handling means how a programming language stores, identifies, and processes different kinds of data. In Python, every value you use โ€” a number, a name, a list of marks โ€” has a data type, and you work on it using operators to form expressions.

graph LR
    DATA["๐Ÿ“ฆ Data\n(values like 25,\n'Riya', 3.14)"]
    TYPE["๐Ÿท๏ธ Data Type\n(int, str, float...)"]
    OPS["โž• Operators\n(+, -, ==, and...)"]
    EXPR["๐Ÿงฎ Expression\n(a + b * 2)"]
    RESULT["โœ… Result"]

    DATA --> TYPE --> OPS --> EXPR --> RESULT

    style TYPE fill:#2196F3,color:#fff
    style OPS fill:#FF9800,color:#fff
    style RESULT fill:#4CAF50,color:#fff

Think of it this way: Data types are like containers in a kitchen โ€” you store milk in a bottle, rice in a jar, and eggs in a tray. Each container is designed for ONE kind of item. Python similarly uses the RIGHT "container" (data type) for each kind of value!


6.2 ๐Ÿท๏ธ Data Types

A data type tells Python what kind of value a variable holds and what operations can be performed on it. You can check the type of any value using the type() function.

>>> type(25)
<class 'int'>
>>> type(3.14)
<class 'float'>
>>> type("Hello")
<class 'str'>
>>> type(True)
<class 'bool'>

Python's Core Data Types:

graph TD
    DT["๐Ÿท๏ธ PYTHON DATA TYPES"]
    NUM["๐Ÿ”ข Numbers"]
    SEQ["๐Ÿ“š Sequences"]
    MAP["๐Ÿ—‚๏ธ Mappings"]
    NONE["๐Ÿšซ None"]

    INT["int\n(Integer)"]
    BOOL["bool\n(Boolean)"]
    FLOAT["float\n(Floating point)"]
    COMP["complex\n(Complex numbers)"]

    STR["str\n(String)"]
    LIST["list"]
    TUP["tuple"]

    DICT["dict\n(Dictionary)"]

    DT --> NUM
    DT --> SEQ
    DT --> MAP
    DT --> NONE
    NUM --> INT
    NUM --> BOOL
    NUM --> FLOAT
    NUM --> COMP
    SEQ --> STR
    SEQ --> LIST
    SEQ --> TUP
    MAP --> DICT

    style NUM fill:#2196F3,color:#fff
    style SEQ fill:#FF9800,color:#fff
    style MAP fill:#4CAF50,color:#fff
    style NONE fill:#9E9E9E,color:#fff

6.2.1 Numbers ๐Ÿ”ข

Python has four numeric types:

๐Ÿ”ข

Integer (int)

Whole numbers without a decimal point โ€” positive, negative or zero; can be of ANY size

25-7012345678901234
โœ…

Boolean (bool)

Represents truth values; a special sub-type of int where True = 1 and False = 0

TrueFalse
๐ŸŽฏ

Floating Point (float)

Numbers WITH a decimal point; also written in exponent (E) notation

3.14-0.52.5E3
๐ŸŒ€

Complex (complex)

Numbers of the form a + bj, where j is the imaginary unit (โˆš-1)

3 + 4j2j

1. Integers (int) โ€” Python integers have unlimited precision: they can be as large as your computer's memory allows!

>>> big = 2 ** 100
>>> print(big)
1267650600228229401496703205376

2. Booleans (bool) โ€” have only two values, True and False (capital T and F). Internally, True behaves like 1 and False like 0.

>>> True + True
2
>>> False * 10
0
>>> bool(0), bool(15), bool("")
(False, True, False)

3. Floating Point Numbers (float) โ€” can be written in two forms:

Form Example Meaning
Fractional Form 17.5, -0.00625 Normal decimal notation
Exponent Form 1.75E1, -6.25E-3 Mantissa ร— 10^exponent (1.75E1 = 17.5)
๐Ÿง  Floats are Approximate! ๐Ÿง 

Floats are stored with limited precision (about 15 significant digits), so tiny rounding errors can appear: 0.1 + 0.2 gives 0.30000000000000004, NOT exactly 0.3! Integers, on the other hand, are always exact.

4. Complex Numbers (complex) โ€” written as a + bj, where a is the real part and b is the imaginary part. Python uses j (not i) for the imaginary unit.

>>> z = 3 + 4j
>>> z.real
3.0
>>> z.imag
4.0
๐Ÿ“‹ Board Exam Tip

"What will z.real and z.imag return for z = 3 + 4j?" โ€” 1-mark question! Answer: 3.0 and 4.0 โ€” both parts of a complex number are always returned as floats, even if you wrote them as integers.


6.2.2 Strings (str) ๐Ÿ”ค

A string is a sequence of characters enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' / """ """) for multi-line text.

name = 'Riya'
school = "Delhi Public School"
address = """House No. 12,
Park Street,
Kolkata"""

Each character in a string has a position called an index. Python supports two-way indexing:

  String :    P     Y     T     H     O     N
 Forward :    0     1     2     3     4     5
Backward :   -6    -5    -4    -3    -2    -1
>>> word = "PYTHON"
>>> word[0]
'P'
>>> word[-1]
'N'
>>> len(word)
6
๐Ÿ”‘ Rule

For a string of length n, forward indices go from 0 to n-1 and backward indices go from -1 to -n. Accessing an index outside this range gives an IndexError.


6.2.3 Lists and Tuples ๐Ÿ“š

Both lists and tuples store an ordered collection of values (which can be of different types).

๐Ÿ“‹

List

Values in SQUARE brackets; can be CHANGED after creation (mutable)

Square brackets [ ]
๐Ÿ“ฆ

Tuple

Values in ROUND brackets; CANNOT be changed after creation (immutable)

Round brackets ( )
marks = [85, 90, 78]       # list
marks[0] = 95              # โœ… allowed โ€” lists can be changed
print(marks)               # [95, 90, 78]

days = ("Mon", "Tue", "Wed")   # tuple
# days[0] = "Sun"          # โŒ TypeError โ€” tuples cannot be changed

6.2.4 Dictionaries (dict) ๐Ÿ—‚๏ธ

A dictionary is an unordered-by-position collection of key : value pairs enclosed in curly braces { }. You access values using their keys, not index numbers.

student = {"name": "Aman", "class": 11, "marks": 92}
print(student["name"])     # Aman
student["marks"] = 95      # values can be changed

Analogy: A dictionary is exactly like a real dictionary โ€” you look up a word (key) to find its meaning (value). You never search a dictionary by "page number 237"!

6.2.5 The None Type ๐Ÿšซ

None is a special value that means "nothing" or "no value". Its type is NoneType.

>>> result = None
>>> type(result)
<class 'NoneType'>
โš  Common Mistake

None is NOT the same as 0, False, or an empty string "". It is a separate value meaning "absence of a value". Also note the capital N โ€” writing none gives a NameError.


6.3 ๐Ÿ”„ Mutable and Immutable Types

This is one of the MOST important concepts of this chapter! Python data types are divided into two groups based on whether their value can be changed in place.

graph TD
    TYPES["๐Ÿ”„ PYTHON TYPES"]
    IMM["๐Ÿ”’ IMMUTABLE\n(cannot be changed in place)"]
    MUT["๐Ÿ”“ MUTABLE\n(can be changed in place)"]

    I1["int, float, complex, bool"]
    I2["str (strings)"]
    I3["tuple"]

    M1["list"]
    M2["dict (dictionary)"]
    M3["set"]

    TYPES --> IMM
    TYPES --> MUT
    IMM --> I1
    IMM --> I2
    IMM --> I3
    MUT --> M1
    MUT --> M2
    MUT --> M3

    style IMM fill:#F44336,color:#fff
    style MUT fill:#4CAF50,color:#fff

6.3.1 Every Object Has Three Things ๐Ÿ”

Every value (object) in Python has:

๐Ÿ†”

Identity

The memory address of the object; never changes during the object's life

id(x)
๐Ÿท๏ธ

Type

What kind of object it is

type(x)
๐Ÿ’Ž

Value

The actual data stored in the object

print(x)

6.3.2 Immutable Types ๐Ÿ”’

For immutable types, the value stored at a memory location can never be changed. When you "change" the variable, Python actually creates a NEW object at a new memory location and makes the variable point to it.

>>> a = 10
>>> id(a)
140714234567120        # (your number will be different)
>>> a = a + 5
>>> id(a)
140714234567280        # a DIFFERENT address! a new object 15 was created
graph LR
    A1["a"]
    V10["๐Ÿ”’ 10\n(old object)"]
    V15["๐Ÿ”’ 15\n(new object)"]

    A1 -.->|"before"| V10
    A1 -->|"after a = a + 5"| V15

    style V10 fill:#9E9E9E,color:#fff
    style V15 fill:#2196F3,color:#fff

Analogy: Immutable objects are like a printed book. You can't erase a word in it โ€” to "change" it, a NEW edition must be printed, and you start reading the new one. The old book still exists (until it's thrown away)!

6.3.3 Mutable Types ๐Ÿ”“

For mutable types, the value can be changed in place โ€” the memory address (id) stays the SAME.

>>> marks = [70, 80, 90]
>>> id(marks)
2034567891200
>>> marks[0] = 100
>>> id(marks)
2034567891200          # SAME address โ€” the list was changed in place
>>> marks
[100, 80, 90]

Analogy: Mutable objects are like a whiteboard โ€” you can erase and rewrite on the SAME board as many times as you like!

Feature Immutable Types Mutable Types
Change in place? โŒ No โœ… Yes
id() after change Changes (new object is created) Remains the same
Examples int, float, bool, complex, str, tuple list, dict, set
๐Ÿง  Memory Trick: "LDS are Mutable" ๐Ÿง 

Only List, Dictionary and Set are mutable โ€” remember "LDS" (like the famous "Lucky Draw Scheme" ๐ŸŽŸ๏ธ). EVERYTHING else you study in Class 11 is immutable!

๐Ÿ“‹ Board Exam Tip

"What are mutable and immutable types? Give two examples of each." โ€” 2-mark question, asked EVERY year! Answer: Mutable types are those whose values can be changed in place without changing their memory address โ€” e.g., list, dictionary. Immutable types are those whose values cannot be changed in place; any change creates a new object โ€” e.g., int, string, tuple.


6.4 โž• Operators

Operators are symbols that perform operations on values. The values on which they operate are called operands.

        a    +    b
        โ†‘    โ†‘    โ†‘
  operand operator operand
graph TD
    OPS["โž• PYTHON OPERATORS"]
    AR["๐Ÿ”ข Arithmetic\n+ - * / // % **"]
    REL["โš–๏ธ Relational\n< > <= >= == !="]
    LOG["๐Ÿง  Logical\nand or not"]
    ASG["๐Ÿ“ Assignment\n= += -= *= ..."]
    ID["๐Ÿ†” Identity\nis, is not"]
    MEM["๐Ÿ“ฆ Membership\nin, not in"]

    OPS --> AR
    OPS --> REL
    OPS --> LOG
    OPS --> ASG
    OPS --> ID
    OPS --> MEM

    style AR fill:#2196F3,color:#fff
    style REL fill:#FF9800,color:#fff
    style LOG fill:#9C27B0,color:#fff
    style ASG fill:#4CAF50,color:#fff
    style ID fill:#F44336,color:#fff
    style MEM fill:#795548,color:#fff

6.4.1 Arithmetic Operators ๐Ÿ”ข

Operator Name Example Result
+ Addition 7 + 2 9
- Subtraction 7 - 2 5
* Multiplication 7 * 2 14
/ Division (true division) 7 / 2 3.5
// Floor Division 7 // 2 3
% Modulus (remainder) 7 % 2 1
** Exponentiation (power) 7 ** 2 49

Unary operators: + and - can also work on a single operand: -a (negation), +a.

The three division operators โ€” the most tested topic!

โž—

True Division ( / )

Always gives a FLOAT result, even if the division is exact

10 / 2 โ†’ 5.0
โฌ‡๏ธ

Floor Division ( // )

Gives the quotient rounded DOWN to the nearest whole number

7 // 2 โ†’ 3
๐Ÿ”

Modulus ( % )

Gives the REMAINDER after division

7 % 2 โ†’ 1
print(10 / 2)      # 5.0   (float, not 5!)
print(17 // 5)     # 3
print(17 % 5)      # 2
print(17.0 // 5)   # 3.0   (float operand โ†’ float result)
print(-17 // 5)    # -4    (rounded DOWN towards minus infinity!)
print(-17 % 5)     # 3
โš  Common Mistake

Students write -17 // 5 = -3 โ€” โŒ WRONG! Floor division always rounds DOWN (towards negative infinity). โˆ’3.4 rounded down is โˆ’4, not โˆ’3. So -17 // 5 gives -4, and -17 % 5 gives 3 (because โˆ’4 ร— 5 + 3 = โˆ’17).

๐Ÿ”‘ Rule

For any numbers a and b: a == (a // b) * b + (a % b). Use this to check your floor division and modulus answers in output questions!

Exponentiation is Right-Associative:

print(2 ** 3 ** 2)    # 512 โ†’ evaluated as 2 ** (3 ** 2) = 2 ** 9
print((2 ** 3) ** 2)  # 64
print(-2 ** 2)        # -4  โ†’ evaluated as -(2 ** 2)

Arithmetic operators on strings:

print("Hi" + "There")   # HiThere   (concatenation)
print("Ha" * 3)          # HaHaHa    (replication)
# print("Age" + 16)      # โŒ TypeError: can only concatenate str (not "int") to str
๐Ÿ“‹ Board Exam Tip

"Differentiate between / and // operators with an example." โ€” 2-mark question, asked almost EVERY year! Answer: / performs true division and always returns a float (e.g., 7 / 2 gives 3.5). // performs floor division and returns the quotient rounded down to the nearest whole number (e.g., 7 // 2 gives 3).


6.4.2 Relational (Comparison) Operators โš–๏ธ

Relational operators compare two values and always return a Boolean result (True or False).

Operator Meaning Example Result
< Less than 5 < 8 True
> Greater than 5 > 8 False
<= Less than or equal to 5 <= 5 True
>= Greater than or equal to 4 >= 5 False
== Equal to 5 == 5.0 True
!= Not equal to 5 != 8 True
print("apple" < "banana")   # True  (compared letter by letter using Unicode values)
print("Zoo" < "apple")      # True  (uppercase letters come BEFORE lowercase: 'Z' = 90, 'a' = 97)
print(1 < 5 < 10)           # True  (chained comparison = 1 < 5 and 5 < 10)
โš  Common Mistake

Don't confuse = (assignment โ€” stores a value) with == (comparison โ€” checks equality). if a = 5: is a SyntaxError; the correct form is if a == 5:.


6.4.3 Identity Operators ๐Ÿ†”

Identity operators check whether two variables refer to the SAME object in memory (same id()), not just equal values.

๐Ÿ†”

is

True if both operands point to the SAME object

a is b
๐Ÿšซ

is not

True if both operands point to DIFFERENT objects

a is not b
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # True   โ†’ same VALUE
print(a is b)   # False  โ†’ different OBJECTS in memory
print(a is c)   # True   โ†’ c points to the SAME object as a
graph LR
    A["a"]
    C["c"]
    B["b"]
    L1["๐Ÿ“‹ [1, 2, 3]\n(object 1)"]
    L2["๐Ÿ“‹ [1, 2, 3]\n(object 2)"]

    A --> L1
    C --> L1
    B --> L2

    style L1 fill:#2196F3,color:#fff
    style L2 fill:#FF9800,color:#fff
๐Ÿ“‹ Board Exam Tip

"Differentiate between == and is operators." โ€” 2-mark question! Answer: == compares the values of two objects, whereas is checks whether both variables refer to the same object in memory (i.e., have the same id()). Two lists with equal values are == but not is.


6.4.4 Logical Operators ๐Ÿง 

Logical operators combine conditions: and, or, not.

Operator Result is True when... Example Result
and BOTH conditions are true (5 > 3) and (2 > 4) False
or AT LEAST ONE condition is true (5 > 3) or (2 > 4) True
not The condition is false (reverses it) not (5 > 3) False

Truth Value Testing โ€” In Python, every value is either "truthy" or "falsy":

โŒ

Falsy Values

Treated as False in conditions

00.00j""[](){}NoneFalse
โœ…

Truthy Values

EVERYTHING else is treated as True

5-1"Hi"[0]" "

and / or return one of the OPERANDS, not always True/False:

print(0 or 7)         # 7     โ†’ first operand is falsy, so returns the second
print(5 or 7)         # 5     โ†’ first operand is truthy, so returns it (second not checked)
print(5 and 7)        # 7     โ†’ first is truthy, so returns the second
print(0 and 7)        # 0     โ†’ first is falsy, so returns it (second not checked)
print(not 5)          # False โ†’ not ALWAYS returns True or False
print("" or "Empty")  # Empty
๐Ÿ”‘ Rule (Short-Circuit Evaluation)

x or y โ†’ if x is truthy, return x; else return y. x and y โ†’ if x is falsy, return x; else return y. Python stops evaluating as soon as the result is known โ€” the second operand may never be checked!


6.4.5 Assignment and Augmented Assignment Operators ๐Ÿ“

The = operator assigns a value to a variable. Augmented assignment operators combine an arithmetic operation with assignment.

Operator Example Same as
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
//= x //= 5 x = x // 5
%= x %= 5 x = x % 5
**= x **= 5 x = x ** 5
x = 10
x += 5      # x is now 15
x *= 2      # x is now 30
x //= 4     # x is now 7
print(x)    # 7
โš  Common Mistake

Python does NOT have ++ or -- operators like C/Java. x++ gives a SyntaxError. Use x += 1 instead.


6.4.6 Membership Operators ๐Ÿ“ฆ

Membership operators check whether a value is present in a sequence (string, list, tuple, dictionary keys).

print("a" in "Python")          # False
print("th" in "Python")         # True
print(3 in [1, 2, 3])           # True
print(5 not in (1, 2, 3))       # True
print("name" in {"name": "Aman"})  # True  โ†’ checks KEYS of a dictionary

6.4.7 Operator Precedence and Associativity ๐Ÿชœ

When an expression has multiple operators, Python follows a fixed order called precedence (just like BODMAS in maths!).

graph TD
    P1["1๏ธโƒฃ ( )  Parentheses โ€” HIGHEST"]
    P2["2๏ธโƒฃ **  Exponentiation"]
    P3["3๏ธโƒฃ +x, -x  Unary plus / minus"]
    P4["4๏ธโƒฃ *, /, //, %"]
    P5["5๏ธโƒฃ +, -  (Binary)"]
    P6["6๏ธโƒฃ <, <=, >, >=, ==, !=,\nis, is not, in, not in"]
    P7["7๏ธโƒฃ not"]
    P8["8๏ธโƒฃ and"]
    P9["9๏ธโƒฃ or โ€” LOWEST"]

    P1 --> P2 --> P3 --> P4 --> P5 --> P6 --> P7 --> P8 --> P9

    style P1 fill:#F44336,color:#fff
    style P2 fill:#FF9800,color:#fff
    style P9 fill:#4CAF50,color:#fff

Associativity decides the order when operators of the same precedence appear together:

  • Almost all operators are left-to-right associative: 20 / 4 * 2 = (20 / 4) * 2 = 10.0
  • `is right-to-left** associative:2 ** 3 ** 2=2 ** 9=512`

Example โ€” Evaluate 12 + 3 * 2 ** 2 // 5 - 1:

12 + 3 * 2 ** 2 // 5 - 1
= 12 + 3 * 4 // 5 - 1       (** first)
= 12 + 12 // 5 - 1          (* and // left to right: 3 * 4 = 12)
= 12 + 2 - 1                (12 // 5 = 2)
= 13                        (+ and - left to right)
๐Ÿง  Memory Trick: "PEU-MDA-RNAO" ๐Ÿง 

Parentheses โ†’ Exponent โ†’ Unary โ†’ Multiply/Divide โ†’ Add/Subtract โ†’ Relational โ†’ Not โ†’ And โ†’ Or Think: "Please Eat Undi โ€” My Dear Aunty Really Needs Another Orange!" ๐ŸŠ

๐Ÿ“‹ Board Exam Tip

"Evaluate the expression / predict the output" โ€” 2 to 3-mark questions are asked every year using precedence! Always solve step by step, write each step, and watch out for ** (right-to-left) and / (always a float).


6.5 ๐Ÿงฎ Expressions

An expression is a valid combination of operators, literals and variables that Python evaluates to produce a value.

๐Ÿ”ข

Arithmetic Expression

Uses arithmetic operators on numbers

a + b * 2
โš–๏ธ

Relational Expression

Compares values; result is True/False

x > y
๐Ÿง 

Logical Expression

Combines conditions using and/or/not

a > 5 and b < 10
๐Ÿ”ค

String Expression

Uses + and * on strings

"Hi" * 3

6.5.1 Type Conversion ๐Ÿ”

When an expression has values of different types, Python must convert them to a common type. There are two ways this happens:

graph TD
    TC["๐Ÿ” TYPE CONVERSION"]
    IMP["๐Ÿค– Implicit Conversion\n(Automatic โ€” done by Python)\nAlso called Coercion"]
    EXP["๐Ÿง‘โ€๐Ÿ’ป Explicit Conversion\n(Done by the programmer)\nAlso called Type Casting"]

    TC --> IMP
    TC --> EXP

    style IMP fill:#2196F3,color:#fff
    style EXP fill:#FF9800,color:#fff

1. Implicit Type Conversion (Coercion) โ€” Python automatically converts the "smaller" type to the "bigger" type so that no data is lost:

bool  โ†’  int  โ†’  float  โ†’  complex
a = 5          # int
b = 2.5        # float
c = a + b      # int is automatically converted to float
print(c, type(c))    # 7.5 <class 'float'>
print(True + 3.5)    # 4.5  (True โ†’ 1 โ†’ 1.0)

2. Explicit Type Conversion (Type Casting) โ€” the programmer converts a value using type-conversion functions:

Function Converts to Example Result
int() Integer int(7.9) 7 (decimal part is cut off, not rounded)
int() Integer int("25") 25
float() Float float(5) 5.0
float() Float float("3.5") 3.5
str() String str(100) '100'
bool() Boolean bool(0) False
complex() Complex complex(2, 3) (2+3j)
age = input("Enter your age: ")     # input() ALWAYS returns a string
print(type(age))                    # <class 'str'>
age = int(age)                      # explicit conversion to int
print(age + 1)
โš  Common Mistake

int("3.5") gives a ValueError โ€” a string containing a decimal point cannot be converted DIRECTLY to int. Use int(float("3.5")) instead, which gives 3. Similarly, int("abc") is a ValueError.

๐Ÿ“‹ Board Exam Tip

"Differentiate between implicit and explicit type conversion." โ€” 2-mark question! Answer: Implicit conversion is done automatically by Python when an expression has mixed types (e.g., 5 + 2.5 gives 7.5, a float). Explicit conversion (type casting) is done by the programmer using functions like int(), float(), str() (e.g., int("25") gives 25).


6.5.2 Working with the math Module ๐Ÿ“

Python's math module provides ready-made mathematical functions. You must import it first.

import math
print(math.sqrt(49))      # 7.0
print(math.pow(2, 5))     # 32.0
print(math.ceil(4.2))     # 5
print(math.floor(4.8))    # 4
print(math.fabs(-7.5))    # 7.5
print(math.pi)            # 3.141592653589793
โˆš

sqrt(x)

Square root of x; returns a float

math.sqrt(16) โ†’ 4.0
โฌ†๏ธ

ceil(x)

Smallest integer GREATER than or equal to x

math.ceil(4.2) โ†’ 5
โฌ‡๏ธ

floor(x)

Largest integer LESS than or equal to x

math.floor(4.8) โ†’ 4
๐Ÿ’ช

pow(x, y)

x raised to the power y; returns a float

2 to the power 3 โ†’ 8.0
๐Ÿ“

fabs(x)

Absolute value of x as a float

math.fabs(-3) โ†’ 3.0

You'll study the math, random and statistics modules in detail in the Python Modules chapter.

Writing maths formulas as Python expressions:

Mathematical Expression Python Expression
aยฒ + bยฒ a ** 2 + b ** 2
โˆš(bยฒ โˆ’ 4ac) math.sqrt(b ** 2 - 4 * a * c)
(a + b) / 2 (a + b) / 2
ฯ€rยฒ math.pi * r ** 2
|x โˆ’ y| abs(x - y)

6.6 ๐Ÿž Errors in a Program

While writing programs, you WILL make mistakes โ€” that's normal! Errors (also called bugs) are of three main types, and removing them is called debugging.

graph TD
    ERR["๐Ÿž ERRORS"]
    SYN["โœ๏ธ Syntax Error\n(Compile-time)\nRules of the language broken"]
    RUN["๐Ÿ’ฅ Runtime Error\n(Exception)\nProgram crashes while running"]
    LOG["๐Ÿค” Logical Error\nProgram runs but gives\nWRONG output"]

    ERR --> SYN
    ERR --> RUN
    ERR --> LOG

    style SYN fill:#FF9800,color:#fff
    style RUN fill:#F44336,color:#fff
    style LOG fill:#9C27B0,color:#fff
Error Type When is it found? Example
Syntax Error Before the program runs print("Hi" (missing bracket), if a = 5:
Runtime Error While the program is running 10 / 0 โ†’ ZeroDivisionError; int("abc") โ†’ ValueError
Logical Error Only when you check the output Writing avg = a + b / 2 instead of (a + b) / 2

Common Runtime Errors (Exceptions):

โž—

ZeroDivisionError

Dividing a number by zero

5 / 0
๐Ÿท๏ธ

NameError

Using a variable that was never defined

print(total)
๐Ÿ”€

TypeError

Operation on incompatible types

"5" + 5
๐Ÿ”ข

ValueError

Right type but invalid value

int("hello")
๐Ÿ“

IndexError

Index out of the valid range

"abc"[5]
๐Ÿ“‹ Board Exam Tip

"Differentiate between syntax errors and logical errors." โ€” 2-mark question! Answer: A syntax error occurs when the rules (grammar) of Python are violated; the program does not run at all (e.g., missing colon). A logical error occurs when the program runs without crashing but produces wrong output due to a mistake in logic (e.g., wrong formula).


โš ๏ธ Common Errors and Misconceptions

Mistake What's Wrong Correct Understanding
โŒ 10 / 2 gives 5 / always returns a float โœ… 10 / 2 gives 5.0
โŒ -7 // 2 gives -3 Floor division rounds DOWN โœ… -7 // 2 gives -4
โŒ Strings are mutable You can't change a character in place โœ… Strings are immutable; s[0] = 'X' gives a TypeError
โŒ == and is mean the same == compares values, is compares identity โœ… Equal lists are == but may not be is
โŒ int(7.9) gives 8 int() truncates, it does not round โœ… int(7.9) gives 7
โŒ input() returns a number when you type a number input() always returns a string โœ… Convert using int() or float()
โŒ 2 ** 3 ** 2 = 64 ** is right-associative โœ… It equals 2 ** 9 = 512
โŒ 5 or 7 gives True or returns one of the operands โœ… 5 or 7 gives 5
โŒ Python has x++ No increment operator in Python โœ… Use x += 1

๐Ÿ”‘ Quick Revision โ€” Exam Ready!

Data Types โ€” One-Line Summary:

  • int โ†’ Whole numbers, unlimited size (25, -7)
  • bool โ†’ True / False (sub-type of int: True = 1, False = 0)
  • float โ†’ Decimal numbers, ~15 digit precision (3.14, 2.5E3)
  • complex โ†’ a + bj; .real and .imag return floats
  • str โ†’ Text in quotes; two-way indexing (0 to n-1, -1 to -n)
  • list [ ] โ†’ Ordered, mutable
  • tuple ( ) โ†’ Ordered, immutable
  • dict {key: value} โ†’ Key-value pairs, mutable
  • None โ†’ Absence of a value

Mutable vs Immutable:

๐Ÿ”“ Mutable ๐Ÿ”’ Immutable
list, dict, set int, float, bool, complex, str, tuple
id() stays same after change New object created on change

Division Operators:

Expression Result
17 / 5 3.4
17 // 5 3
17 % 5 2
-17 // 5 -4
-17 % 5 3

Precedence (high โ†’ low): () โ†’ ** โ†’ unary + - โ†’ * / // % โ†’ + - โ†’ relational / is / in โ†’ not โ†’ and โ†’ or

Type Conversion:

  • Implicit โ†’ automatic: bool โ†’ int โ†’ float โ†’ complex
  • Explicit โ†’ by programmer: int(), float(), str(), bool()

๐ŸŽฏ Sample Board Exam Questions

Q1: Very Short Answer [1 mark each]

a) What will be the output of print(type(10 / 2))? โ†’ <class 'float'>

b) Name any two immutable data types in Python. โ†’ int and str (also float, tuple, bool, complex)

c) What is the output of print(15 % 4)? โ†’ 3

d) Which function is used to get the memory address (identity) of an object? โ†’ id()

e) What is the output of print(2 ** 2 ** 3)? โ†’ 256 (evaluated as 2 ** 8)

f) What will bool("") return? โ†’ False


Q2: Short Answer [2 marks]

Q: What are mutable and immutable data types? Give two examples of each.

Mutable data types are those whose values can be changed in place, without changing their memory address (id). Examples: list, dictionary. Immutable data types are those whose values cannot be changed in place; any change creates a new object at a new memory address. Examples: int, string, tuple.


Q3: Short Answer [2 marks]

Q: Evaluate the following expressions:

a) 20 // 3 + 2 ** 3 % 5 b) not 5 > 3 or 4 < 2

Answer:

a) 20 // 3 + 2 ** 3 % 5
 = 20 // 3 + 8 % 5       (** first)
 = 6 + 3                 (// and % left to right)
 = 9

b) not 5 > 3 or 4 < 2
 = not True or False     (relational first)
 = False or False        (not before or)
 = False

Q4: Output Based [3 marks]

Q: Write the output of the following code:

a = 17
b = 5
print(a / b, a // b, a % b)
a, b = b, a
print(a ** 2 - b)
x = 0 or "Python"
print(x)
print(int(7.99) + float("2"))

Answer:

3.4 3 2
8
Python
9.0

Q5: Short Answer [2 marks]

Q: Differentiate between == and is operators with an example.

The == operator compares the values of two objects, while the is operator checks whether two variables refer to the same object in memory.

L1 = [1, 2]
L2 = [1, 2]
print(L1 == L2)   # True  โ†’ values are equal
print(L1 is L2)   # False โ†’ two different objects

โœ๏ธ Practice Problems

  1. Name the four numeric data types in Python and give one example of each.

  2. Explain two-way indexing in strings using the string "SCHOOL". What are the forward and backward indices of the letter 'H'?

  3. Explain, with the help of id(), why integers are called immutable but lists are called mutable.

  4. Predict the output:

    print(-22 // 5, -22 % 5)
    print(22 / 5, 22 // 5.0)
    print(3 * "ab" + "c")
  5. Evaluate: (a) 5 + 3 * 2 ** 2 - 8 / 4 (b) 10 > 5 and 3 > 4 or not 7 == 7

  6. What will print(0 and 5, 3 or 0, not 0) display? Explain each result.

  7. Write the Python expressions for: (a) (a + b)ยฒ (b) โˆš(xยฒ + yยฒ) (c) ยฝ ร— base ร— height

  8. Find the error(s) in the following code and rewrite it correctly:

    num = input("Enter a number")
    square = num ** 2
    Print("Square is" + square)
  9. Write a program that accepts the radius of a circle and prints its area and circumference using math.pi.

  10. Identify the type of error (syntax, runtime or logical) in each case: (a) print("Total" , 5 / 0) (b) if x == 5 print(x) (c) Calculating the average of three numbers as a + b + c / 3

Learning Support

Need Help With This Chapter?

Save key topics for exam revision, ask questions to teachers, or submit content corrections.

Verified Doubts & Teacher Answers

Take the Chapter 06 Quiz