Current Affairs updated daily
KalviGavaniKalviGavani
Class 12 · Tamil Nadu State Board

Python Variables and Operators Exercise Solutions | KalviGavani

Complete Samacheer Kalvi Class 12 Computer Science Chapter 5 exercise solutions covering Python variables, data types (int, float, str, bool, list, tuple, dict, set), type conversion, arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, and operator precedence with code examples.

Updated 13 June 202629 min read

Chapter 5 — Python Variables and Operators: Exercise Solutions Guide

How to Use This Page

1. Attempt every exercise question on your own first — use your Samacheer Kalvi textbook and class notes. 2. Compare your answers with the solutions below only after you have written your own. 3. Read the explanations for MCQs and True/False items — understanding why an answer is correct is more important than the answer itself. 4. Practise the short and detailed answers by writing them in your own words; do not memorise verbatim. 5. Use the Exam Checklist at the end for a quick pre-exam revision round.


Key Concepts (Quick Recap)

  • A variable is a named location in memory that stores a value. Python is dynamically typed — no type declaration needed.
  • Data types: int (integer), float (decimal), complex (complex number), bool (True/False), str (string), list (ordered, mutable), tuple (ordered, immutable), dict (key-value pairs), set (unordered, unique elements).
  • Type conversion converts one data type to another: int(), float(), str(), bool(), list(), tuple(), set(), dict().
  • Arithmetic operators: + (addition), - (subtraction), (multiplication), / (true division), // (floor division), % (modulus), * (exponentiation).
  • Relational operators: ==, !=, >, <, >=, <= — return True or False.
  • Logical operators: and, or, not — combine boolean expressions.
  • Bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
  • Assignment operators: =, +=, -=, =, /=, //=, %=, *=, &=, |=, ^=, <<=, >>=.
  • Operator precedence (highest to lowest): () > * > unary +- > / // % > + - > relational > not > and > or.
  • Implicit conversion (automatic): Python converts smaller types to larger types (e.g., int + float → float).
  • Explicit conversion (manual): Using type conversion functions like int(), float(), str().
  • type() returns the data type of a value; isinstance() checks if a value is of a specific type.

I. Choose the Best Answer (MCQs)

1. What is the output of 7 // 2 in Python? (a) 3.5 (b) 3 (c) 4 (d) 2

Answer(b) 3 The // operator performs floor division, which returns the integer part of the quotient. 7 divided by 2 is 3.5, and the floor of 3.5 is 3.

2. Which of the following is a mutable data type in Python? (a) tuple (b) str (c) list (d) int

Answer(c) list A list is mutable — its elements can be changed after creation. Tuples and strings are immutable (cannot be changed). Int is also immutable (you cannot change the value of an integer object).

3. What is the output of 2 3 2 in Python? (a) 64 (b) 512 (c) 36 (d) 81

Answer(b) 512 Exponentiation () is right-associative in Python. So 2 3 2 is evaluated as 2 (3 2) = 2 9 = 512. If it were left-associative, it would be (2 3) 2 = 8 ** 2 = 64.

4. What is the result of int(3.9) in Python? (a) 3.9 (b) 4 (c) 3 (d) Error

Answer(c) 3 int() truncates the decimal part (rounds toward zero). int(3.9) returns 3, not 4. It does not round to the nearest integer.

5. Which operator is used for modulus (remainder) in Python? (a) / (b) // (c) % (d) **

Answer(c) % The % operator returns the remainder of division. Example: 7 % 3 returns 1 (because 7 = 2 × 3 + 1). / is true division, // is floor division, ** is exponentiation.

6. What is the output of bool(0) in Python? (a) True (b) False (c) 0 (d) Error

Answer(b) False In Python, the following values evaluate to False: 0, 0.0, empty string "", empty list [], empty tuple (), empty dict {}, None, and False. All other values evaluate to True.

7. Which of the following is the correct way to find the type of a variable? (a) type(x) (b) typeof(x) (c) datatype(x) (d) x.type()

Answer(a) type(x) Python's built-in type() function returns the data type of an object. Example: type(42) returns <class 'int'>.

8. What is the output of 10 % 3? (a) 3 (b) 3.33 (c) 1 (d) 0

