Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 03

Python Variables & Data Types

5 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

Variables store data.

Data types decide what kind of data it is and what you can do with it.

This chapter covers variables, built-in data types, numbers, type casting and the Boolean type.

Every program stores and transforms data.

Wrong types cause the most common runtime errors.

Billing totals, user input conversion, flags, sensor readings, scores and configuration values.

1

Python Variables

A variable is a name that refers to an object stored in memory. In Python a variable is created the moment you assign a value to it with the = operator. No type declaration is needed.

In short: A variable is a label stuck on a value. You can use the label to read or change the value later.

Think about it

Variables let programs remember and reuse data, so the same code works for any input. A shopping app stores cart_total in a variable and updates it as items are added.

Assignment binds a name to an object: x = 5 means "x refers to the int object 5".

Multiple assignment: a, b, c = 1, 2, 3; chained: a = b = 0; swap: a, b = b, a.

Extended unpacking: first, *rest = [1, 2, 3, 4].

Variables are dynamically typed: the same name can later refer to a different type.

id(x) gives the identity (memory address in CPython) and del x removes the name.

Naming rules: letters, digits, underscore; no leading digit; not a keyword; case-sensitive.

Style: snake_case; constants written in UPPER_CASE by convention (Python has no true constants).

Scope: variables created inside a function are local; those outside are global; use the global keyword to modify a global inside a function.

Caution: x = y = [] makes both names refer to the SAME list.

Key points

  • Assignment: Binding a name to a value with =.
  • Reference: The link between a name and an object.
  • Unpacking: Assigning items of a sequence to several names at once.
  • Scope: Region of code where a name is visible.
  • Constant (convention): UPPER_CASE name that should not be changed.
  • No declaration needed; assignment creates the variable.
  • A variable can change type when you assign a new value.
  • Use meaningful snake_case names.
  • Aliasing: b = a makes b point to the same object, not a copy.

Example

Code
creating and using variables:
name = "Asha"
age = 21
height = 5.4
print(name, age, height)

a, b, c = 1, 2, 3
x = y = 0
a, b = b, a            # swap
print(a, b)            # 2 1

first, *rest = [10, 20, 30, 40]
print(first, rest)     # 10 [20, 30, 40]

MAX_USERS = 100        # constant by convention

# aliasing trap
p = [1, 2]
q = p                  # same list
q.append(3)
print(p)               # [1, 2, 3]
r = p.copy()           # real copy
r.append(4)
print(p, r)            # [1, 2, 3] [1, 2, 3, 4]

del age
# print(age)           # NameError
2

Python Data Types

A data type defines the kind of value an object holds and the operations allowed on it. Python has built-in types: int, float, complex, str, bool, list, tuple, range, dict, set, frozenset, bytes and NoneType.

In short: A data type tells Python what the value is: number, text, true/false, collection and so on.

Variable → value in memory

Think about it

The type decides which operations work: you can add numbers, join strings and index lists, but not the reverse. A form value arrives as str; you must convert it to int before doing arithmetic.

Numeric: int, float, complex.

Text: str.

Boolean: bool.

Sequence: list (mutable), tuple (immutable), range (immutable).

Mapping: dict (key-value pairs).

Set types: set (mutable, unique items), frozenset (immutable).

Binary: bytes, bytearray.

None type: NoneType with the only value None.

Mutable types can be changed after creation (list, dict, set, bytearray).

Immutable types cannot (int, float, str, tuple, frozenset, bytes, bool).

Check types with type(x) or isinstance(x, int); isinstance also accepts subclasses and tuples of types.

Python is dynamically typed but strongly typed: "5" + 5 raises TypeError instead of silently converting.

Ordered: list, tuple, str, dict (insertion order since 3.7).

Unordered: set.

Key points

  • Mutable: Can be changed in place after creation.
  • Immutable: Cannot be changed after creation.
  • type(): Returns the exact type of an object.
  • isinstance(): Checks if an object is of a given type or subclass.
  • Strong typing: Python refuses unsafe mixes like "5" + 5.
  • list, dict, set are mutable; str, tuple, int, float are immutable.
  • Dictionary keys must be immutable (hashable).
  • Python is dynamically but strongly typed.
  • bool is a subclass of int.

