Variables in Python
Introduction to Variables in Python
Now that you know how to print text and use comments in Python, it's time to dive into one of the most important concepts in programming: variables.
![]() |
What is Variables in Python |
Variables are like boxes where you can store information, and they allow you to manage data in your programs. Understanding variables is key to working efficiently in Python.
1. What is a Variable?
A variable is like a container that holds a value. You can think of it like a labeled box where you put something you need later. Variables help you organize data, making it possible to store, retrieve, and change information as your program runs.
age = 25
name = "Alice"
Explanation: Here, age
is a variable that stores the number 25
, and name
is a variable that stores the text "Alice"
.
2. Rules for Naming Variables
- Start with a letter or an underscore.
- Use letters, numbers, and underscores only.
- No spaces are allowed.
- Variable names are case-sensitive.
Examples of valid and invalid variable names:
- Valid:
my_age
,first_name
,_counter
- Invalid:
1st_number
(cannot start with a number),my age
(spaces are not allowed)
3. Assigning Values to Variables
In Python, you assign a value to a variable using the =
sign.
height = 180
city = "New Delhi"
Explanation: Here, height
is assigned the value 180
, and city
is assigned the value "New Delhi"
.
4. Changing Variable Values
score = 0
print("Initial score:", score)
score = score + 10
print("Updated score:", score)
Explanation: Variables allow you to track and update data dynamically as your program runs.
5. Using Variables in Expressions
width = 5
height = 10
area = width * height
print("The area is:", area)
Explanation: Variables can be used in calculations to make your code reusable and dynamic.
6. Combining Variables with Text
name = "Alice"
age = 25
print("Hello, my name is " + name + " and I am " + str(age) + " years old.")
Explanation: Combining variables with text allows you to create user-friendly messages and outputs.
7. Variable Types and Dynamic Typing
x = 10
x = "Hello"
Explanation: Python supports dynamic typing, allowing variables to change types during program execution.
8. Good Practices for Using Variables
- Use meaningful names:
age
instead ofa
. - Be consistent: Stick to one naming convention, like
snake_case
. - Avoid using Python keywords as variable names.
Example:
# Poor naming
x = 5
y = 10
z = x * y
# Improved naming
width = 5
height = 10
area = width * height
Conclusion: Understanding Variables
Variables are fundamental building blocks in Python programming. They allow you to store, update, and reuse information easily. Practice using variables to become comfortable with this essential concept, and you’ll be ready for more advanced programming challenges.
![]() |
What is Variables in Python |