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:
- name: This variable stores the value
"John"
(which is text). - age: This variable stores the value
25
(which is a number).
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:
- Use only letters, numbers, or underscores (_).
# Correct: my_name = "Python" # Incorrect: my-name = "Error" # Hyphens are not allowed
# Correct: name1 = "John" # Incorrect: 1name = "Error" # Cannot start with a number
# Correct: first_name = "Alice" # Incorrect: first name = "Error" # Spaces are not allowed
print
, if
, or
while
).# Correct: my_variable = "Allowed" # Incorrect: print = "Error" # `print` is a Python keyword
Name
and name
are
different variables.# These are two different variables: Name = "John" name = "Doe" print(Name) # Output: John print(name) # Output: Doe
Types of Data You Can Store in Variables
Variables can store different types of data:
- Text (String): Use quotes for text, like
"Hello"
or'Python'
. - Numbers: Whole numbers like
10
or decimal numbers like3.14
. - True/False (Boolean): Can store either
True
orFalse
.
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!