Skip to content
C

Variables, Data Types, Loops

Complete learning notes


1. Introduction

Now that you know how to run basic Python statements, it's time to learn how Python stores information (variables), what kinds of information it can store (data types), and how to repeat actions automatically (loops). These three ideas together form the actual "thinking machinery" of every program you'll ever write — including every ML script in this course.


2. What are Variables, Data Types, and Loops?

Simple definition: A variable is a named container that holds a value. A data type tells Python what kind of value is stored (a number, text, a list of items, etc.). A loop lets you repeat a block of code multiple times without rewriting it.

Technical explanation: In Python, a variable is a label bound to an object in memory. Python is dynamically typed, meaning the same variable name can be reassigned to a different type of object at any time. Loops (for and while) allow iterative execution — repeating a block of statements either a fixed number of times or until a condition becomes false.


3. Why is it Important?

  • Nearly every dataset you'll process in ML is stored using these basic data types (numbers, text, lists, dictionaries).
  • Loops are how we process data row-by-row, train models across many iterations, and automate repetitive calculations.
  • Understanding data types prevents confusing bugs later (e.g., trying to do math on text).

4. Prerequisites

You should be comfortable with Topic 1 — Python Basics (print(), input(), comments, indentation).


5. Core Concepts

  1. Variables and assignment
  2. Basic data types: int, float, str, bool
  3. Collection data types: list, tuple, dict, set
  4. Type checking and type conversion
  5. for loops
  6. while loops
  7. break and continue

6. Detailed Explanation

a) Variables

A variable is created the moment you assign a value to a name using =. Python figures out the type automatically — you never need to declare it in advance.

b) Basic Data Types

  • int — whole numbers (e.g., 25)
  • float — decimal numbers (e.g., 25.5)
  • str — text, written inside quotes (e.g., "hello")
  • bool — either True or False

c) Collection Data Types

  • list — an ordered, changeable collection, written with square brackets: [1, 2, 3]
  • tuple — an ordered, unchangeable (immutable) collection, written with round brackets: (1, 2, 3)
  • dict — a collection of key-value pairs, written with curly braces: {"name": "Riya", "age": 21}
  • set — an unordered collection of unique values: {1, 2, 3}

In simple words: think of a list as a shopping list you can edit, a tuple as a printed receipt you can't change, a dict as a labeled filing cabinet, and a set as a bag where duplicate items automatically disappear.

d) Type Checking and Conversion

type(x) tells you what data type a variable currently holds. Functions like int(), float(), and str() convert a value from one type to another.

e) `for` Loops

A for loop repeats a block of code once for every item in a sequence (like a list, or a range of numbers).

f) `while` Loops

A while loop repeats a block of code as long as a given condition stays True.

g) `break` and `continue`

break immediately stops a loop entirely. continue skips the rest of the current iteration and moves to the next one.


7. How It Works

For a for loop over a list:

  1. Python takes the first item in the list.
  2. It runs the loop body using that item.
  3. It moves to the next item and repeats step 2.
  4. This continues until every item has been processed, then the loop ends.

For a while loop:

  1. Python checks the condition.
  2. If True, it runs the loop body, then re-checks the condition.
  3. If False, the loop stops immediately.

8. Real-World Example

A list is like a to-do list on paper — you can add tasks, cross them off, or reorder them. A for loop is like going through that to-do list one task at a time, doing each one before moving to the next, until the list is finished.


9. Technical Example

python
age = 21 # int height = 5.6 # float name = "Aarav" # str is_student = True # bool

Here, Python automatically assigns each variable the correct data type based on the value given — no manual type declaration needed.


10. Python Example

python
# Variables of different data types age = 21 height = 5.6 name = "Aarav" is_student = True print(type(age)) # <class 'int'> print(type(height)) # <class 'float'> print(type(name)) # <class 'str'> print(type(is_student)) # <class 'bool'> # A list of student marks marks = [78, 85, 90, 66, 92] # for loop - print each mark for mark in marks: print("Mark:", mark) # for loop with range() - print numbers 1 to 5 for i in range(1, 6): print("Number:", i) # while loop - countdown from 5 count = 5 while count > 0: print("Countdown:", count) count = count - 1 # break example - stop when a failing mark is found for mark in marks: if mark < 70: print("Found a low mark, stopping loop.") break # continue example - skip marks below 80 for mark in marks: if mark < 80: continue print("Good mark:", mark) # A dictionary storing student info student = {"name": "Aarav", "age": 21, "passed": True} print(student["name"])

