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! ๐๐ข
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-7012345678901234Boolean (bool)
Represents truth values; a special sub-type of int where True = 1 and False = 0
TrueFalseFloating Point (float)
Numbers WITH a decimal point; also written in exponent (E) notation
3.14-0.52.5E3Complex (complex)
Numbers of the form a + bj, where j is the imaginary unit (โ-1)
3 + 4j2j1. 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 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
"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
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'>
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 |
Only List, Dictionary and Set are mutable โ remember "LDS" (like the famous "Lucky Draw Scheme" ๐๏ธ). EVERYTHING else you study in Class 11 is immutable!
"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.0Floor Division ( // )
Gives the quotient rounded DOWN to the nearest whole number
7 // 2 โ 3Modulus ( % )
Gives the REMAINDER after division
7 % 2 โ 1print(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
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).
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
"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)
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 bis not
True if both operands point to DIFFERENT objects
a is not ba = [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
"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""[](){}NoneFalseTruthy 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
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
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)
Parentheses โ Exponent โ Unary โ Multiply/Divide โ Add/Subtract โ Relational โ Not โ And โ Or Think: "Please Eat Undi โ My Dear Aunty Really Needs Another Orange!" ๐
"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 * 2Relational Expression
Compares values; result is True/False
x > yLogical Expression
Combines conditions using and/or/not
a > 5 and b < 10String Expression
Uses + and * on strings
"Hi" * 36.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)
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.
"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.0ceil(x)
Smallest integer GREATER than or equal to x
math.ceil(4.2) โ 5floor(x)
Largest integer LESS than or equal to x
math.floor(4.8) โ 4pow(x, y)
x raised to the power y; returns a float
2 to the power 3 โ 8.0fabs(x)
Absolute value of x as a float
math.fabs(-3) โ 3.0You'll study the
math,randomandstatisticsmodules 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 / 0NameError
Using a variable that was never defined
print(total)TypeError
Operation on incompatible types
"5" + 5ValueError
Right type but invalid value
int("hello")IndexError
Index out of the valid range
"abc"[5]"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;.realand.imagreturn 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
-
Name the four numeric data types in Python and give one example of each.
-
Explain two-way indexing in strings using the string
"SCHOOL". What are the forward and backward indices of the letter'H'? -
Explain, with the help of
id(), why integers are called immutable but lists are called mutable. -
Predict the output:
print(-22 // 5, -22 % 5) print(22 / 5, 22 // 5.0) print(3 * "ab" + "c") -
Evaluate: (a)
5 + 3 * 2 ** 2 - 8 / 4(b)10 > 5 and 3 > 4 or not 7 == 7 -
What will
print(0 and 5, 3 or 0, not 0)display? Explain each result. -
Write the Python expressions for: (a) (a + b)ยฒ (b) โ(xยฒ + yยฒ) (c) ยฝ ร base ร height
-
Find the error(s) in the following code and rewrite it correctly:
num = input("Enter a number") square = num ** 2 Print("Square is" + square) -
Write a program that accepts the radius of a circle and prints its area and circumference using
math.pi. -
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 asa + b + c / 3