Answer(c) 1 10 % 3 returns the remainder when 10 is divided by 3. 10 = 3 × 3 + 1, so the remainder is 1.

9. Which logical operator returns True only if both operands are True? (a) or (b) not (c) and (d) xor

Answer(c) and The and operator returns True only when both operands are True. or returns True if at least one operand is True. not reverses the boolean value. Python does not have an xor keyword for logical operations.

*10. What is the output of 5 + 2 3?** (a) 21 (b) 11 (c) 10 (d) 17

Answer(b) 11 Following operator precedence, multiplication () is evaluated before addition (+). So 5 + 2 3 = 5 + 6 = 11, not (5 + 2) * 3 = 21.

II. Fill in the Blanks

1. The type() function returns the data type of a variable in Python.

2. The // operator performs floor division in Python.

3. The % operator returns the remainder of a division operation.

4. The ****** operator performs exponentiation in Python.

5. In Python, dynamic typing means that the type of a variable is determined at runtime based on the value assigned.

6. The bool() function converts a value to a boolean (True or False).

7. The str() function converts a number to a string.

8. The and logical operator returns True only if both operands are True.

9. In operator precedence, parentheses () have the highest priority.

10. The bitwise operator ~ performs a bitwise NOT (complement) operation.


III. True or False

1. Python is a statically typed language. False. Python is a dynamically typed language. Variables do not need to be declared with a type; the type is determined at runtime based on the assigned value. x = 5 makes x an int; x = "hello" makes x a str.

2. A string is a mutable data type in Python. False. Strings are immutable in Python. Once created, the characters of a string cannot be changed. Operations like s.upper() create a new string; they do not modify the original.

3. The // operator always returns an integer. True. Floor division (//) always returns an integer result (the floor of the quotient). Even 7 // 2.0 returns 3.0 (a float, but the value is the integer floor). Note: when operands are floats, the result is a float, but the value is still the integer part.

4. 5 / 2 returns 2 in Python 3. False. In Python 3, / performs true division and returns a float: 5 / 2 returns 2.5. In Python 2, / performed integer division when both operands were integers, but Python 3 always returns a float.

5. A list can contain elements of different data types. True. Python lists can hold elements of any type, including mixed types. Example: [1, "hello", 3.14, True] is a valid list.

6. The not operator reverses the boolean value of its operand. True. not True returns False, and not False returns True. It is a unary operator that negates the boolean value.

7. True + True returns 2 in Python. True. In Python, True has an integer value of 1 and False has a value of 0. So True + True = 1 + 1 = 2, and True * 5 = 5.

8. Tuple elements can be modified after creation. False. Tuples are immutable — their elements cannot be changed, added, or removed after creation. If you need a modifiable sequence, use a list instead.

9. The is operator checks if two variables have the same value. False. The is operator checks if two variables refer to the same object in memory (identity), not just the same value. For value comparison, use ==. Example: [1, 2] == [1, 2] is True, but [1, 2] is [1, 2] is False.

10. Operator precedence determines the order in which operators are evaluated in an expression. True. Operator precedence defines the order: parentheses first, then exponentiation, then multiplication/division, then addition/subtraction, then comparison, then logical operators. Without precedence, expressions would be ambiguous.


IV. Match the Following

Set A

AB
1. inte. Integer data type (e.g., 42)
2. floatc. Decimal number data type (e.g., 3.14)
3. stra. String data type (e.g., "hello")
4. boold. Boolean data type (True or False)
5. complexb. Complex number data type (e.g., 3+4j)

Set B

AB
1. //d. Floor division
2. %e. Modulus (remainder)
3. **a. Exponentiation
4. &c. Bitwise AND
5. <<b. Left shift

V. Short Answer Questions

1. What are variables in Python? Explain with examples. How are they different from variables in C/Java?
Answer

A variable is a named location in memory that stores a value. In Python, variables are created by assignment — no type declaration is needed.

name = "Kavi"    # str variable
age = 17         # int variable
height = 5.8     # float variable
is_student = True # bool variable

Key features of Python variables:

  • Dynamic typing: The type is determined by the value assigned. A variable can change type.
  x = 10       # x is int
  x = "hello"  # now x is str (type changed)
  • No declaration needed: Just assign a value to create a variable.
  • Case-sensitive: age and Age are different variables.

Differences from C/Java variables:

FeaturePythonC/Java
Type declarationNot requiredRequired (e.g., int age;)
TypingDynamicStatic
Type changeAllowed (x = 5; x = "hi")Not allowed
Multiple assignmenta, b = 1, 2Not directly supported
Memory managementAutomatic (garbage collection)Manual (C) or automatic (Java)

2. Explain the data types in Python with examples.
Answer

Python has several built-in data types:

Numeric types:

x = 10          # int - integer (whole number)
y = 3.14        # float - decimal number
z = 3 + 4j      # complex - complex number (real + imaginary)

Boolean type:

flag = True     # bool - either True or False

Sequence types:

# str - string (immutable sequence of characters)
name = "KalviGavani"

# list - ordered, mutable sequence
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# tuple - ordered, immutable sequence
coordinates = (10, 20)

Mapping type:

# dict - key-value pairs (unordered, mutable)
student = {"name": "Kavi", "age": 17, "grade": "A"}

Set types:

# set - unordered collection of unique elements
unique_numbers = {1, 2, 3, 4, 5}

Summary table:

Data TypeKeywordMutableOrderedExample
IntegerintNoN/A42
FloatfloatNoN/A3.14
ComplexcomplexNoN/A3+4j
BooleanboolNoN/ATrue
StringstrNoYes"hello"
ListlistYesYes[1, 2, 3]
TupletupleNoYes(1, 2, 3)
DictionarydictYesYes (Python 3.7+){"a": 1}
SetsetYesNo{1, 2, 3}

3. Explain type conversion (type casting) in Python with examples.
Answer

Type conversion is the process of converting a value from one data type to another.

(i) Implicit conversion (automatic): Python automatically converts smaller types to larger types to avoid data loss.

a = 10        # int
b = 3.14      # float
c = a + b     # int + float → float
print(c)      # 13.14
print(type(c))  # <class 'float'>

(ii) Explicit conversion (manual): The programmer explicitly converts using type conversion functions.

# int() - converts to integer (truncates decimal)
x = int(3.9)      # 3
y = int("42")     # 42
z = int(True)     # 1

# float() - converts to float
a = float(5)       # 5.0
b = float("3.14")  # 3.14

# str() - converts to string
s1 = str(42)      # "42"
s2 = str(3.14)    # "3.14"
s3 = str(True)    # "True"

# bool() - converts to boolean
print(bool(0))     # False
print(bool(1))     # True
print(bool(""))    # False
print(bool("hi")) # True
print(bool([]))    # False
print(bool([1]))   # True

# list() - converts to list
print(list("abc"))    # ['a', 'b', 'c']
print(list((1, 2)))   # [1, 2]

# tuple() - converts to tuple
print(tuple([1, 2]))  # (1, 2)

# set() - converts to set (removes duplicates)
print(set([1, 2, 2, 3]))  # {1, 2, 3}

Important notes:

  • int("hello") raises ValueError — only numeric strings can be converted.
  • int(3.9) returns 3 (truncates, does not round).
  • Values that convert to False: 0, 0.0, "", [], (), {}, None, False.

4. Explain arithmetic operators in Python with examples.
Answer

Arithmetic operators perform mathematical calculations.

OperatorNameExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/True division7 / 23.5
//Floor division7 // 23
%Modulus7 % 21
**Exponentiation2 ** 38

Detailed examples:

# Addition
print(10 + 5)         # 15
print(3.5 + 2.1)      # 5.6
print("Hello" + " World")  # "Hello World" (string concatenation)

# Subtraction
print(10 - 5)         # 5
print(3.5 - 1.2)      # 2.3

# Multiplication
print(10 * 5)         # 50
print(3.5 * 2)        # 7.0
print("Hi" * 3)       # "HiHiHi" (string repetition)

# True division (/) — always returns float
print(7 / 2)          # 3.5
print(10 / 2)         # 5.0 (always float)