Expected Output:

text
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> Mark: 78 Mark: 85 Mark: 90 Mark: 66 Mark: 92 Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Found a low mark, stopping loop. Good mark: 85 Good mark: 90 Good mark: 92 Aarav

11. Code Explanation

  • type(age) shows the data type Python assigned to age based on its value.
  • for mark in marks: runs the loop body once for every value inside the marks list, storing the current value in mark each time.
  • range(1, 6) generates numbers from 1 up to (but not including) 6 — this is a common beginner trip-up.
  • count = count - 1 reduces count by 1 each time through the while loop, which is essential — without it, the loop would run forever.
  • break inside the if mark < 70: block exits the loop the moment a mark below 70 is found, so nothing after it in the loop runs again.
  • continue skips printing for any mark below 80, but the loop still moves on to check the next mark.
  • student["name"] retrieves the value linked to the key "name" inside the dictionary.

12. Advantages

  • Dynamic typing means faster, simpler code writing.
  • Loops eliminate repetitive, error-prone manual code.
  • Rich built-in collection types (list, dict, etc.) cover almost every data-organization need without extra libraries.

13. Limitations

  • Dynamic typing can hide type-related bugs until the program actually runs.
  • Poorly controlled while loops can accidentally run forever ("infinite loops") if the condition never becomes False.
  • Using the wrong collection type (e.g., a list when a dict would be clearer) can make code harder to read.

14. Common Mistakes

  • Forgetting to update the loop-control variable in a while loop, causing an infinite loop.
  • Confusing list (changeable, square brackets) with tuple (unchangeable, round brackets).
  • Assuming range(1, 6) includes 6 — it stops just before the second number.
  • Using = (assignment) when == (comparison) was intended.
  • Trying to change a value inside a tuple, which raises an error since tuples are immutable.

15. Best Practices

  • Use meaningful variable names (total_marks instead of x).
  • Prefer for loops when the number of repetitions is known or based on a collection; prefer while loops when repetition depends on a changing condition.
  • Use a dict when data naturally has labeled fields (like a student record); use a list for simple ordered collections.
  • Always double-check that a while loop's condition will eventually become False.

16. Real-World Applications

  • Storing a dataset's rows in lists or dictionaries before feeding them into an ML model.
  • Looping through thousands of data rows to clean or transform values.
  • Using loops during model training to repeat calculations across many iterations (epochs).

17. Interview-Oriented Points

  • Be ready to explain the difference between a list and a tuple (mutability).
  • Know why a set automatically removes duplicate values.
  • Understand the difference between for and while loops, and when to use each.
  • Be able to explain what break and continue do differently.

18. Exam-Oriented Points

  • Variables in Python don't need explicit type declarations.
  • list = mutable, ordered; tuple = immutable, ordered; dict = key-value pairs; set = unique, unordered values.
  • for loops iterate over a sequence; while loops repeat based on a condition.
  • break exits a loop entirely; continue skips to the next iteration.

19. Comparison Tables

`for` Loop vs `while` Loop

Aspectfor Loopwhile Loop
Best used whenNumber of repetitions or a collection is knownRepetition depends on a changing condition
Risk of infinite loopVery lowHigher, if condition is never updated
Common useIterating over lists, rangesWaiting for a condition to change

`list` vs `tuple` vs `dict` vs `set`

Aspectlisttupledictset
Brackets[ ]( ){ } (key:value){ } (values only)
Changeable?YesNoYesYes
Ordered?YesYesInsertion-orderedNo
Duplicates allowed?YesYesKeys must be uniqueNo

20. Quick Revision

  • A variable is a labeled container for a value; Python assigns its data type automatically.
  • Core data types: int, float, str, bool.
  • Collection types: list (changeable), tuple (unchangeable), dict (key-value pairs), set (unique values).
  • for loops iterate over a sequence; while loops repeat while a condition is True.
  • break stops a loop completely; continue skips to the next iteration.

Mock Test

  • Variables, Data Types, Loops — Quick Test

    A 10-question multiple-choice check on Variables, Data Types, Loops.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems