What is a Variable?
Imagine you have a magical box where you can store things. You give it a name, put something inside, and later, you can open it to retrieve the item. That’s exactly what a variable does in Python!
A variable is like a labeled container that holds data.
Example:
name = "Alice"
age = 25
height = 5.6
is_happy = True
Here, we stored:
- A string (
"Alice") inname - An integer (
25) inage - A float (
5.6) inheight - A boolean (
True) inis_happy
You can imagine them as:
name → Alice
age → 25
height → 5.6
is_happy → True
Rules for Naming Variables
Python has some rules (and some best practices) for naming variables. You don’t want to upset Python—it will throw errors at you!
Valid Variable Names:
- Can contain letters, numbers, and underscores (
_) - Must start with a letter or an underscore (
_), not a number - Case-sensitive (
ageandAgeare different!) - Should be descriptive (avoid
x = 10, usescore = 10instead!)
my_variable = 42 # Valid
_name = "Bob" # Valid
user2 = "Charlie" # Valid
Invalid Variable Names:
- Cannot start with a number
- Cannot use spaces
- Cannot use special characters like
@,#,!,-, etc. - Cannot be a Python keyword (
if,else,for, etc.)
2name = "Oops" # ERROR
user-name = "Nope" # ERROR
def = 100 # ERROR (def is a reserved keyword)
Best Practices for Naming Variables
Since Python won’t physically stop you from writing ugly variable names, here are some golden rules to keep your code clean:
Use Snake Case (snake_case)
first_name = "John" # Easy to read
user_age = 30 # Descriptive
Avoid Camel Case (camelCase) in Python (It’s more common in JavaScript)
firstName = "John" # Not Pythonic (but still works)
Use Meaningful Names
Bad example:
x = 10 # What is x?
y = 20 # What is y?
Good example:
apple_price = 10 # Now we know what this value represents!
total_students = 20 # Clear meaning
Changing Variable Values
Variables are not permanent—you can change their values anytime!
mood = "Happy"
print(mood) # Output: Happy
mood = "Sleepy"
print(mood) # Output: Sleepy
You can also swap variables easily:
a, b = 5, 10
print(a, b) # Output: 5 10
a, b = b, a # Swap values!
print(a, b) # Output: 10 5
Conclusion
- Variables store data like numbers, text, and more.
- Follow naming rules to avoid Python’s angry red error messages.
- Use snake_case for clean and readable code.
- Choose meaningful variable names so future-you understands what’s going on!
Now go forth and create awesome variables in Python!
0 Comments:
Post a Comment