CodingNic

Python Foundations

Variables and Naming Rules

Python Foundations 18 min read

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.

python
name = "Alex"
age = 25
is_student = True

Here:

  • name stores text
  • age stores a number
  • is_student stores 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.

python
city = "Nairobi"
score = 100

Updating Variables

Variables can change during program execution.

python
score = 100
score = 150
print(score)

Output:

text
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:

python
user_name = "Sam"
age2 = 30
_total = 50

Invalid examples:

python
2age = 30
user name = "Sam"
class = "Python"

Best Practices

Choose clear names that describe the data.

Good:

python
student_name = "Maya"
price = 19.99
is_logged_in = False

Bad:

python
x = "Maya"
a = 19.99
flag = False

Code Along

python
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

  1. What symbol is used to assign a value?
  2. Can variable names contain spaces?
  3. Are age and Age the same variable?
  4. Which is better: x or total_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.