What are Variables?
Chapter 1: What are Variables?
Welcome to the second lesson of our Python and FastAPI course! In the previous lesson, we set up our development environment and wrote our first Python program. Now, it's time to understand one of the most fundamental concepts in programming: variables. Think of variables as labeled boxes where you can store information. Without variables, your program would have no memory and couldn't process any data.
What is a Variable?
A variable is a named location in your computer's memory that stores a value. You can think of it like a sticky note with a name on it, attached to a box. The box holds some data, and you use the name to find and use that data later. In Python, you create a variable by giving it a name and assigning a value using the equals sign (=).
Why Do We Need Variables?
Variables are essential because they allow us to:
- Store data – Keep information like numbers, text, or results of calculations.
- Reuse data – Use the same value multiple times without rewriting it.
- Update data – Change the value stored in a variable as our program runs.
- Make code readable – Use meaningful names instead of raw values.
For example, if you're building a Task API later, you'll use variables to store task titles, descriptions, and completion status. Without variables, you couldn't manage any dynamic data.
How to Create and Use Variables
Creating a variable in Python is straightforward. You choose a name, use the assignment operator (=), and provide a value. Python automatically determines the type of data you're storing.
Step-by-Step Example
Let's create a simple program that stores a user's name and age, then prints a greeting.
# Step 1: Create variables
user_name = "Ahmed"
user_age = 25
# Step 2: Use the variables
print("Hello, " + user_name + "!")
print("You are " + str(user_age) + " years old.")
Explanation:
user_name = "Ahmed"– Creates a variable nameduser_nameand stores the text "Ahmed" in it.user_age = 25– Creates a variable nameduser_ageand stores the number 25.print("Hello, " + user_name + "!")– Combines the text with the variable's value and prints it.str(user_age)– Converts the number to text so it can be joined with other strings.
When you run this code, you'll see:
Hello, Ahmed!
You are 25 years old.
Variable Naming Rules
Python has specific rules for naming variables. Follow these to avoid errors:
- Names can contain letters, numbers, and underscores (
_). - Names cannot start with a number.
- Names are case-sensitive (
ageandAgeare different). - You cannot use Python reserved words like
if,for, orwhileas variable names.
Good examples: my_name, task_count, total_price
Bad examples: 2fast (starts with a number), my-name (contains a hyphen), class (reserved word)
Common Mistakes and How to Avoid Them
Beginners often make these mistakes. Let's look at them so you can avoid them:
If you try to use a variable before assigning a value, Python raises a NameError.
print(my_variable) # Error: name 'my_variable' is not defined
Solution: Always assign a value before using the variable.
Python doesn't automatically convert between types in all situations. For example, you can't add a string and a number directly.
age = 25
print("I am " + age + " years old.") # Error: can only concatenate str (not "int") to str
Solution: Convert the number to a string using str().
Python is case-sensitive and exact. UserName and username are different variables.
user_name = "Sara"
print(user_name) # Works fine
print(User_name) # Error: name 'User_name' is not defined
Solution: Use consistent naming (e.g., always lowercase with underscores) and double-check spelling.
Practical Example: Building a Simple User Profile
Let's combine everything we've learned into a practical example. We'll create variables for a user profile and display the information.
# User profile variables
first_name = "Mona"
last_name = "Ali"
age = 30
email = "mona.ali@example.com"
is_active = True
# Display profile
print("User Profile")
print("------------")
print("Name: " + first_name + " " + last_name)
print("Age: " + str(age))
print("Email: " + email)
print("Active: " + str(is_active))
Output:
User Profile
------------
Name: Mona Ali
Age: 30
Email: mona.ali@example.com
Active: True
Notice how we used different data types: strings for text, an integer for age, and a boolean (True/False) for the active status. Python handles all these types automatically.
Practice Task
Now it's your turn! Create a Python script that does the following:
- Create a variable called
task_titleand assign it the value "Learn Python". - Create a variable called
task_priorityand assign it the number 1. - Create a variable called
is_completedand assign it the valueFalse. - Print a message that says: "Task: [task_title], Priority: [task_priority], Completed: [is_completed]"
Hint: Remember to convert numbers and booleans to strings when combining them with text using the + operator.
Once you've written the code, run it and check the output. If you get an error, review the common mistakes section above. This simple exercise will prepare you for the next lesson where we'll dive deeper into data types and how to work with them effectively.
Congratulations! You now understand what variables are and how to use them in Python. In the next chapter, we'll explore Python's built-in data types in more detail, including numbers, strings, and booleans, and learn how to convert between them.
Loading ratings...