Learning Objectives – after this chapter you will be able to:
  • Create variables and follow naming conventions.
  • Identify Python’s built-in data types and check them with type().
  • Explain dynamic typing and multiple assignment.
  • Distinguish mutable and immutable types.
Variables
  • A variable is a name that refers to a value stored in memory. It is created the moment you assign a value with =; there is no separate declaration.
  • In Python a variable is a reference (label) to an object – the object has the type, not the name.
  • Recommended style (PEP 8): lowercase names with underscores, e.g. student_name, total_marks.
name = "Asha"          # str
age = 20               # int
height = 5.4           # float
is_student = True      # bool
print(name, age, height, is_student)

# Multiple assignment
x, y, z = 10, 20, 30
a = b = c = 0
print(x, y, z, a, b, c)

# Swapping two variables
x, y = y, x
print(x, y)
Output
Asha 20 5.4 True
10 20 30 0 0 0
20 10
Built-in Data Types
CategoryTypeExampleMutable?
Numericint25, -7 (no size limit)No
float3.14, 2.5e3No
complex2 + 3jNo
Textstr"Python", 'A'No
BooleanboolTrue, FalseNo
Sequencelist[1, 2, 3]Yes
tuple(1, 2, 3)No
rangerange(5)No
Setset{1, 2, 3}Yes
Mappingdict{"a": 1}Yes
None typeNoneTypeNone (means “no value”)No
Checking types with type()
print(type(25))
print(type(3.14))
print(type(2 + 3j))
print(type("Python"))
print(type(True))
print(type([1, 2]))
print(type((1, 2)))
print(type({1, 2}))
print(type({"a": 1}))
print(type(None))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
<class 'NoneType'>
Dynamic Typing and isinstance()

Because Python is dynamically typed, the same variable can refer to values of different types at different times. Use isinstance() to test a type in programs.

value = 100
print(type(value))
value = "one hundred"
print(type(value))
print(isinstance(value, str))
print(isinstance(True, int))   # bool is a subclass of int
Output
<class 'int'>
<class 'str'>
True
True
Mutable vs Immutable
  • Immutable objects cannot be changed after creation: int, float, str, bool, tuple. “Changing” them actually creates a new object.
  • Mutable objects can be changed in place: list, dict, set.
  • id() returns an object’s identity; it stays the same when a mutable object is modified.
nums = [1, 2, 3]
before = id(nums)
nums.append(4)              # list changed in place
print(nums, id(nums) == before)

word = "hi"
before = id(word)
word = word + "!"           # a NEW string object is created
print(word, id(word) == before)

try:
    word[0] = "H"           # strings cannot be changed
except TypeError as e:
    print("Error:", e)
Output
[1, 2, 3, 4] True
hi! False
Error: 'str' object does not support item assignment
Key Takeaways
  • Variables are names referring to objects; they are created by assignment.
  • Main types: int, float, complex, str, bool, list, tuple, range, set, dict and None.
  • Lists, dicts and sets are mutable; numbers, strings and tuples are immutable.
Video : Variables and Data Types
Question / Answer (15 questions)

Answer : A variable is a name that refers to an object (value) stored in memory. It is created automatically when a value is first assigned to it with the = operator; no type declaration is needed.

Answer : In C a variable must be declared with a type before use (int x;). In Python a variable is created simply by assigning a value (x = 10), and its type comes from the value.

Answer : int for whole numbers (25, -7), float for decimal numbers (3.14, 2.5e3) and complex for complex numbers (2 + 3j).

Answer : type() returns the class (data type) of the object passed to it, for example type(3.14) returns <class 'float'>.

Answer : type(x) returns the exact class of x. isinstance(x, T) returns True if x is an instance of T or of a subclass of T, which makes it the preferred way to test types in programs. For example isinstance(True, int) is True because bool is a subclass of int.

Answer : None is a special constant that represents the absence of a value. Its type is NoneType. Functions that do not return anything explicitly return None.

Answer : Several variables can be assigned in one statement: x, y, z = 10, 20, 30 assigns each value to the corresponding name, and a = b = c = 0 assigns the same value to all three names.

Answer : Using tuple packing and unpacking: x, y = y, x. No temporary variable is needed.

Answer : Mutable objects can be changed in place after creation – list, dict and set. Immutable objects cannot be changed – int, float, str, bool and tuple; any “change” creates a new object.

Answer : Strings are immutable, so their characters cannot be replaced. Python raises TypeError: 'str' object does not support item assignment. A new string must be created instead.

Answer : id() returns an integer that uniquely identifies an object during its lifetime (its identity). If a mutable object is modified in place, its id stays the same.

Answer : The type is associated with the value, not the variable, and is checked at run time. Example: value = 100 (int) and later value = "one hundred" (str) – the same name now refers to a string.

Answer : No fixed limit. Python int has arbitrary precision and can grow as large as available memory allows.

Answer : Lowercase words separated by underscores (snake_case), for example total_marks or student_name.

Answer : Sequence types store ordered items accessed by position – str, list, tuple and range. A mapping type stores key–value pairs – dict.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What is the output of print(type(3.0))?

Show Answer

Correct Answer : B. <class 'float'>
3.0 has a decimal point, so it is a float.

Q2. Which of the following data types is MUTABLE?

Show Answer

Correct Answer : D. list
Lists can be changed in place; tuples, strings and integers cannot.

Q3. After x, y = 5, 9 and then x, y = y, x, what is the value of x?

Show Answer

Correct Answer : A. 9
The values are swapped, so x becomes 9.

Q4. What is the type of None?

Show Answer

Correct Answer : C. NoneType
type(None) is <class 'NoneType'>.

Q5. What does isinstance(True, int) return?

Show Answer

Correct Answer : B. True
bool is a subclass of int, so True is an instance of int.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Python Software Foundation. (n.d.). An Informal Introduction to Python. In The Python Tutorial. https://docs.python.org/3/tutorial/introduction.html
  2. Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
  3. Python Software Foundation. (n.d.). Data Model. In The Python Language Reference. https://docs.python.org/3/reference/datamodel.html
  4. Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
  5. van Rossum, G., Warsaw, B., & Coghlan, N. (2001). PEP 8 – Style Guide for Python Code. Python Enhancement Proposals. https://peps.python.org/pep-0008/
  6. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
  7. Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.