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
- Variables and assignment
- Basic data types:
int,float,str,bool - Collection data types:
list,tuple,dict,set - Type checking and type conversion
forloopswhileloopsbreakandcontinue
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— eitherTrueorFalse
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:
- Python takes the first item in the list.
- It runs the loop body using that item.
- It moves to the next item and repeats step 2.
- This continues until every item has been processed, then the loop ends.
For a while loop:
- Python checks the condition.
- If
True, it runs the loop body, then re-checks the condition. - 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
pythonage = 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 toagebased on its value.for mark in marks:runs the loop body once for every value inside themarkslist, storing the current value inmarkeach time.range(1, 6)generates numbers from 1 up to (but not including) 6 — this is a common beginner trip-up.count = count - 1reducescountby 1 each time through thewhileloop, which is essential — without it, the loop would run forever.breakinside theif mark < 70:block exits the loop the moment a mark below 70 is found, so nothing after it in the loop runs again.continueskips 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
whileloops can accidentally run forever ("infinite loops") if the condition never becomesFalse. - Using the wrong collection type (e.g., a
listwhen adictwould be clearer) can make code harder to read.
14. Common Mistakes
- Forgetting to update the loop-control variable in a
whileloop, causing an infinite loop. - Confusing
list(changeable, square brackets) withtuple(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_marksinstead ofx). - Prefer
forloops when the number of repetitions is known or based on a collection; preferwhileloops when repetition depends on a changing condition. - Use a
dictwhen data naturally has labeled fields (like a student record); use alistfor simple ordered collections. - Always double-check that a
whileloop's condition will eventually becomeFalse.
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
listand atuple(mutability). - Know why a
setautomatically removes duplicate values. - Understand the difference between
forandwhileloops, and when to use each. - Be able to explain what
breakandcontinuedo 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.forloops iterate over a sequence;whileloops repeat based on a condition.breakexits a loop entirely;continueskips to the next iteration.
19. Comparison Tables
`for` Loop vs `while` Loop
| Aspect | for Loop | while Loop |
|---|---|---|
| Best used when | Number of repetitions or a collection is known | Repetition depends on a changing condition |
| Risk of infinite loop | Very low | Higher, if condition is never updated |
| Common use | Iterating over lists, ranges | Waiting for a condition to change |
`list` vs `tuple` vs `dict` vs `set`
| Aspect | list | tuple | dict | set |
|---|---|---|---|---|
| Brackets | [ ] | ( ) | { } (key:value) | { } (values only) |
| Changeable? | Yes | No | Yes | Yes |
| Ordered? | Yes | Yes | Insertion-ordered | No |
| Duplicates allowed? | Yes | Yes | Keys must be unique | No |
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). forloops iterate over a sequence;whileloops repeat while a condition isTrue.breakstops a loop completely;continueskips to the next iteration.