# Floor division (//) — returns integer part
print(7 // 2)         # 3
print(-7 // 2)        # -4 (rounds toward negative infinity)
print(7.0 // 2)       # 3.0 (float result when operand is float)

# Modulus (%) — remainder
print(7 % 3)          # 1
print(10 % 5)         # 0
print(-7 % 3)         # 2 (Python modulus follows divisor sign)

# Exponentiation (**)
print(2 ** 3)         # 8
print(4 ** 0.5)       # 2.0 (square root)
print(2 ** -1)         # 0.5 (1/2)

Key differences to remember:

  • / always returns a float in Python 3.
  • // returns an integer when both operands are integers; a float when either operand is a float.
  • // rounds toward negative infinity: -7 // 2 = -4 (not -3).

5. Explain relational and logical operators with examples.
Answer

Relational (comparison) operators compare two values and return True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal5 >= 5True
<=Less than or equal5 <= 3False
a, b = 10, 5
print(a == b)   # False
print(a != b)   # True
print(a > b)    # True
print(a < b)    # False
print(a >= 10)  # True
print(a <= b)   # False

# String comparison (lexicographic/alphabetical)
print("apple" < "banana")   # True
print("abc" == "abc")       # True

Logical operators combine boolean expressions.

OperatorMeaningExampleResult
andTrue if both are TrueTrue and FalseFalse
orTrue if at least one is TrueTrue or FalseTrue
notReverses the valuenot TrueFalse
# and — both must be True
print(True and True)     # True
print(True and False)    # False
print(5 > 3 and 10 > 7)   # True (both conditions True)
print(5 > 3 and 10 < 7)   # False (second condition False)

# or — at least one must be True
print(True or False)     # True
print(False or False)    # False
print(5 > 3 or 10 < 7)    # True (first condition True)

# not — reverses boolean value
print(not True)          # False
print(not False)         # True
print(not (5 > 3))       # False

# Combining relational and logical
age = 18
has_id = True
print(age >= 18 and has_id)   # True (both conditions True)
print(age >= 21 or has_id)     # True (second condition True)

Truth tables:

ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue

6. Explain bitwise operators with examples.
Answer

Bitwise operators work on integers at the binary (bit) level.

OperatorNameDescriptionExampleResult
&AND1 if both bits are 15 & 31
``OR1 if at least one bit is 1`53`7
^XOR1 if bits are different5 ^ 36
~NOTInverts all bits~5-6
<<Left shiftShifts bits left5 << 110
>>Right shiftShifts bits right5 >> 12
# AND (&) — 1 only if both bits are 1
#   5 = 0101
#   3 = 0011
#   -------
#   1 = 0001
print(5 & 3)   # 1

# OR (|) — 1 if at least one bit is 1
#   5 = 0101
#   3 = 0011
#   -------
#   7 = 0111
print(5 | 3)   # 7

# XOR (^) — 1 if bits are different
#   5 = 0101
#   3 = 0011
#   -------
#   6 = 0110
print(5 ^ 3)   # 6

# NOT (~) — inverts all bits (two's complement)
print(~5)      # -6

# Left shift (<<) — shifts bits left, fills with 0s
#   5 = 0101
#   5 << 1 = 1010 (multiply by 2)
print(5 << 1)  # 10

# Right shift (>>) — shifts bits right, fills with 0s
#   5 = 0101
#   5 >> 1 = 0010 (divide by 2, floor)
print(5 >> 1)  # 2

Quick formulas:

  • Left shift by n: x << n = x × 2ⁿ
  • Right shift by n: x >> n = x // 2ⁿ

VI. Detailed Answer Questions

1. Explain all arithmetic operators in Python with examples. Distinguish between / and //, and show how % and ** work with both positive and negative numbers.
Answer

Python provides seven arithmetic operators:

OperatorNameExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/True divisiona / b
//Floor divisiona // b
%Modulusa % b
**Exponentiationa ** b

True division (/) vs Floor division (//):

# True division (/) always returns a float
print(10 / 3)    # 3.3333333333333335
print(10 / 2)    # 5.0 (always float, even when divisible)
print(7 / 2)     # 3.5

# Floor division (//) returns the integer part (floor of quotient)
print(10 // 3)   # 3
print(10 // 2)   # 5
print(7 // 2)    # 3

# With negative numbers, // rounds toward negative infinity
print(-7 // 2)   # -4 (not -3, because floor(-3.5) = -4)
print(7 // -2)   # -4
print(-7 // -2)  # 3

Modulus (%) with positive and negative numbers:

# Positive numbers
print(10 % 3)    # 1 (10 = 3*3 + 1)
print(7 % 2)    # 1 (7 = 2*3 + 1)

# Negative numbers — result has the sign of the divisor
print(-10 % 3)  # 2 (-10 = 3*(-4) + 2)
print(10 % -3)  # -2 (10 = (-3)*(-4) + (-2))
print(-10 % -3) # -1 (-10 = (-3)*3 + (-1))

Exponentiation () with different values:**

print(2 ** 3)     # 8 (2 to the power 3)
print(2 ** 0.5)   # 1.4142135623730951 (square root of 2)
print(2 ** -1)    # 0.5 (1/2)
print(3 ** 4)     # 81 (3 to the power 4)
print((-2) ** 3)  # -8 (negative base, odd exponent)
print((-2) ** 2)  # 4 (negative base, even exponent)

Mixed-type operations:

# int + float → float
print(5 + 2.5)   # 7.5

# int * float → float
print(3 * 2.0)   # 6.0

# int // float → float (but floor value)
print(7 // 2.0)  # 3.0

2. Explain all relational (comparison) and logical operators with truth tables and Python examples.
Answer

Relational (comparison) operators:

These compare two values and return True or False.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal5 >= 5True
<=Less than or equal5 <= 3False
a, b = 10, 5
print(a == b)   # False
print(a != b)   # True
print(a > b)    # True
print(a < b)    # False
print(a >= 10)  # True
print(a <= b)   # False

# Chained comparisons
print(1 < 5 < 10)    # True (5 is between 1 and 10)
print(1 < 5 > 3)     # True (5 > 1 and 5 > 3)

# String comparison (lexicographic)
print("apple" < "banana")  # True (a comes before b)
print("abc" == "abc")      # True
print("A" < "a")            # True (ASCII: A=65, a=97)

Logical operators:

OperatorMeaningDescription
andLogical ANDTrue only if both operands are True
orLogical ORTrue if at least one operand is True
notLogical NOTReverses the boolean value

Truth table for and:

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Truth table for or:

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Truth table for not:

Anot A
TrueFalse
FalseTrue
# and operator
print(True and True)      # True
print(True and False)     # False
print(5 > 3 and 10 > 7)   # True
print(5 > 3 and 10 < 7)   # False

# or operator
print(True or False)      # True
print(False or False)     # False
print(5 > 3 or 10 < 7)    # True

# not operator
print(not True)           # False
print(not False)          # True
print(not (5 > 3))        # False

# Combining operators
age = 18
has_id = True
print(age >= 18 and has_id)      # True
print(age < 18 or not has_id)    # False

# Short-circuit evaluation
# and: stops at first False
# or: stops at first True
x = 0
print(x != 0 and 10 // x > 0)   # False (second part not evaluated — no ZeroDivisionError)

3. Explain operator precedence in Python with examples. What is the order of evaluation?
Answer

Operator precedence determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first.

Precedence table (highest to lowest):

PriorityOperatorDescription
1 (highest)()Parentheses
2**Exponentiation
3+x, -xUnary plus, unary minus
4*, /, //, %Multiplication, division, floor division, modulus
5+, -Addition, subtraction
6==, !=, >, <, >=, <=Comparison operators
7notLogical NOT
8andLogical AND
9 (lowest)orLogical OR

Examples showing precedence:

# Exponentiation before multiplication
print(2 + 3 * 4)      # 14 (3*4=12, then 2+12=14)
print(2 ** 3 ** 2)     # 512 (** is right-associative: 2**(3**2)=2**9=512)

# Parentheses override precedence
print((2 + 3) * 4)     # 20 (2+3=5, then 5*4=20)
print(2 ** (3 ** 2))   # 512 (same as without parentheses)
print((2 ** 3) ** 2)   # 64 (8**2=64)

# Multiplication/division before addition/subtraction
print(10 + 5 * 2)      # 20 (5*2=10, then 10+10=20)
print(10 - 6 / 2)      # 7.0 (6/2=3.0, then 10-3.0=7.0)

# Modulus and floor division
print(10 + 7 % 3)      # 11 (7%3=1, then 10+1=11)
print(10 // 3 * 2)     # 6 (10//3=3, then 3*2=6)

# Comparison operators
print(2 + 3 > 1 + 3)   # True (5 > 4)

# Logical operators
print(not True or True)    # True (not True=False, False or True=True)
print(not (True or True))  # False (True or True=True, not True=False)

# Combining all
print(2 + 3 * 4 > 10 and not False)  # True
# Step 1: 3 * 4 = 12
# Step 2: 2 + 12 = 14
# Step 3: 14 > 10 = True
# Step 4: not False = True
# Step 5: True and True = True

Associativity:

  • Most operators are left-associative: 10 - 3 - 2 = (10 - 3) - 2 = 5
  • Exponentiation is right-associative: 2 3 2 = 2 (3 2) = 512

Tip: When in doubt, use parentheses to make the order explicit. It improves readability and prevents bugs.


4. Explain all data types in Python with examples. Differentiate between mutable and immutable types.
Answer

Python data types can be categorised as follows:

(i) Numeric types:

# int — integer (whole numbers, unlimited size)
x = 42
y = -100
big = 999999999999999999999999  # Python handles arbitrarily large integers

# float — decimal (floating-point) numbers
pi = 3.14159
temp = -10.5
sci = 2.5e10    # 25000000000.0 (scientific notation)

# complex — complex numbers (real + imaginary)
z = 3 + 4j
print(z.real)   # 3.0
print(z.imag)   # 4.0

(ii) Boolean type:

flag = True
active = False
print(type(flag))   # <class 'bool'>
print(True + True)  # 2 (True = 1, False = 0)

(iii) Sequence types:

# str — string (immutable sequence of characters)
name = "KalviGavani"
print(name[0])      # 'K'
print(name[0:4])    # 'Kalv'
# name[0] = "k"    # TypeError: strings are immutable

# list — ordered, mutable sequence
fruits = ["apple", "banana", "cherry"]
fruits.append("mango")     # Can modify
fruits[0] = "avocado"      # Can change elements
print(fruits)              # ['avocado', 'banana', 'cherry', 'mango']

# tuple — ordered, immutable sequence
point = (10, 20)
print(point[0])            # 10
# point[0] = 5            # TypeError: tuples are immutable
single = (5,)              # Single-element tuple (note the comma)

(iv) Mapping type:

# dict — key-value pairs (mutable)
student = {
    "name": "Kavi",
    "age": 17,
    "grade": "A"
}
print(student["name"])     # Kavi
student["age"] = 18        # Can modify
student["school"] = "HSC"  # Can add new key

(v) Set type:

# set — unordered collection of unique elements (mutable)
colors = {"red", "green", "blue"}
colors.add("yellow")       # Can modify
print(colors)              # Order not guaranteed
numbers = {1, 2, 2, 3, 3} # Duplicates removed
print(numbers)             # {1, 2, 3}

Mutable vs Immutable:

FeatureMutableImmutable
DefinitionCan be changed after creationCannot be changed after creation
Typeslist, dict, setint, float, complex, bool, str, tuple
Examplel = [1, 2]; l[0] = 5 (works)s = "hi"; s[0] = "H" (error)
MemorySame object is modifiedNew object is created on change
# Mutable — same object, content changes
a = [1, 2, 3]
b = a
a[0] = 99
print(b)    # [99, 2, 3] — b also changed (same object)

# Immutable — new object created on change
x = "hello"
y = x
x = "world"      # New string object created
print(y)         # "hello" — y still points to original

5. Explain type conversion in Python. Differentiate between implicit and explicit conversion with examples. What errors can occur during type conversion?
Answer

Type conversion is the process of converting a value from one data type to another.

(i) Implicit conversion (automatic / coercion): Python automatically converts smaller types to larger types to prevent data loss. This happens without programmer intervention.

# int + float → float
a = 10       # int
b = 3.5      # float
c = a + b    # int + float → float
print(c)           # 13.5
print(type(c))     # <class 'float'>

# int + bool → int (bool is subclass of int)
x = 10 + True      # 10 + 1 = 11
print(x)           # 11

# float + complex → complex
y = 2.5 + 3j
print(y)           # (2.5+3j)
print(type(y))     # <class 'complex'>

(ii) Explicit conversion (type casting): The programmer manually converts using built-in functions.

# int() — converts to integer
print(int(3.9))      # 3 (truncates, does not round)
print(int("42"))     # 42 (string to int)
print(int(True))     # 1
print(int(False))    # 0
print(int(-3.7))     # -3 (truncates toward zero)

# float() — converts to float
print(float(5))       # 5.0
print(float("3.14"))  # 3.14
print(float("5"))     # 5.0
print(float(True))    # 1.0

# str() — converts to string
print(str(42))       # "42"
print(str(3.14))     # "3.14"
print(str(True))     # "True"

# bool() — converts to boolean
print(bool(0))       # False
print(bool(1))       # True
print(bool(-5))      # True (any non-zero number is True)
print(bool(""))      # False
print(bool("hello")) # True
print(bool([]))      # False
print(bool([1, 2]))  # True

# list() — converts to list
print(list("abc"))      # ['a', 'b', 'c']
print(list((1, 2, 3)))  # [1, 2, 3]
print(list(range(5)))    # [0, 1, 2, 3, 4]

# tuple() — converts to tuple
print(tuple([1, 2, 3]))  # (1, 2, 3)

# set() — converts to set (removes duplicates)
print(set([1, 2, 2, 3]))  # {1, 2, 3}
print(set("hello"))        # {'h', 'e', 'l', 'o'} (order not guaranteed)

Common errors during type conversion:

# ValueError — converting non-numeric string to int/float
# int("hello")      # ValueError: invalid literal for int()
# float("abc")      # ValueError: could not convert string to float

# TypeError — invalid conversion
# int([1, 2])       # TypeError: int() argument must be a string or number

# Implicit conversion does NOT work between incompatible types
# "Age: " + 18      # TypeError: can only concatenate str to str
# Fix: "Age: " + str(18)   # "Age: 18"

Summary of falsy values (convert to False):

Valuebool() result
0, 0.0False
"" (empty string)False
[] (empty list)False
() (empty tuple)False
{} (empty dict)False
set() (empty set)False
NoneFalse
FalseFalse

All other values convert to True.


Common Mistakes

1. Confusing / (true division) with // (floor division): 7 / 2 returns 3.5 (float); 7 // 2 returns 3 (integer floor). For negative numbers: -7 // 2 returns -4, not -3.

2. Forgetting that / always returns float in Python 3: 10 / 2 returns 5.0, not 5. Use // if you need an integer result.

3. Confusing = (assignment) with == (comparison): x = 5 assigns 5 to x; x == 5 checks if x equals 5 and returns True/False.

4. Not understanding Python's modulus with negative numbers: -10 % 3 returns 2 (not -1), because Python's modulus follows the sign of the divisor.

5. Assuming int() rounds to nearest integer: int(3.9) returns 3, not 4. int() truncates toward zero. Use round(3.9) for rounding.

6. Forgetting that strings are immutable: "hello"[0] = "H" raises a TypeError. Create a new string instead: "H" + "ello".

7. Operator precedence errors: 2 + 3 4 = 14, not 20. Multiplication has higher precedence than addition. Use parentheses for clarity: (2 + 3) 4 = 20.


Exam Checklist

  • [ ] Can define variables and explain dynamic typing in Python
  • [ ] Can list and explain all data types (int, float, complex, bool, str, list, tuple, dict, set)
  • [ ] Can differentiate between mutable and immutable types
  • [ ] Can use type conversion functions (int(), float(), str(), bool(), list(), tuple(), set())
  • [ ] Can explain implicit vs explicit type conversion
  • [ ] Can use all arithmetic operators (+, -, , /, //, %, *) with correct results
  • [ ] Can use relational operators (==, !=, >, <, >=, <=) and predict results
  • [ ] Can use logical operators (and, or, not) with truth tables
  • [ ] Can use bitwise operators (&, |, ^, ~, <<, >>) with binary representations
  • [ ] Can determine the order of evaluation using operator precedence rules

Frequently Asked Questions

Python has built-in data types: int (integer), float (decimal), complex (complex number), bool (boolean), str (string), list (ordered mutable sequence), tuple (ordered immutable sequence), dict (key-value pairs), and set (unordered unique collection).
← Browse all Class 12 Exercise Solutions

Other question types — same chapter