Board Formulas
🐍 PythonπŸ“… Day 2

Variables in Python

Create and use variables in Python. Dynamic typing, common types and assignment patterns.

🎯

Learning objectives

  • β†’Create variables without declaring a type
  • β†’Recognise the common built-in types
  • β†’Use multiple and swap assignment

πŸ’‘ Key points

  • Python is dynamically typed β€” the type is attached to the value, not the variable.
  • A variable is created the first time you assign to it: no declaration needed.
  • Common built-in types: int, float, str, bool, list, tuple, dict, set.
  • Constants are conventional β€” write them in UPPER_CASE; Python has no true 'const'.

πŸ’» Code examples(3)

#1Basic assignments
python
age = 21
price = 99.99
name = "Rohan"
is_active = True
PI = 3.14159        # convention: uppercase = constant
Type is inferred from the value. bool literals are True / False (capitalised).
#2Dynamic typing
python
x = 10
print(type(x))    # <class 'int'>
x = "hello"
print(type(x))    # <class 'str'>
The same name can point to different types at different times. type() returns the current type of the value.
#3Multiple + swap assignment
python
a, b, c = 1, 2, 3         # multiple assignment
x = y = z = 0             # chained
a, b = b, a               # swap without a temp variable
Tuple unpacking makes multi-assignment and swaps a one-liner.

🎯 Practice

Q1. What is the output: `x = 5; x = 'hello'; print(type(x))`?+

<class 'str'> β€” the name x now refers to a string.

Q2. Swap the values of a=10 and b=20 in one line.+

a, b = b, a

Q3. Does Python have a `const` keyword?+

No. UPPER_CASE naming is a convention to signal 'do not modify', but the value can still be reassigned.

πŸ“ Notes

Common built-in types

| Type | Example | Notes | |---|---|---| | int | 42 | Arbitrary precision β€” no overflow | | float | 3.14 | 64-bit IEEE 754 | | str | "hello" or 'hi' | Immutable Unicode string | | bool | True, False | Subclass of int (True == 1) | | list | [1, 2, 3] | Mutable ordered sequence | | tuple | (1, 2, 3) | Immutable ordered sequence | | dict | {"a": 1} | Key–value map | | set | {1, 2, 3} | Unique, unordered |

Naming rules

  • Start with a letter or _; then letters, digits or _.
  • Case-sensitive: name and Name are different.
  • Cannot be a Python keyword.
  • Convention: snake_case for variables and functions.