Python Lesson 2: Variables & Data Types (int, float, str, bool) Explained
Learn how Python variables actually work: what a variable is, how assignment fills it, and the core data types you'll use constantly, integers, floats, strings, and booleans. We cover dynamic typing (how Python figures out types for you), two classic beginner mistakes with quotes and mixed-type math, and how dynamic typing compares to static typing. Perfect for absolute beginners starting their Python journey. #Python #LearnPython #PythonForBeginners #CodingTutorial #PythonBasics
Introduction
Every programming language needs a way to store information, and Python's answer is the variable. Before you can write a single meaningful program — a calculator, a to-do list, a game — you need to understand how Python holds data in memory and how it decides what kind of data it's holding.
This sounds basic, and it is, but it's also one of the most common places where beginners get tripped up, and where interviewers quietly test whether someone actually understands the language or just memorized syntax. Questions like "what's the difference between 5 and 5.0?" or "why did concatenating a string and a number crash?" come up constantly in junior developer interviews, because they reveal whether you understand Python's type system or you've just been copy-pasting code that happens to work.
Once you have a solid mental model of variables and data types, most of what follows in Python — functions, loops, data structures — becomes much easier, because they're all just operations performed on these basic building blocks.
Problem Overview
There's no LeetCode-style problem here — this is a foundational concept — but let's frame it as a set of questions every Python program needs to answer:
- How do you create a named storage location for a value?
- How does Python know what kind of value is stored, without you declaring it?
- What are the basic categories of values you'll work with constantly?
- What happens when you try to mix incompatible types together?
In Python, the answer to the first question is assignment: you write a name, an equals sign, and a value. Python then automatically figures out the type — this is called dynamic typing, and it's one of the defining features of the language.
Example
age = 25
name = "Maya"
height = 5.9
is_student = True
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
Let's walk through what's happening:
age = 25creates an integer — a whole number with no decimal component.name = "Maya"creates a string — text, wrapped in quotes.height = 5.9creates a float — a number with a decimal point.is_student = Truecreates a boolean — one of exactly two values,TrueorFalse, always capitalized.
The type() function is your best friend when you're not sure what you're dealing with. Print it, and Python tells you exactly what's stored.
A subtle but important detail: 10, 10.0, and "10" are three completely different types, even though they look almost identical.
print(type(10)) # int
print(type(10.0)) # float
print(type("10")) # str
The presence of a decimal point makes it a float. The presence of quotes makes it a string, even if the characters inside are digits.
Intuition
Here's how an experienced engineer thinks about this, rather than just memorizing rules.
Picture a labeled box sitting on a shelf. The label is the variable name. Whatever you put inside the box is the value. The material the contents are made of — a stack of coins, a piece of paper with words on it, a light switch that's either on or off — that's the data type.
When you write age = 25, you're not declaring "this box shall forever hold whole numbers." You're just placing a whole number inside a box labeled age right now. Python inspects what you handed it and tags the box with the appropriate type internally — you never state the type yourself.
This is the core intuition behind dynamic typing: the box doesn't care what's inside it. You can empty it out and put something else in later:
age = 25
age = "twenty-five" # totally legal, the box just holds something new now
Compare that to static typing (used in languages like Java or C++), where you declare up front, "this box only ever holds integers," and the compiler enforces that forever. Static typing catches type mistakes earlier — before the program even runs — at the cost of more upfront ceremony. Dynamic typing is faster to write and more flexible, but a type mismatch might not surface until the exact line of code that breaks actually executes. Neither is objectively better; it's a tradeoff between writing speed and early safety.
Once you internalize "the box doesn't lock in a type, the value you hand it determines the type," most of Python's behavior around variables stops feeling like magic and starts feeling obvious.
Brute Force Solution
There isn't really a "brute force" version of storing a value — but there is a brute-force way beginners often approach type-checking, worth calling out because it's a common early mistake:
Idea: Manually check every value in your code using type() calls scattered everywhere, or worse, guess the type based on how the value looks in your source code.
Algorithm:
- Write a value.
- Assume its type based on appearance.
- Proceed without verifying.
Advantages: None, really — this isn't a real technique, it's the absence of one.
Disadvantages: It's exactly how bugs like TypeError: can only concatenate str (not "int") to str sneak into code — someone assumed a value was a string when it was actually an integer, and never checked.
Time complexity: N/A (this describes a habit, not an algorithm) Space complexity: N/A
The "optimal solution" here isn't a smarter algorithm — it's a disciplined habit.
Optimal Solution
The real solution is a small set of practices that prevent the two classic beginner mistakes.
Mistake 1: Mixing strings and numbers with +
price = 20
message = "Total: $" + price # TypeError
Python refuses to guess whether you meant to add numbers or concatenate text, so it raises a TypeError. The fix is to explicitly convert the number to a string using str():
message = "Total: $" + str(price) # "Total: $20"
Mistake 2: Forgetting quotes around text
color = red # NameError: name 'red' is not defined
Without quotes, Python assumes red is the name of some other variable. Since no such variable exists, it crashes with a NameError. The fix is simply remembering that text always needs quotes:
color = "red"
Here's a quick reference table for the four basic types:
| Type | Example | Use case |
|---|---|---|
int |
25 |
Counting, scores, whole quantities |
float |
19.99 |
Prices, measurements, precise values |
str |
"Maya" |
Names, messages, any text |
bool |
True |
Yes/no decisions, flags, conditions |
And naming conventions worth internalizing early:
- Use descriptive names:
total_priceinstead oftp. - Use underscores instead of spaces:
user_name, notuser name. - Python is case-sensitive:
ageandAgeare two separate variables.
Python Code
def demonstrate_variables():
"""Show variable assignment, type checking, and safe conversion."""
age = 25
name = "Maya"
height = 5.9
is_student = True
print(f"{name} is {age} years old, {height} ft tall, student: {is_student}")
# Explicit conversion avoids the classic str + int crash
price = 20
message = "Total: $" + str(price)
print(message)
return age, name, height, is_student, message
if __name__ == "__main__":
demonstrate_variables()
Code Walkthrough
age = 25,name = "Maya",height = 5.9,is_student = True— four assignments, four different data types, no type declarations needed.- The f-string (
f"...") embeds each variable directly into a formatted message — this is the standard, readable way to combine text and values in modern Python, safer than manual+concatenation. str(price)explicitly converts the integer to a string before concatenation, which is the fix for Mistake 1 above.- The function returns all values as a tuple, which is useful if you want to test the function's output.
Dry Run
Let's trace demonstrate_variables() step by step:
age = 25→ Python creates an int, stores25under the nameage.name = "Maya"→ Python creates a str, stores"Maya"under the namename.height = 5.9→ Python creates a float, stores5.9under the nameheight.is_student = True→ Python creates a bool, storesTrueunder the nameis_student.- The f-string evaluates each variable and produces:
"Maya is 25 years old, 5.9 ft tall, student: True". price = 20→ an int.str(price)converts20(int) into"20"(str)."Total: $" + "20"→ string concatenation succeeds, producing"Total: $20".
Output:
Maya is 25 years old, 5.9 ft tall, student: True
Total: $20
Complexity Analysis
Variable assignment and type checking are both O(1) in time and space — Python's variable binding is a constant-time operation (it just updates a reference in a namespace dictionary), and each value occupies a fixed, small amount of memory relative to the program overall. There's no loop or recursive structure involved, so there's nothing to analyze beyond "this happens once, immediately."
Alternative Solutions
The main "alternative" worth knowing is explicit type declaration using type hints, introduced for readability (not enforcement) in modern Python:
age: int = 25
name: str = "Maya"
This doesn't change Python's dynamic typing behavior at runtime — Python still won't stop you from reassigning age = "twenty-five" later — but it communicates intent to other developers and lets tools like mypy catch mismatches during development. It's a good habit in larger codebases, though unnecessary for small beginner scripts.
Edge Cases
- Empty string vs. no value:
name = ""is a valid string of zero length, different from not assigningnameat all. - Reassigning across types:
x = 5thenx = "5"is legal — the variable itself has no fixed type, only the current value does. - Large integers: Python has no fixed integer size limit (unlike many languages), so
x = 10**100works without overflow. - Float precision:
0.1 + 0.2doesn't exactly equal0.3due to floating-point representation — a common gotcha when comparing floats directly. - Boolean as integer:
True == 1andFalse == 0both evaluate toTruein Python, since booleans are technically a subtype of int.
Common Mistakes
- Concatenating a string and a number directly with
+without converting first. - Forgetting quotes around text, causing a
NameErrorinstead of the intended string. - Assuming a variable's type never changes, then being surprised when reassignment changes it.
- Comparing floats with
==and getting unexpected results due to precision issues. - Using vague variable names like
x,temp, ordata1that make code hard to read later. - Confusing
ageandAgeas the same variable — Python is case-sensitive. - Assuming
"10"and10behave identically just because they display the same.
Interview Questions
- What's the difference between dynamic and static typing, and what's the tradeoff?
- Why does
"5" + 5raise an error, and how do you fix it? - Is a boolean a separate type from an integer in Python, or related to it?
- What does
type()return, and how would you use it to debug a type mismatch? - Why is
5.0a float and not an int, even though it represents a whole number?
Similar Problems
- Type Conversion / Casting exercises — practicing
int(),float(),str(),bool()conversions reinforces this same intuition about types. - String Formatting (LeetCode-style string manipulation problems) — most string problems assume comfort with concatenation and type conversion first.
- Truthy/Falsy Evaluation problems — booleans interacting with conditionals is a natural next step after this lesson.
Key Takeaways
- Variables are labeled boxes created through assignment (
=) — Python infers the type from the value you hand it. - The four foundational types are
int,float,str, andbool. - Python uses dynamic typing: a variable's type can change over its lifetime, unlike statically typed languages.
- The two classic beginner errors — mixing types with
+, and forgetting quotes — both stem from misunderstanding what type a value actually is. - Good variable names and consistent casing prevent subtle bugs down the line.
Watch the Video
For the full walkthrough with live coding and terminal output, watch the video here: {LINK}
About the Series
This lesson is part of the Daily Python LeetCode series, where every video breaks down one core Python concept or interview problem, builds the intuition behind it, and turns it into a clean, working solution. Whether you're just starting out or brushing up before interviews, the series is built to take you from fundamentals to interview-ready, one lesson at a time.
Call To Action
If this helped clarify how variables and types work, subscribe on YouTube so you don't miss the next lesson, and subscribe to the newsletter on Substack for the written breakdown delivered straight to your inbox. Drop a comment with any questions — and if you know someone starting their Python journey, share this with them.
The solution
# color = red # error, red looks like a variable
color = "red"
print(color)Ready to try it yourself? Solve General problems with instant feedback in the practice sandbox.
Practice now →