Example

Code
types, mutability and type checks:
values = [42, 3.14, 2 + 5j, "text", True, [1, 2], (1, 2),
          range(3), {"a": 1}, {1, 2}, frozenset({1}), b"hi", None]
for v in values:
    print(type(v).__name__, end=" | ")
print()
# int | float | complex | str | bool | list | tuple | range | dict | set | frozenset | bytes | NoneType |

print(isinstance(5, int), isinstance(True, int))   # True True
print(isinstance(5, (int, float)))                 # True

s = "hello"
# s[0] = "H"      # TypeError: str is immutable
t = (1, 2, 3)
# t[0] = 9        # TypeError
nums = [1, 2, 3]
nums[0] = 9       # list is mutable
print(nums)       # [9, 2, 3]

# "5" + 5         # TypeError (strong typing)
print("5" + str(5), int("5") + 5)   # 55 10
3

Python Numbers

Python has three numeric types: int (whole numbers of unlimited size), float (double-precision decimal numbers) and complex (numbers with real and imaginary parts written as a+bj).

In short: int is for whole numbers, float is for decimals, complex is for numbers like 3+4j.

Think about it

Float precision and integer division are classic exam traps and real-world money bugs. Banking software uses Decimal instead of float so that 0.1 + 0.2 equals exactly 0.3.

int has no fixed limit, so 2 ** 200 works.

float follows IEEE 754 double precision, so some decimals are stored approximately: 0.1 + 0.2 gives 0.30000000000000004.

Compare floats with math.

isclose(); use the decimal module for exact money calculations and fractions.

Fraction for exact ratios.

Useful functions: abs, round, pow, divmod, min, max, sum and the math module (sqrt, floor, ceil, pi).

round() uses banker's rounding: round(2.5) is 2 and round(3.5) is 4.

