A computer handles all kinds of data โ your age (a whole number), your percentage (a decimal), your name (text), and whether you passed (yes/no). Python keeps each kind in its own data type and uses operators to work on them. This chapter answers the BIG questions: What types of data does Python understand? Which data can be changed and which cannot? How do operators like /, //, % and `` work? In which order does Python solve an expression? And what kinds of errors can a program have?** Let's handle some data! ๐
The most tested topics are data types with examples, mutable vs immutable, / vs // vs %, operator precedence (output questions!), implicit vs explicit type conversion, and syntax vs runtime vs logical errors. Solve every expression yourself on paper FIRST, then check it in the Python Lab.
4.1 ๐ Introduction
Every value in Python has a type. The type decides what the value can do. You can add two numbers, but you can't divide a name by 2!
Analogy: Think of a kitchen ๐ณ. Milk goes in a jug, rice goes in a jar, and eggs go in a tray. Each item has the right container. In the same way, each kind of data has its right data type.
We can always check a value's type with the type() function:
print(type(25))
print(type(25.5))
print(type("25"))
print(type(True))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
4.2 ๐๏ธ Data Types in Python
graph TD
DT["๐๏ธ PYTHON DATA TYPES"]
NUM["๐ข Numbers"]
SEQ["๐ Sequences"]
MAP["๐บ๏ธ Mapping"]
NONE["๐ซ None"]
INT["int\n(whole numbers)"]
FLT["float\n(decimals)"]
CPX["complex\n(a + bj)"]
BOOL["bool\n(True / False)"]
STR["str\n(text)"]
LST["list\n[ ]"]
TUP["tuple\n( )"]
DICT["dict\n{ key: value }"]
DT --> NUM
DT --> SEQ
DT --> MAP
DT --> NONE
NUM --> INT
NUM --> FLT
NUM --> CPX
NUM --> BOOL
SEQ --> STR
SEQ --> LST
SEQ --> TUP
MAP --> DICT
style NUM fill:#2196F3,color:#fff
style SEQ fill:#4CAF50,color:#fff
style MAP fill:#FF9800,color:#fff
style NONE fill:#9E9E9E,color:#fff
4.2.1 Numbers ๐ข
int (Integer)
Whole numbers โ positive or negative โ with no decimal point. No size limit in Python!
25-70float (Floating point)
Numbers with a decimal point โ also written in E-notation
3.14-0.52.5E3complex
Numbers with a real part and an imaginary part j
3+4jbool (Boolean)
Only two values โ True and False. Internally True = 1 and False = 0
TrueFalsea = 2.5E3 # 2.5 ร 10ยณ
print(a)
print(True + True)
c = 3 + 4j
print(c.real, c.imag)
Output:
2500.0
2
3.0 4.0
25 and 25.0 and "25" are three DIFFERENT things!25 is an int, 25.0 is a float, and "25" is a str (text). Only the first two can be used in maths directly.
4.2.2 Sequences ๐
A sequence is an ordered collection of items. Each item has a position number called an index, starting from 0.
| Type | Written with | Example | Can change? |
|---|---|---|---|
| String (str) | Quotes ' ' or " " |
"Python" |
โ No |
| List | Square brackets [ ] |
[10, 20, 30] |
โ Yes |
| Tuple | Round brackets ( ) |
(10, 20, 30) |
โ No |
subject = "Python"
marks = [85, 90, 78]
days = ("Mon", "Tue", "Wed")
print(subject[0], marks[1], days[2])
Output:
P 90 Wed
You'll study lists in detail in the List Manipulation chapter.
4.2.3 Mapping โ Dictionary ๐บ๏ธ
A dictionary stores data in key : value pairs inside curly brackets { }. We look up a value by its key, not by a position.
student = {"name": "Riya", "class": 11, "marks": 92}
print(student["name"])
print(student["marks"])
Output:
Riya
92
Analogy: A dictionary is like your phone's contact list ๐ฑ โ you search by the name (key) to get the number (value).
4.2.4 None ๐ซ
None is a special value that means "nothing" or "no value yet". Its type is NoneType.
result = None
print(result)
print(type(result))
Output:
None
<class 'NoneType'>
4.3 ๐ Mutable and Immutable Types
This is one of the most important ideas in Python!
Mutable
The value CAN be changed in place after it is created
listdictImmutable
The value CANNOT be changed in place โ you can only make a new value
intfloatboolstrtupleAnalogy: A mutable type is like a whiteboard ๐งโ๐ซ โ you can erase one word and write another on the SAME board. An immutable type is like a printed certificate ๐ โ to change it, you need a brand-new certificate!
marks = [85, 90, 78]
marks[0] = 95 # allowed โ list is mutable
print(marks)
Output:
[95, 90, 78]
name = "Ravi"
name[0] = "K" # NOT allowed โ string is immutable
Output:
TypeError: 'str' object does not support item assignment
x = 5 to x = 6โฆ so int is mutable?" โ NO!Writing x = 6 does not change the value 5. It makes the name x point to a new value 6. The value 5 itself never changes โ so int is immutable.
x = 5 x โโโบ [5]
x = 6 x โโโบ [6] ([5] is left unchanged)| Mutable | Immutable |
|---|---|
| Can be changed in place | Cannot be changed in place |
| list, dictionary | int, float, complex, bool, string, tuple |
List and Dictionary can change โ think "Live Data". Everything else in this chapter is immutable!
"What are mutable and immutable data types? Give two examples of each." โ 2 marks Answer: Mutable types can be changed in place after creation โ e.g. list, dictionary. Immutable types cannot be changed in place; a new value is created instead โ e.g. int, string, tuple.
4.4 โ Operators
Operators are symbols that perform an operation on values called operands.
graph TD
OP["โ OPERATORS"]
A["๐งฎ Arithmetic\n+ - * / // % **"]
R["โ๏ธ Relational\n< > <= >= == !="]
L["๐ง Logical\nand or not"]
AS["๐ฅ Assignment\n= += -= *= /="]
M["๐ Membership\nin, not in"]
OP --> A
OP --> R
OP --> L
OP --> AS
OP --> M
style A fill:#2196F3,color:#fff
style R fill:#FF9800,color:#fff
style L fill:#9C27B0,color:#fff
style AS fill:#4CAF50,color:#fff
style M fill:#795548,color:#fff
4.4.1 Arithmetic Operators ๐งฎ
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 17 + 5 |
22 |
- |
Subtraction | 17 - 5 |
12 |
* |
Multiplication | 17 * 5 |
85 |
/ |
Division (always gives a float) | 17 / 5 |
3.4 |
// |
Floor division (quotient, rounded down) | 17 // 5 |
3 |
% |
Modulus (remainder) | 17 % 5 |
2 |
** |
Exponent (power) | 2 ** 3 |
8 |
The three kinds of division โ the MOST confused topic!
17 รท 5
โ
โโโโโโโโโโโผโโโโโโโโโโโ
โผ โผ โผ
17 / 5 17 // 5 17 % 5
= 3.4 = 3 = 2
(exact) (quotient) (remainder)
print(17 / 5)
print(17 // 5)
print(17 % 5)
print(10 / 2)
print(2 ** 10)
Output:
3.4
3
2
5.0
1024
Analogy: You have 17 laddoos ๐ฌ to share among 5 friends. Each friend gets 3 laddoos (
17 // 5), and 2 laddoos are left over (17 % 5). If you could cut them into pieces, each would get 3.4 (17 / 5)!
/ ALWAYS gives a float โ even when it divides exactly!10 / 2 gives 5.0, not 5. Use // if you want a whole number.
-17 // 5 gives -4, not -3, because โ3.4 rounded down is โ4. And -17 % 5 gives 3.
Handy uses of % and //:
num = 4728
print(num % 10) # last digit
print(num // 10) # number without the last digit
print(num % 2 == 0) # True if even
Output:
8
472
True
+ and * also work on strings:
print("Good" + "Morning")
print("Ha" * 3)
print("-" * 20)
Output:
GoodMorning
HaHaHa
--------------------
"Age: " + 16 gives TypeError. Use "Age: " + str(16) or print("Age:", 16).
4.4.2 Relational (Comparison) Operators โ๏ธ
Relational operators compare two values and always give 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")
print("A" == "a")
print(10 == "10")
Output:
True
False
False
= and == are NOT the same!= stores a value (x = 5). == compares two values (x == 5 gives True or False). Mixing them up is the #1 beginner mistake.
4.4.3 Logical Operators ๐ง
Logical operators join conditions.
| Operator | Gives True whenโฆ | Example | Result |
|---|---|---|---|
and |
Both conditions are True | 5 > 2 and 3 > 1 |
True |
or |
At least one condition is True | 5 > 9 or 3 > 1 |
True |
not |
Reverses the result | not 5 > 2 |
False |
Truth table:
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
Analogy: To enter a school event you need a ticket AND an ID card ๐๏ธ๐ชช โ both are required (
and). To pay at a shop you can use cash OR UPI ๐ต๐ฑ โ either one works (or)!
age = 17
marks = 82
print(age >= 16 and marks >= 75)
print(age >= 18 or marks >= 90)
print(not age >= 18)
Output:
True
False
True
4.4.4 Assignment and Augmented Assignment Operators ๐ฅ
The augmented assignment operators are shortcuts that do an operation and store the result in the same variable.
| Operator | Example | Same as | If x = 10, x becomes |
|---|---|---|---|
+= |
x += 5 |
x = x + 5 |
15 |
-= |
x -= 3 |
x = x - 3 |
7 |
*= |
x *= 2 |
x = x * 2 |
20 |
/= |
x /= 4 |
x = x / 4 |
2.5 |
//= |
x //= 3 |
x = x // 3 |
3 |
%= |
x %= 3 |
x = x % 3 |
1 |
**= |
x **= 2 |
x = x ** 2 |
100 |
score = 50
score += 10
score *= 2
score -= 20
print(score)
Output:
100
++ or --!To increase a variable by 1, write x += 1. Writing x++ gives a SyntaxError.
4.4.5 Membership Operators ๐
in and not in check whether a value is present in a sequence (string, list, tuple) or among a dictionary's keys.
print("a" in "Python")
print(20 in [10, 20, 30])
print("Mon" not in ("Mon", "Tue"))
print("name" in {"name": "Riya", "class": 11})
Output:
False
True
False
True
"Write the output: print(25 // 4, 25 % 4, 25 / 4, 2 ** 4)" โ 2 marks
Answer: 6 1 6.25 16
4.5 ๐งฎ Expressions and Operator Precedence
An expression is a combination of values, variables and operators that gives a single value โ like a + b * 2.
When an expression has many operators, Python follows a fixed order called precedence โ just like BODMAS in maths!
| Priority | Operator | Description |
|---|---|---|
| 1 (highest) | ( ) |
Brackets |
| 2 | ** |
Exponent |
| 3 | +x -x |
Unary plus and minus (sign) |
| 4 | * / // % |
Multiply, divide, floor divide, modulus |
| 5 | + - |
Add, subtract |
| 6 | < > <= >= == != in not in |
Comparison and membership |
| 7 | not |
Logical NOT |
| 8 | and |
Logical AND |
| 9 (lowest) | or |
Logical OR |
- Most operators work left to right:
20 / 4 * 2=5.0 * 2=10.0 **works right to left:2 ** 3 ** 2=2 ** 9=512(not 64!)
Solving step by step:
10 + 6 * 3 ** 2 // 4 - 1
= 10 + 6 * 9 // 4 - 1 โ ** first
= 10 + 54 // 4 - 1 โ * (left to right with //)
= 10 + 13 - 1 โ //
= 23 - 1 โ +
= 22 โ -
print(10 + 6 * 3 ** 2 // 4 - 1)
print((10 + 6) * 3)
print(2 ** 3 ** 2)
print(20 / 4 * 2)
print(5 > 3 and 2 > 4 or 7 > 1)
Output:
22
48
512
10.0
True
Parentheses โ Exponent โ Multiply/Divide โ Add/Subtract โ Relational โ Not โ And โ Or
"Evaluate: 15 - 3 * 2 + 8 // 3 % 2" โ 2 marks
Answer:
= 15 - 6 + 8 // 3 % 2
= 15 - 6 + 2 % 2
= 15 - 6 + 0
= 94.6 ๐ Type Conversion
Changing a value from one data type to another is called type conversion. It happens in two ways:
4.6.1 Implicit Conversion (Automatic) ๐ค
Python automatically converts a smaller type to a bigger type when needed, so no data is lost. This is also called type promotion.
a = 10 # int
b = 2.5 # float
c = a + b # int is converted to float automatically
print(c, type(c))
print(True + 5)
Output:
12.5 <class 'float'>
6
bool โโโบ int โโโบ float โโโบ complex
(smaller) (bigger)
4.6.2 Explicit Conversion (Type Casting) โ
We convert the type ourselves using functions like int(), float(), str(), bool().
| Function | Example | Result |
|---|---|---|
int() |
int(7.9) |
7 (decimal part is cut off, not rounded) |
int() |
int("45") |
45 |
float() |
float(5) |
5.0 |
float() |
float("3.5") |
3.5 |
str() |
str(100) |
'100' |
bool() |
bool(0) |
False |
bool() |
bool("Hi") |
True |
price = "250"
qty = 3
total = int(price) * qty
print("Total = " + str(total))
print(int(7.9), int(-7.9))
print(bool(0), bool(15), bool(""))
Output:
Total = 750
7 -7
False True False
0, 0.0, "" (empty string), [], (), {} and None are all treated as False. Everything else is True!
| Implicit Conversion | Explicit Conversion |
|---|---|
| Done automatically by Python | Done by the programmer |
| No function is written | Uses int(), float(), str() etc. |
| Smaller type โ bigger type (no data loss) | Any direction; data may be lost (e.g. int(7.9) โ 7) |
e.g. 10 + 2.5 โ 12.5 |
e.g. int("45") โ 45 |
"Differentiate between implicit and explicit type conversion with an example." โ 2 marks
Answer: Implicit conversion is done automatically by Python, converting a smaller type to a bigger one โ e.g. in 5 + 2.0, the int 5 becomes a float and the result is 7.0. Explicit conversion (type casting) is done by the programmer using functions โ e.g. int("25") converts the string to the integer 25.
4.7 ๐ Debugging โ Types of Errors
A mistake in a program is called a bug, and finding and fixing it is called debugging. Errors are of three types:
graph TD
E["๐ ERRORS"]
S["โ๏ธ Syntax Error\n(breaks Python's grammar)\nProgram does NOT start"]
R["๐ฅ Runtime Error\n(problem while running)\nProgram STOPS midway"]
L["๐ค Logical Error\n(wrong logic)\nProgram runs but\nanswer is WRONG"]
E --> S
E --> R
E --> L
style S fill:#F44336,color:#fff
style R fill:#FF9800,color:#fff
style L fill:#9C27B0,color:#fff
Syntax Error
The code breaks Python's grammar rules โ missing bracket or colon or quote, misspelt keyword
print("Hi"Runtime Error (Exception)
Grammar is correct, but something goes wrong while running โ Python stops with an error message
10 / 0Logical Error
Program runs without any message but gives the WRONG answer because the logic is wrong
avg = a + b / 2Common runtime errors:
| Error | When it happens | Example |
|---|---|---|
ZeroDivisionError |
Dividing by zero | 10 / 0 |
NameError |
Using a name that doesn't exist | print(totl) |
TypeError |
Operation on the wrong type | "5" + 5 |
ValueError |
Right type but wrong value | int("abc") |
IndexError |
Index out of range | [1, 2][5] |
A logical error example:
a = 80
b = 90
avg = a + b / 2 # wrong! / is done before +
print("Wrong average:", avg)
avg = (a + b) / 2 # correct
print("Right average:", avg)
Output:
Wrong average: 125.0
Right average: 85.0
Analogy: Writing a letter โ๏ธ:
- Syntax error = spelling and grammar mistakes โ the reader can't even read it.
- Runtime error = the letter is fine, but the address doesn't exist โ delivery fails midway.
- Logical error = the letter reaches, but you wrote the wrong date for the party โ everything "works", but the result is wrong!
Python gives no error message for them. Always check your output with a value you can calculate by hand.
"Differentiate between a syntax error and a logical error." โ 2 marks
Answer: A syntax error occurs when the rules (grammar) of Python are broken, e.g. a missing colon or bracket; the program does not run at all. A logical error occurs when the program runs without any error message but gives a wrong result because of wrong logic, e.g. writing a + b / 2 instead of (a + b) / 2 for an average.
โ ๏ธ Common Errors and Misconceptions
| Mistake | What's Wrong | Correct Understanding |
|---|---|---|
10 / 2 gives 5 |
/ always gives a float |
It gives 5.0; use // for 5 |
-7 // 2 gives -3 |
Floor division rounds down | It gives -4 |
2 ** 3 ** 2 = 64 |
** works right to left |
It is 2 ** 9 = 512 |
"int is mutable because x = 5 can become x = 6" |
The name points to a new value | int is immutable |
| "String is mutable" | s[0] = "K" gives TypeError |
Strings are immutable |
x == 5 to store a value |
== compares |
Use x = 5 to store |
x++ to add 1 |
Python has no ++ |
Write x += 1 |
"Total " + 50 |
Can't join str and int | Use "Total " + str(50) |
int(7.9) gives 8 |
int() cuts off the decimal | It gives 7 |
bool("False") gives False |
Any non-empty string is True | It gives True |
| "A program with no error message is correct" | Logical errors show no message | Test with values you can check by hand |
๐ Quick Revision โ Exam Ready!
- Numbers โ
int(25),float(3.14, 2.5E3),complex(3+4j),bool(True = 1, False = 0) - Sequences โ
str"โฆ",list[ ],tuple( ); index starts at 0 - Mapping โ
dict{ key: value }; None โ no value (NoneType) - Mutable โ list, dict; Immutable โ int, float, complex, bool, str, tuple
- Arithmetic โ
/float division,//floor (quotient),%remainder,**power - Relational โ
< > <= >= == !=give True/False - Logical โ
and(both),or(either),not(reverse) - Augmented โ
+= -= *= /= //= %= **=; no++in Python - Membership โ
in,not in - Precedence โ
()>**> unary->* / // %>+ -> comparisons >not>and>or - Same priority โ left to right, except
**(right to left) - Implicit conversion โ automatic, smaller to bigger type (int + float โ float)
- Explicit conversion โ
int(),float(),str(),bool();int(7.9)โ 7 - False values โ 0, 0.0, "", [], (), {}, None
- Errors โ Syntax (grammar, doesn't run), Runtime (stops midway), Logical (wrong answer, no message)
๐ฏ Sample Exam Questions
Q1: Very Short Answer [1 mark each]
a) What is the output of print(type(5 / 5))?
Answer: <class 'float'>
b) Name two mutable data types. Answer: List and Dictionary
c) What is the result of 19 % 4?
Answer: 3
d) Which operator is used for exponent in Python?
Answer: **
e) What is the output of print(bool(0))?
Answer: False
f) Which error occurs when you run print(10 / 0)?
Answer: ZeroDivisionError (a runtime error)
Q2: Output Based [2 marks]
a = 17
b = 4
print(a / b, a // b, a % b)
print(a ** 2 - b * 10)
Answer:
4.25 4 1
249
Q3: Output Based [2 marks]
x = 10
x += 5
x //= 2
x **= 2
print(x)
print(x > 40 and not x % 2 == 0)
Answer:
49
True
Steps: x = 15 โ 15 // 2 = 7 โ 7 ** 2 = 49. Then 49 > 40 is True and 49 % 2 == 0 is False, so not False is True โ True and True = True.
Q4: Evaluate [2 marks]
Evaluate: 4 + 18 / 3 ** 2 * 2 - 1
Answer:
= 4 + 18 / 9 * 2 - 1
= 4 + 2.0 * 2 - 1
= 4 + 4.0 - 1
= 7.0
Q5: Short Answer [2 marks]
Identify the type of error in each and correct it:
(a) print("Result" , 25
(b) area = 3.14 * r + r (to find the area of a circle)
Answer:
(a) Syntax error โ closing bracket is missing. Correct: print("Result", 25)
(b) Logical error โ the formula is wrong. Correct: area = 3.14 * r * r
Q6: Program [3 marks]
Write a program to input a number of days and print it as weeks and remaining days.
Answer:
days = int(input("Enter number of days: "))
weeks = days // 7
left = days % 7
print(weeks, "weeks and", left, "days")
Sample run (the user types 45):
Enter number of days: 45
6 weeks and 3 days
โ๏ธ Practice Problems
- Name the data type of each:
45,45.0,"45",[45],(45,),True,None,4+5j - Why is a list called mutable and a string immutable? Show with a small program.
- Write the output:
print(29 // 5, 29 % 5, 29 / 5, -29 // 5) - Evaluate:
3 + 4 * 2 ** 2 // 5 % 3 - Write the output:
print("5" * 3, 5 * 3, "5" + "3") - Evaluate:
not 5 > 3 or 4 < 2 and 6 == 6 - If
a = 12, findaafter each statement runs in order:a += 3,a %= 4,a *= 10 - What is the difference between implicit and explicit type conversion? Give one example of each.
- Write the output:
print(int(9.99), float(9), str(9) + "9", bool("")) - Write a program to input a three-digit number and print the sum of its digits (use
%and//). - Write a program to input the time in seconds and print it in hours, minutes and seconds.
- Classify each error as syntax, runtime or logical: (a)
if x > 5without a colon (b)int("12a")(c) usings = l + bfor the area of a rectangle