Understanding Variables in Python

A variable is like a container that holds information. Think of it as a labeled box where you can store something (like numbers or text) and use it later.

What is a Variable?

In Python, a variable is used to store data. For example, if you want to remember someone’s name or age, you can save it in a variable.

How to Create a Variable

Creating a variable in Python is very simple. You just need to write a name for the variable, use the = sign, and assign it a value. Here’s the format:

variable_name = value
    

Example:

name = "John"
age = 25
    

Explanation:

Using Variables

Once you create a variable, you can use it in your program. Example:

name = "John"
age = 25

print(name)
print(age)
    

Output:

John
25
    

Rules for Naming Variables

When naming variables in Python, follow these rules:

Types of Data You Can Store in Variables

Variables can store different types of data:

Example:

name = "Alice"
age = 30
is_student = True
    

Why Use Variables?

Variables make your programs easier to write and read. Instead of repeating values, you can store them in variables and use them whenever needed. This makes your code clean, flexible, and easy to update.

Practice: Try It Yourself!

Write and run the following Python code:

# Storing data in variables
name = "Emma"
hobby = "painting"

# Using variables
print(name)
print(hobby)
    

Expected Output:

Emma
painting
    

Congratulations!

You’ve learned what variables are and how to use them. Keep practicing to get comfortable with storing and using data in your programs!