KAHIBARO Bookshelves
Discord Login Register

3.2. Creating variables

In Python, creating a variable is as simple as writing a name, an equals sign, and a value.

This chapter focuses on:

  • How to write a valid variable name
  • How to assign values to variables
  • Re-assigning (changing) variables
  • Naming style and good habits for beginners

(What a variable is and what types of values exist are covered in other sections of this chapter.)

Basic variable assignment

The simplest way to create a variable is:

name = "Alice"
age = 20
pi = 3.14
is_student = True

This is called assignment. The general pattern is:

$$\text{variable_name} = \text{value}$$

Python reads this as “store this value in this variable.”

  • name is the variable
  • = is the assignment operator
  • "Alice" is the value stored in name

You do not have to say the type (int, str, etc.) when creating a variable in Python. Python figures it out from the value.

Variables are created when you assign

In Python, a variable comes into existence the first time you assign a value to it.

x = 10      # x is created here
message = "Hello"  # message is created here

If you try to use a variable before giving it a value, you’ll get an error:

print(score)   # ERROR: score is not defined
score = 100

So always assign a value before using a variable.

Re-assigning variables

You can change the value stored in a variable by assigning to it again.

counter = 0
print(counter)   # 0
counter = 5
print(counter)   # 5
counter = counter + 1
print(counter)   # 6
  • The name stays the same (counter)
  • The value can change over time

Python variables are like labels you can move to point at different values.

Variable names: rules

Python has some strict rules about what counts as a valid variable name.

A variable name:

  • Must start with a letter (a–z, A–Z) or an underscore (_)
  • Can contain letters, digits, and underscores
  • Cannot start with a digit
  • Cannot contain spaces
  • Cannot use special characters like -, !, @, #, ., etc.
  • Cannot be a Python keyword (like if, for, while, etc.)

Valid variable names

x
age
user_name
total3
_pi_value

Invalid variable names (and why)

3dogs      # starts with a digit
user-name  # contains a hyphen
first name # contains a space
for        # 'for' is a Python keyword

If you use an invalid name, Python will raise a syntax error when you run the code.

Python keywords (names you cannot use)

Some words are reserved by Python and have special meaning in the language. You cannot use them as variable names.

Examples (not full list):

False, True, None,
and, or, not,
if, elif, else,
for, while,
break, continue,
def, return,
class, try, except

Trying to use one of these as a variable name will cause an error:

if = 10       # ERROR: invalid syntax

You don’t need to memorize all of them right away; you’ll recognize most as you learn the language. Just remember: if Python complains about a name, it might be a keyword.

Naming style: `snake_case`

Python has a common style for writing variable names called snake_case:

  • All lowercase letters
  • Words separated by underscores (_)

Examples:

user_name
total_price
max_speed
number_of_items

While Python allows userName or UserName, the recommended style for variables is:

  • snake_case for variable names: user_age, account_balance
  • Avoid starting variable names with _ unless you have a specific reason (more advanced use)

Following this style makes your code easier for others (and your future self) to read.

Good vs bad variable names

Python doesn’t care what your variable is called, as long as it follows the rules. But you should care, because clear names make your code easier to understand.

Clear, descriptive names

age = 25
temperature_celsius = 18.5
user_first_name = "Maria"
items_in_cart = 4

These names describe what the values represent.

Unclear names

a = 25
x1 = 18.5
s = "Maria"
n = 4

These follow the rules but do not tell you what they mean.

As a beginner, prefer longer, descriptive names over short, cryptic ones.

Case sensitivity

Python variable names are case-sensitive:

age = 20
Age = 30
AGE = 40
print(age)  # 20
print(Age)  # 30
print(AGE)  # 40

These are three different variables.

To avoid confusion:

  • Pick one style and stick to it (usually all lowercase with underscores)
  • Don’t rely on capitalization to distinguish similar variables unless you really mean different things

Assigning multiple variables

Sometimes you can assign multiple variables in a single line.

Multiple assignment (same value)

x = y = z = 0
print(x, y, z)   # 0 0 0

All three variables get the value 0.

Multiple assignment (different values)

x, y, z = 1, 2, 3
print(x)   # 1
print(y)   # 2
print(z)   # 3

Python matches them position by position:

  • x gets 1
  • y gets 2
  • z gets 3

The number of variables on the left must match the number of values on the right, or Python will show an error.

Updating a variable using its current value

You will often create a variable, then update it based on its current value.

count = 0
count = count + 1   # add 1
count = count + 2   # add 2
print(count)        # 3

This pattern is extremely common in programming.

Python also provides shorter forms (like count += 1), which you will see later in the course when learning about operations.

Temporary variables

Sometimes you create a variable just to hold a value “in between” steps.

a = 5
b = 10
temp = a   # save a's value
a = b      # now a becomes 10
b = temp   # b becomes the old a (5)
print(a, b)  # 10 5

Here, temp is a temporary variable used to help swap values. Even if a variable is only used for a short time, giving it a clear name can make your code easier to follow.

Practical examples

Example 1: Simple profile

first_name = "Lena"
last_name = "Kim"
age = 19
is_student = True

Each variable name clearly describes the kind of information it stores.

Example 2: Shopping cart

item_name = "Book"
item_price = 12.99
item_quantity = 3
total_cost = item_price * item_quantity

Notice how the variable names express their meaning directly.

Summary

  • Create a variable using name = value
  • Variables are created when you first assign to them
  • You can re-assign a variable to change its value
  • Variable names must follow Python’s rules (no spaces, no starting with a digit, no keywords)
  • Use descriptive, snake_case names for readability
  • Python is case-sensitive (age and Age are different)
  • You can assign multiple variables in one line when needed

In the next sections, you’ll explore the different kinds of values (data types) you can store in these variables and how to work with them.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms