Python Variables: Storing Data for Your Programs
Introduction
In the last lesson, we printed text to the screen. But what if you want to store information to use later? That's where variables come in.
Think of a variable as a labeled box. You put a value inside the box, and you use the label to find it whenever you need it.
How to Create a Variable
In Python, you create a variable by giving it a name and using the equals sign = to assign a value to it.
user_name = "Alice"user_age = 25print(user_name)print(user_age)
In this example, user_name stores the text "Alice", and user_age stores the number 25.
Why Use Variables?
Variables allow us to reuse data easily. Instead of typing the same value over and over, we just reference the variable name.
score = 10print("Your score is:")print(score)# Later in the code, we update the scorescore = 20print("Your new score is:")print(score)
This makes your code easier to update and read. If the value changes, you only need to update the variable.
Rules for Naming Variables
Python is picky about variable names. Follow these important rules:
- Use letters, numbers, and underscores, like
player_1. - Don't start with a number. For example,
1_playeris invalid. - No spaces are allowed. Use
my_variableinstead ofmy variable. - Variable names are case-sensitive, so
Scoreandscoreare different variables.
Conclusion
Variables are one of the most important building blocks in Python. They help you store and reuse data throughout your program.
Once you understand variables, writing more useful and interactive programs becomes much easier.
