Lesson: Code That Reads Like English Still Breaks You
š Full written solution: https://timepasshub2539-hue.github.io/leetcode-python/python-basics.html š» Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/python-basics Chapters: 0:00 Code That Reads Like English Still Breaks You 0:24 Your Whole Python Toolkit Fits in a Kitchen 0:46 Variables: Labeled Boxes 1:04 Data Types: Different Jar Shapes 1:30 Lists: A Row of Jars 1:48 Working With Lists 2:04 Conditionals: Asking Yes or No 2:25 Two Ways to Repeat, One Big Idea 2:49 Functions: Reusable Machines 3:09 Common Mistake: Indentation 3:39 Common Mistake: Mixing Types 3:58 Python vs Other Languages 4:27 Recap and Sign-off A full walkthrough of Python fundamentals: variables as labeled boxes, data types as jar shapes, lists and how to work with them, conditionals, the two ways to repeat code, functions as reusable machines, and the indentation and type-mixing mistakes that trip up every beginner. Ends with a Python vs other languages comparison and a full recap. #PythonBasics #LearnPython #CodingForBeginners #PythonTutorial #ProgrammingLesson Watch next: - Python Basics: Variables, Loops, Lists & Functions Explained Simply: https://youtu.be/VnyBhaHk1bA - Complexity: where brute-force dies #shorts: https://youtu.be/ecAz1xC_fok - š” Intermediate: One 0-1-0 sandwich decides a Hard problem #shorts: https://youtu.be/lNBRqUgqkg0
Introduction
Every developer remembers their first Python bug that made no sense. The code looked right. It read almost like a sentence. And it still crashed. That gap between "this looks correct" and "this runs correctly" is where most beginners get stuck, and it's also where a lot of interview candidates lose points on fundamentals they assumed were too basic to review.
Python is often called the most readable programming language, and that's true ā but readability is a double-edged sword. Because Python lets you write code that resembles plain English, it's easy to assume you understand what's happening under the hood when you actually don't. Interviewers know this. That's why even senior candidates get asked to explain how variables are typed, why indentation matters, or what happens when you mix a string and an integer. These aren't beginner questions in disguise ā they're checks for whether you actually understand the language you're using every day.
This article rebuilds Python's core toolkit from the ground up: variables, data types, lists, conditionals, loops, and functions. Along the way, we'll walk through the two mistakes that catch nearly every new Python developer, and we'll reconstruct working code for each concept so you can see exactly how the pieces fit together.
Problem Overview
The "problem" here isn't a single algorithm ā it's a foundation. Before you can solve any real coding challenge, whether it's on LeetCode or in a production codebase, you need fluency in five things:
- Variables ā how Python stores and labels values
- Data types ā how Python distinguishes numbers, text, and true/false values
- Lists ā how Python stores ordered collections of values
- Conditionals ā how your program makes decisions
- Loops and functions ā how your program repeats work and packages logic for reuse
Get these wrong, and every later problem ā reversing a string, traversing a tree, writing a sorting algorithm ā becomes harder than it needs to be, because you're fighting the language instead of solving the problem.
Example
Let's build a concrete example that touches every concept, then explain each output.
age = 25
temperature = 30
name = "Kai"
scores = [7, 9, 3]
scores.append(10)
if temperature > 25:
print("It's hot")
for score in scores:
print(score)
count = 0
while count < 3:
print(count)
count += 1
def greet(name):
return "Hello " + name
print(greet(name))
Output:
It's hot
7
9
3
10
0
1
2
Hello Kai
age = 25creates a variable ā a name pointing at a value. No type declaration needed.temperature > 25evaluates toTrue, so theifblock runs and printsIt's hot.scores.append(10)adds a fourth item to the list, so theforloop prints all four values in order.- The
whileloop prints0,1,2ā it stops the momentcountreaches3, because the conditioncount < 3becomesFalse. greet(name)combines the fixed string"Hello "with whatever name you pass in, and returns it āKaibecomesHello Kai.
Intuition
Here's how an experienced engineer actually thinks about these building blocks ā not as syntax rules to memorize, but as a small set of ideas that combine.
Think of a variable as a labeled jar. You write a name on a sticky note (age), and you drop a value inside (25). The jar doesn't care what's inside until you look ā Python figures out the type automatically based on what you handed it. This is why you never write "this is a number" in Python the way you might in Java or C. Python inspects the value at assignment time and assigns a type behind the scenes.
Every jar has a shape that matches what's inside: whole numbers are integers, decimals are floats, text is a string, yes/no values are booleans. The shape matters because Python treats each type differently during math and comparisons ā you can add two integers, but you can't add a string and an integer without converting one of them first.
A list is a row of jars on a shelf, all sharing one shelf label. The critical detail: counting starts at zero. The first jar is at position 0, the second at position 1. This single fact ā zero-indexing ā causes more early bugs than almost anything else in the language, so it's worth internalizing early rather than re-deriving it every time.
A conditional is a fork in the road ā your code asks a yes/no question and picks a path. Python uses a colon and indentation (not curly braces) to mark which lines belong to that path. This is a deliberate design choice: indentation isn't just cosmetic in Python, it's syntax.
Loops solve one problem two ways. A for loop is for when you already know what you're iterating over ā walk down a known row of jars until you reach the end. A while loop is for when you don't know how many iterations you need in advance ā keep going as long as a condition holds true, like reading a book until you hit the last page without knowing the page count ahead of time.
A function is a machine you build once and reuse forever. You feed it inputs, it hands back an output via return. The entire point is to avoid rewriting the same logic every time you need it.
Once these five ideas click, most of what looks like "Python syntax weirdness" turns out to be logical consequences of these mental models.
Brute Force Solution
There isn't a brute-force algorithm here in the traditional sense ā but there is a brute-force way of writing code that beginners default to, and it's worth naming so you can recognize and avoid it.
Idea: Repeat logic by copy-pasting instead of using loops and functions. Handle every input value with hardcoded checks instead of general conditionals.
print(7)
print(9)
print(3)
print(10)
if age == 25:
print("Kai is 25")
elif age == 26:
print("Kai is 26")
# ...and so on for every possible age
Advantages: Works for a fixed, tiny amount of data. No abstractions to learn.
Disadvantages: Doesn't scale. Add one more score and you have to edit the code by hand. Doesn't generalize to unknown input sizes. Violates the entire point of programming ā automating repetition.
Time complexity: O(n) lines of code for n items ā not O(n) execution time, which is the real red flag. Your source code grows linearly with your data, which is backwards.
Space complexity: Same issue ā no reuse, no compression of logic.
Optimal Solution
The optimal approach uses each tool for what it's built for:
| Task | Right Tool | Why |
|---|---|---|
| Store one value | Variable | Simple label, simple lookup |
| Store many ordered values | List | Indexed access, built-in methods like append |
| Make a decision | if / elif / else |
Explicit branching, readable |
| Repeat over known data | for loop |
Iterates until the collection is exhausted |
| Repeat until a condition changes | while loop |
Doesn't require knowing the count in advance |
| Reuse logic | Function (def) |
Write once, call many times, easy to test |
The mental shift that makes this "optimal" isn't performance ā it's matching structure to intent. A for loop over a list communicates "I'm processing every item" more clearly than a while loop with a manually incremented counter, even though both can technically work. Choosing the right structure makes bugs less likely and code easier for the next person (including future you) to read.
Python Code
def summarize_scores(scores):
"""Return the sum, average, and highest score from a list of numbers."""
if not scores:
return None
total = sum(scores)
average = total / len(scores)
highest = max(scores)
return total, average, highest
def greet(name):
"""Return a friendly greeting for the given name."""
return "Hello " + name
def classify_temperature(temperature):
"""Return a description based on temperature."""
if temperature > 25:
return "It's hot"
elif temperature >= 15:
return "It's mild"
else:
return "It's cold"
if __name__ == "__main__":
scores = [7, 9, 3]
scores.append(10)
total, average, highest = summarize_scores(scores)
print(f"Total: {total}, Average: {average}, Highest: {highest}")
print(classify_temperature(30))
print(greet("Kai"))
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
Code Walkthrough
def summarize_scores(scores):ā defines a reusable function that takes a list.if not scores: return Noneā guards against an empty list, avoiding a division-by-zero error on the average calculation.total = sum(scores)ā uses Python's built-insum, avoiding a manual loop for something the language already provides.average = total / len(scores)ālen()gives the item count; dividing gives the mean.highest = max(scores)ā another built-in, avoids manually tracking a running maximum.return total, average, highestā returns three values as a tuple, unpacked by the caller.classify_temperatureā demonstratesif/elif/elsebranching with three distinct outcomes instead of just two.if __name__ == "__main__":ā ensures this block only runs when the file is executed directly, not when imported elsewhere ā standard practice, not a beginner-only pattern.- The
whileloop incrementscountmanually and stops once the conditioncount < 3is false.
Dry Run
Let's trace summarize_scores([7, 9, 3, 10]):
| Step | Variable | Value |
|---|---|---|
| Check empty | scores |
[7, 9, 3, 10] ā not empty, continue |
total = sum(scores) |
total |
29 |
average = total / len(scores) |
average |
29 / 4 = 7.25 |
highest = max(scores) |
highest |
10 |
| Return | ā | (29, 7.25, 10) |
Printed output: Total: 29, Average: 7.25, Highest: 10
Then classify_temperature(30) checks 30 > 25 ā True ā returns "It's hot".
Then greet("Kai") returns "Hello " + "Kai" ā "Hello Kai".
Then the while loop runs three times, printing Count is 0, Count is 1, Count is 2, stopping when count becomes 3.
Complexity Analysis
sum(scores)ā O(n), where n is the number of scores, since it visits each element once.max(scores)ā O(n), same reasoning.len(scores)ā O(1), Python lists track their length internally.- Overall
summarize_scoresā O(n) time, O(1) extra space (we don't build any new collections, just accumulate scalars). - The
whileloop ā O(k) where k is the fixed iteration count (3), so effectively O(1) here since it doesn't scale with input size.
These are correct because each operation touches the input at most a constant number of times ā no nested loops, no repeated scans.
Alternative Solutions
Instead of a while loop with a manual counter, you could use range():
for count in range(3):
print(f"Count is {count}")
Comparison: This is more idiomatic when you know the exact number of iterations in advance ā it removes the risk of forgetting to increment count (which causes infinite loops, a very common beginner mistake). Use while when the stopping condition depends on something that changes unpredictably, like reading input until a sentinel value appears. Use for with range() when the count is fixed and known upfront.
Edge Cases
- Empty list:
summarize_scores([])returnsNoneinstead of crashing ontotal / len(scores). - Single-item list:
summarize_scores([5])should return(5, 5.0, 5)ā average equals the single value. - Duplicate values:
[7, 7, 7]āmax()still works correctly, returning7. - Negative numbers:
[-3, -1, -10]āsum,average, andmaxall still behave correctly;maxreturns-1, the "highest" of the negatives. - Very large lists: Performance stays linear ā no hidden quadratic behavior from
sumormax. - Mixed types in a list:
[7, "9", 3]ā this will crashsum()with aTypeError, since Python won't silently add an integer and a string.
Common Mistakes
- Mixing tabs and spaces. Python reads indentation as syntax, and inconsistent whitespace throws an
IndentationErroreven when the code looks visually aligned in your editor. - Concatenating a string and a number directly.
"Age: " + 25fails ā you must convert withstr(25)first. - Off-by-one errors from zero-indexing. Assuming the "second" item is at index
2instead of1. - Infinite
whileloops. Forgetting to update the loop's condition variable (like forgettingcount += 1) causes the loop to run forever. - Assuming a list method returns a new list.
list.append()modifies the list in place and returnsNoneā writingscores = scores.append(10)silently setsscorestoNone. - Comparing types that don't match. Comparing a string
"25"to an integer25with==returnsFalse, which surprises beginners expecting Python to coerce types automatically. - Forgetting the colon after
if,for,while, ordef. A small syntax slip that produces aSyntaxErrorimmediately.
Interview Questions
- What's the difference between a
listand atuplein Python, and when would you choose one over the other? - Why does Python use indentation instead of braces, and what tradeoffs does that create?
- Explain the difference between
isand==when comparing values. - What happens if you call a function with too few or too many arguments?
- How does Python decide the type of a variable, and can that type change later?
- What's the time complexity of
list.append()versus inserting at the front of a list?
Similar Problems
- Two Sum (LeetCode #1): Reinforces list traversal and conditional logic ā the same fundamentals used to search and compare values.
- Valid Parentheses (LeetCode #20): Builds on conditionals and loops, introducing stacks as a natural extension of lists.
- FizzBuzz: A classic beginner exercise that combines loops and conditionals almost identically to the temperature example above.
- Reverse a String (LeetCode #344): Tests list/string indexing and loop mechanics directly.
Key Takeaways
- Variables are labels pointing at values ā Python infers the type automatically.
- Data types (int, float, string, boolean) determine how values behave in math and comparisons.
- Lists store ordered values, indexed starting at zero.
- Conditionals let your program choose between paths based on a question.
forloops iterate over known collections;whileloops repeat until a condition changes.- Functions package logic once so you never rewrite it.
- The two mistakes that catch nearly every beginner: inconsistent indentation, and mixing strings with numbers without converting first.
Watch the Video
For the full walkthrough with live code and the kitchen analogies that make these concepts stick, watch the video here: {LINK}
About the Series
This breakdown is part of the Daily Python LeetCode series, where each entry takes a coding concept or interview problem and rebuilds it from first principles ā not just showing the solution, but explaining the reasoning an experienced engineer uses to get there. Whether you're preparing for interviews or strengthening your fundamentals, the goal is the same: understand the "why," not just memorize the "what."
Call To Action
If this helped clarify Python's fundamentals, like the video on YouTube and subscribe so future breakdowns land in your feed. For deeper dives delivered straight to your inbox, subscribe to the Substack newsletter. Drop a comment with the Python bug that once cost you an afternoon ā chances are someone else has hit the same one. And if you know a developer just starting out, share this with them.
The solution
for score in [7, 3, 9]:
print(score)
count = 0
while count < 3:
print(count)
count += 1Ready to try it yourself? Solve General problems with instant feedback in the practice sandbox.
Practice now ā


