Lesson 2: Variables and Data Types#
Variables are like labeled boxes that store information. They’re one of the most fundamental concepts in programming!
What You’ll Learn#
Creating and naming variables
Understanding different data types
Type checking and conversion
Variable operations and best practices
💡 Real-World Analogy#
Think of variables like labeled storage containers:
The label is the variable name (e.g.,
age)The contents are the value (e.g.,
25)The type of container determines what you can store (numbers, text, etc.)
1. Creating Your First Variables#
A variable is created when you assign a value using the = sign.
Syntax: variable_name = value
# Creating variables
name = "Alice"
age = 25
height = 5.6
is_student = True
# Display the variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is student:", is_student)
📝 Variable Naming Rules#
Rules you MUST follow:
Can contain letters, numbers, and underscores
Must start with a letter or underscore (not a number)
Case-sensitive (
ageandAgeare different!)Cannot use Python keywords (
if,for,while, etc.)
Good naming conventions:
Use lowercase with underscores:
user_name,total_scoreBe descriptive:
ageis better thanaAvoid single letters (except for loops:
i,j,k)
# Good variable names
user_name = "Bob"
total_score = 100
is_valid = True
# Bad variable names (but technically valid)
x = "Bob" # Too vague
UsErNaMe = "Bob" # Hard to read
name123 = "Bob" # Numbers are okay, but not meaningful here
# Invalid variable names (will cause errors if uncommented)
# 123name = "Bob" # Can't start with number
# user-name = "Bob" # Hyphens not allowed
# for = "Bob" # Can't use Python keywords
2. Data Types in Python#
Every value in Python has a type that determines what you can do with it.
Main Data Types#
Type |
Description |
Example |
|---|---|---|
str (String) |
Text data |
|
int (Integer) |
Whole numbers |
|
float |
Decimal numbers |
|
bool (Boolean) |
True or False |
|
Strings (Text Data)#
Strings store text and must be wrapped in quotes (single or double).
# Both single and double quotes work
message1 = "Hello, World!"
message2 = 'Hello, World!'
print(message1)
print(message2)
# Use single quotes if your text contains double quotes
quote = 'She said, "Python is awesome!"'
print(quote)
# Or use double quotes if your text contains single quotes
sentence = "It's a beautiful day!"
print(sentence)
Integers (Whole Numbers)#
Integers are whole numbers without decimal points.
score = 100
temperature = -5
year = 2024
print("Score:", score)
print("Temperature:", temperature)
print("Year:", year)
# You can use underscores for readability in large numbers
population = 1_000_000 # Same as 1000000
print("Population:", population)
Floats (Decimal Numbers)#
Floats represent numbers with decimal points.
pi = 3.14159
price = 19.99
height = 5.8
print("Pi:", pi)
print("Price: $", price)
print("Height:", height, "feet")
# Numbers with .0 are also floats
whole_number_float = 10.0
print(type(whole_number_float)) # This is a float, not an int!
Booleans (True/False Values)#
Booleans represent truth values. Must be capitalized!
is_raining = True
is_sunny = False
has_umbrella = True
print("Is it raining?", is_raining)
print("Is it sunny?", is_sunny)
print("Do I have an umbrella?", has_umbrella)
# Booleans are useful for decisions (we'll learn more about this later)
# Note: True and False must be capitalized
# true or false (lowercase) will cause an error
3. Checking Variable Types#
Use the type() function to check what type a variable is.
name = "Alice"
age = 25
height = 5.6
is_student = True
print("Type of name:", type(name))
print("Type of age:", type(age))
print("Type of height:", type(height))
print("Type of is_student:", type(is_student))
⚠️ Watch Out!#
Numbers in quotes are strings, not numbers!
number1 = 42 # This is an integer
number2 = "42" # This is a string!
print("number1:", number1, "Type:", type(number1))
print("number2:", number2, "Type:", type(number2))
# They look the same when printed, but they're different types!
# This matters when you try to do math (you can't do math with strings)
4. Type Conversion#
Sometimes you need to convert between types. Python provides functions for this:
str()- Convert to stringint()- Convert to integerfloat()- Convert to floatbool()- Convert to boolean
Converting to String#
age = 25
age_as_string = str(age)
print("Original age:", age, "Type:", type(age))
print("Age as string:", age_as_string, "Type:", type(age_as_string))
# This is useful when combining text and numbers
message = "I am " + str(age) + " years old."
print(message)
Converting to Integer#
# String to integer
text_number = "100"
actual_number = int(text_number)
print("Text number:", text_number, "Type:", type(text_number))
print("Actual number:", actual_number, "Type:", type(actual_number))
# Now we can do math with it!
result = actual_number + 50
print("100 + 50 =", result)
# Float to integer (removes decimal part)
decimal = 3.99
whole = int(decimal)
print(f"{decimal} as integer: {whole}") # Note: it doesn't round, just truncates!
Converting to Float#
# Integer to float
whole_number = 42
decimal_number = float(whole_number)
print(f"{whole_number} as float: {decimal_number}")
# String to float
price_text = "19.99"
price = float(price_text)
print(f"Price: ${price}")
# Now we can calculate
with_tax = price * 1.08
print(f"Price with tax: ${with_tax:.2f}") # .2f means 2 decimal places
⚠️ Conversion Errors#
Not all conversions work! Be careful:
# This works:
number1 = int("123")
print("Success:", number1)
# Uncomment to see errors:
# number2 = int("Hello") # Error! Can't convert text to number
# number3 = int("12.5") # Error! Can't convert decimal string to int
# Use float() first, then int()
# The correct way for decimal strings:
decimal_string = "12.5"
correct = int(float(decimal_string)) # First to float, then to int
print("Correct conversion:", correct)
5. Variable Operations#
Updating Variables#
Variables can change their values!
score = 10
print("Initial score:", score)
score = 20 # Change the value
print("New score:", score)
score = score + 5 # Use the old value to calculate the new value
print("Updated score:", score)
# Shorthand for updating
score += 10 # Same as: score = score + 10
print("Final score:", score)
Multiple Assignment#
You can assign multiple variables in one line!
# Assign multiple variables at once
x, y, z = 1, 2, 3
print("x:", x)
print("y:", y)
print("z:", z)
# Assign same value to multiple variables
a = b = c = 0
print("a:", a, "b:", b, "c:", c)
# Swap values (Python makes this easy!)
first = 100
second = 200
print("Before swap:", first, second)
first, second = second, first # Swap!
print("After swap:", first, second)
6. None Type#
None represents “no value” or “nothing”. It’s useful for placeholders.
# Variable with no value yet
user_input = None
result = None
print("user_input:", user_input)
print("Type:", type(user_input))
# You can check if a variable is None
if user_input is None:
print("No input received yet!")
📝 Exercises#
Exercise 1: Personal Profile#
Create variables to store your information:
Your name (string)
Your age (integer)
Your height in feet (float)
Whether you like Python (boolean)
Print all of them with labels.
# Your code here
Exercise 2: Favorite Book#
Create variables about your favorite book:
Title (string)
Number of pages (integer)
Your rating out of 5 (float)
Have you finished reading it? (boolean)
Print them all in a readable format.
# Your code here
Exercise 3: Type Conversions#
Create a string variable with the value
"100"Convert it to an integer
Add 50 to it
Convert the result to a string
Print the final result and its type
# Your code here
Exercise 4: Temperature Converter#
Create a variable for temperature in Fahrenheit (e.g., 72.5), then:
Convert it to Celsius using the formula:
(F - 32) * 5/9Print both temperatures with labels
Convert the Celsius temperature to an integer (whole number)
Print the rounded temperature
# Your code here
Exercise 5: Variable Swap#
Create two variables:
first = "Python"second = "Programming"
Swap their values so that first contains “Programming” and second contains “Python”.
Print before and after.
# Your code here
Exercise 6: Shopping Cart#
You’re building a shopping cart. Create variables for:
Item name (string)
Price (float)
Quantity (integer)
In stock? (boolean)
Calculate the total cost (price * quantity) and print a summary.
# Your code here
✅ Self-Check Quiz#
Before moving on, make sure you can answer these:
What is a variable?
What are the four main data types in Python?
How do you check the type of a variable?
What’s the difference between
42and"42"?How do you convert a string to an integer?
Can variable names start with numbers?
What does
Nonerepresent?How do you swap two variables in Python?
🎯 Key Takeaways#
Variables store data that you can use and modify
Data types determine what you can do with values:
strfor textintfor whole numbersfloatfor decimalsboolfor True/False
Use
type()to check a variable’s typeConvert types with
str(),int(),float(),bool()Choose descriptive variable names
Variables can change their values
🚀 Next Steps#
Great work! You now know how to store and work with data in Python.
Next, you’ll learn about operations and conditionals - how to do math and make decisions in your code!
Continue to: 03_basic_operations_and_conditionals.ipynb
💡 Pro Tips#
Use meaningful names:
user_ageis better thanxBe consistent: Stick to one naming style (we use
snake_case)Watch your types: Can’t do math with strings!
Check types when debugging:
print(type(variable))is your friendPractice type conversion: You’ll use it all the time in real programs