Variables and Naming Rules
Variables and Naming Rules
Variables are used to store data in memory so your program can use it later. They make code dynamic, reusable, and easier to understand.
What Is a Variable?
A variable is a name that points to a value.
name = "Alex"
age = 25
is_student = True
Here:
namestores textagestores a numberis_studentstores a boolean value
Why Variables Matter
Without variables, programs would only contain fixed values. Variables allow programs to react to user input, perform calculations, and manage changing data.
Creating Variables
Use the equals sign = to assign a value.
city = "Nairobi"
score = 100
Updating Variables
Variables can change during program execution.
score = 100
score = 150
print(score)
Output:
150
Naming Rules
Variable names must follow these rules:
- Use letters, numbers, and underscores
- Must start with a letter or underscore
- Cannot contain spaces
- Cannot use Python keywords
- Names are case-sensitive
Valid examples:
user_name = "Sam"
age2 = 30
_total = 50
Invalid examples:
2age = 30
user name = "Sam"
class = "Python"
Best Practices
Choose clear names that describe the data.
Good:
student_name = "Maya"
price = 19.99
is_logged_in = False
Bad:
x = "Maya"
a = 19.99
flag = False
Code Along
name = "Jordan"
country = "Kenya"
age = 21
print(name)
print(country)
print(age)
Mini Challenge
Create variables for:
- Your name
n- Your age - Your favorite language
- Whether you like coding
Print all values.
Real World Use Case
E-commerce apps use variables to store product names, prices, stock counts, and customer information while the program runs.
Quiz
- What symbol is used to assign a value?
- Can variable names contain spaces?
- Are
ageandAgethe same variable? - Which is better:
xortotal_price?
Assignment
Create a program with five variables about yourself and print them in a friendly format.
Summary
You learned what variables are, how to create and update them, and how to name them professionally for clean Python code.