divmod(a, b) returns (a // b, a % b).

Complex numbers have .

real, .

imag, abs() for magnitude and .

conjugate().

Number systems: bin(10), oct(10), hex(255) and int("1010", 2).

Underscores in literals (1_000) improve readability.

Division by zero raises ZeroDivisionError for int and float.

Key points

  • int: Whole number with unlimited size.
  • float: Decimal number stored in 64-bit IEEE 754 format.
  • complex: Number with real and imaginary part, like 2+3j.
  • Decimal: Exact decimal type from the decimal module.
  • Banker's rounding: Ties round to the nearest even number.
  • Python ints never overflow.
  • 0.1 + 0.2 != 0.3 because of binary floating point.
  • / always returns float; // keeps int for int operands.
  • round(2.5) is 2, round(3.5) is 4.

Example

Code
int, float, complex and precision:
import math
from decimal import Decimal

print(2 ** 100)                 # 1267650600228229401496703205376
print(10 / 4, 10 // 4, 10 % 4)  # 2.5 2 2
print(divmod(17, 5))            # (3, 2)

print(0.1 + 0.2)                # 0.30000000000000004
print(math.isclose(0.1 + 0.2, 0.3))          # True
print(Decimal("0.1") + Decimal("0.2"))       # 0.3

print(round(2.5), round(3.5), round(2.675, 2))   # 2 4 2.67
print(math.floor(-2.5), math.ceil(-2.5))         # -3 -2

z = (2 + 3j) * (1 - 1j)
print(z, z.real, z.imag)        # (5+1j) 5.0 1.0
print(abs(3 + 4j))              # 5.0

print(bin(10), oct(10), hex(255))   # 0b1010 0o12 0xff
print(int("1010", 2), int("ff", 16))  # 10 255
4

Type Casting in Python

Type casting (type conversion) means converting a value from one data type to another. Python does implicit conversion automatically in safe cases and explicit conversion with functions such as int(), float(), str(), bool(), list(), tuple() and set().

In short: Type casting changes a value from one type to another, like turning the text "25" into the number 25.

Think about it

User input, files and APIs deliver text. Casting makes calculations possible. A form gives age as "21"; the program does int(age) to compare with 18.

Implicit casting: Python widens types by itself, int → float → complex: 3 + 2.0 gives 5.0; True + 1 gives 2.

Explicit casting: int(3.99) gives 3 (truncates toward zero, does not round); int("42") gives 42; int("3.5") raises ValueError, so use int(float("3.5")); float("2.5") gives 2.5; str(10) gives "10"; bool(x) gives False for 0, 0.0, "", [], (), {}, set(), None and True for all else; list("abc") gives ["a", "b", "c"]; tuple([1, 2]); set([1, 1, 2]) gives {1, 2}; dict([("a", 1)]); chr(65) is "A" and ord("A") is 65; int("1010", 2) converts from base 2.

input() always returns a str, so convert it.

Always handle bad input with try/except ValueError.

There is no implicit conversion between str and numbers.

Key points

  • Implicit casting: Automatic conversion done by Python.
  • Explicit casting: Manual conversion using a function like int().
  • Truncation: Cutting off the decimal part without rounding.
  • ValueError: Error raised when a value has the right type but wrong content.
  • input() returns a string.
  • int("3.5") fails; int(3.99) gives 3.
  • bool("False") is True because the string is not empty.
  • Use try/except to convert user input safely.

Example

Code
implicit and explicit casting:
print(3 + 2.0, type(3 + 2.0))      # 5.0 <class 'float'>
print(True + True)                  # 2

print(int(3.99), int(-3.99))        # 3 -3
print(int("42") + 8)                # 50
print(float("2.5"), float(7))       # 2.5 7.0
print(str(10) + "5")                # 105
print(list("abc"), tuple([1, 2]), set([1, 1, 2]))

print(bool(0), bool("0"), bool(""), bool([]), bool("False"))
# False True False False True

print(chr(65), ord("A"))            # A 65

# safe conversion of user input
raw = "12x"
try:
    num = int(raw)
except ValueError:
    num = 0
    print("invalid number, using 0")
print(num)

# int("3.5") raises ValueError
print(int(float("3.5")))            # 3
5

Python Boolean

The Boolean type bool has exactly two values: True and False. Comparisons and logical operations produce Booleans, and any object can be tested for truth value. bool is a subclass of int, so True equals 1 and False equals 0.

In short: A Boolean is a yes/no value. Python uses it to make decisions.

Think about it

Conditions in if, while and filters all depend on Boolean values and truthiness. is_logged_in = True decides whether to show the dashboard or the login page.

Boolean values come from comparisons (5 > 3), membership tests (x in y), identity tests (x is None) and the bool() function.

Truthiness: these are falsy: False, None, 0, 0.0, 0j, "", [], (), {}, set(), range(0); everything else is truthy, including "0", "False" and [0].

Logical operators short-circuit: A and B returns A if A is falsy, else B; A or B returns A if A is truthy, else B; not always returns a real bool.

Functions all(iterable) (True if all items truthy, True for empty) and any(iterable) (True if at least one truthy, False for empty).

Because bool is an int, True + True is 2 and sum([True, False, True]) counts the True values.

Class instances are truthy unless they define __bool__ or __len__ returning falsy.

Never write if x == True; write if x.

Key points

  • Truthy: Value that behaves as True in a condition.
  • Falsy: Value that behaves as False in a condition.
  • all(): True if every item is truthy.
  • any(): True if at least one item is truthy.
  • True and False start with capital letters.
  • Empty containers, 0 and None are falsy.
  • and/or return operands, not just True/False.
  • all([]) is True; any([]) is False.

Example

Code
Boolean values and truthiness:
print(5 > 3, 5 == 3, "a" in "cat")      # True False True
print(True + True, True * 10)            # 2 10
print(isinstance(True, int))             # True

for v in [0, 1, "", "0", [], [0], None]:
    print(repr(v), bool(v))
# 0 False / 1 True / '' False / '0' True / [] False / [0] True / None False

print([] or "default")                   # default
print("a" and "b", 0 and "b")            # b 0
print(not [], not "x")                   # True False

marks = [True, False, True]
print(sum(marks), all(marks), any(marks))   # 2 False True
print(all([]), any([]))                  # True False

name = ""
if not name:
    print("name is empty")

Solved examples

Example 01 · Basic

Swap the values of x = 5 and y = 9 without a temporary variable.

Given Data:
    Required To Find:

    x = 9, y = 5

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: The right side (y, x) is built first as a tuple
    Step 2: The values are unpacked into x and y
    Final Answer: x, y = 5, 9 x, y = y, x print(x, y) # 9 5

    Approach note: Python swaps in one line; no third variable is needed.

    Example 02 · Intermediate

    Read two numbers as text, "12" and "8", and print their sum and average.

    Given Data:
      Required To Find:

      Sum 20 and average 10.0

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Convert each string using int()
      Step 2: Add the numbers
      Step 3: Divide by 2 using / for a float
      Final Answer: a = int("12") b = int("8") print(a + b, (a + b) / 2) # 20 10.0

      Approach note: Without int(), "12" + "8" would give "128".

      Example 03 · Intermediate

      Find the output: print(bool("False"), bool(0.0), bool([0]), int(7.9), int("7"))

      Given Data:
        Required To Find:

        Five values

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: "False" is a non-empty string → True
        Step 2: 0.0 is zero → False
        Step 3: [0] is a non-empty list → True
        Step 4: int(7.9) truncates → 7
        Step 5: int("7") → 7
        Final Answer: True False True 7 7

        Approach note: Truthiness depends on emptiness or zero, not on the meaning of the text.

        Example 04 · Basic

        Predict the types: a = 7; b = 7.0; c = "7"; d = 7 + 0j. Print type of each.

        Given Data:
          Required To Find:

          Four type names

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: 7 is int
          Step 2: 7.0 is float
          Step 3: "7" is str
          Step 4: 7 + 0j is complex
          Final Answer: <class 'int'> <class 'float'> <class 'str'> <class 'complex'>

          Approach note: A decimal point or j suffix changes the type even if the value looks like 7.

          Real-world applications

          Python

          Using Python Variables & Data Types in real projects

          Billing totals, user input conversion, flags, sensor readings, scores and configuration values.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Python variables must be declared with a type.

          Why this is wrong: Python is dynamically typed; assignment creates the variable.

          ✅ Verified Truth: Type belongs to the value, not to the name.

          ⚠️ Exam Tip: Say "dynamic typing" in viva.

          ❌ Myth: int(3.99) rounds to 4.

          Why this is wrong: int() truncates toward zero.

          ✅ Verified Truth: int(3.99) is 3; use round() to round.

          ⚠️ Exam Tip: Know truncate vs round.

          ❌ Myth: 0.1 + 0.2 equals 0.3 in Python.

          Why this is wrong: Floats use binary fractions and are approximate.

          ✅ Verified Truth: The result is 0.30000000000000004; use math.isclose or Decimal.

          ⚠️ Exam Tip: Classic output question.

          ❌ Myth: bool("False") is False.

          Why this is wrong: Any non-empty string is truthy.

          ✅ Verified Truth: Only the empty string "" is falsy.

          ⚠️ Exam Tip: Truthiness ignores the meaning of text.

          Revision notes

          Variables store data. Data types decide what kind of data it is and what you can do with it. This chapter covers variables, built-in data types, numbers, type casting and the Boolean type.

          High-Yield Quick Revision Points

          1. A variable is a name bound to an object; assignment creates it; no declaration needed.
          2. Naming: letters, digits, underscore; no leading digit; no keywords; case-sensitive; use snake_case.
          3. Built-in types: int, float, complex, str, bool, list, tuple, range, dict, set, frozenset, bytes, NoneType.
          4. Mutable: list, dict, set. Immutable: int, float, str, tuple, frozenset, bool.
          5. int is unlimited; float is approximate (0.1 + 0.2 trap); use Decimal or isclose.
          6. int() truncates; int("3.5") fails; input() returns str.
          7. Falsy: 0, 0.0, "", [], (), {}, set(), None, False; all others are truthy.
          8. bool is a subclass of int; all([]) is True, any([]) is False.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          What is the output of type(3 / 2)?

          Question 2 · MCQ (Interview / semester)

          Which data type is immutable?

          Question 3 · MCQ (Interview / semester)

          What does int("3.5") do?

          Question 4 · MCQ (Interview / semester)

          What is bool([])?

          Question 5 · MCQ (Interview / semester)

          What is the value of True + True?

          Question 6 · MCQ (Interview / semester)

          What does input() always return?