π Quick Recap (Day 3)
You mastered
print()and saw how comments work.You created simple scripts like
hello.pyandfavorite.py.
π― What Youβll Learn Today
What variables are and why we use them.
The basic data types in Python: whole numbers, decimal numbers, text, and true/false values.
How to convert values from one type to another.
π Overview: What Is a Variable?
A variable is like a labeled box in the computerβs memory. You give the box a name and put something inside it: a number, a word, or a true/false value.
age = 5 # stores the whole number 5 in a box labeled age
name = "Alice" # stores the text βAliceβ in a box labeled nameThe name on the left (
age,name) is the boxβs label.The
=sign means βput whatβs on the right into the labeled box on the left.β
Why Use Variables?
Readability: Labels make your code much easier to understand.
Reusability: Use the same value in multiple places without retyping it.
Flexibility: Change the value in one place and it updates everywhere.
π Data Types in Python
Every value has a type. The most common types youβll use first are:
Type | Example | Description |
|---|---|---|
int |
| Whole numbers |
float |
| Decimal (floating-point) |
str |
| Text (strings) |
bool |
| True/false values |
You can check a variableβs type with the type() function:
x = 10
print(type(x)) # β <class 'int'>
y = "hi"
print(type(y)) # β <class 'str'>
z = True
print(type(z)) # β <class 'bool'>π Converting Between Types
Sometimes you need to change a valueβs type:
str(value): turnsvalueinto text (string).int(value): turnsvalueinto a whole number (if itβs valid).float(value): turnsvalueinto a decimal number.
num = 5
text_version = str(num) # "5"
print(text_version, type(text_version))
pi = 3.14
whole_part = int(pi) # 3
print(whole_part, type(whole_part))
num_str = "42"
num_int = int(num_str) # 42
print(num_int * 2) # 84π§ββοΈ Take the Wand and Try Yourself
Create a file called
data_types.py.Inside, declare and print these variables (each on its own line):
An integer of your choice.
A float of your choice.
A string with your favorite quote.
A boolean showing whether you like Python (
TrueorFalse).
Use
type()to print the type of each variable.Convert your float to an integer, then print that integer and its type.
Solution Example (data_types.py):
# data_types.py
num = 10
print(num)
print(type(num))
pi = 3.14
print(pi)
print(type(pi))
quote = "Code is like magic."
print(quote)
print(type(quote))
likes_python = True
print(likes_python)
print(type(likes_python))
# Convert float to int
pi_as_int = int(pi)
print(pi_as_int)
print(type(pi_as_int))Run:
python data_types.pyExpected output:
10
<class 'int'>
3.14
<class 'float'>
Code is like magic.
<class 'str'>
True
<class 'bool'>
3
<class 'int'>Once you see these correct values and types, youβve mastered variables and data types!
Ready for Day 5: Code Style & Best Practices? Letβs continue!