Variable Naming Rules in Python


TL ; DR:

  • In Python, we use the snake_case convention to name our variables. It implies separating different words with an underscore (_), like this:

    company_name = "Apple"
    
    founding_year = 1976
    
    is_Unicorn = True
    
    number_of_employees = 137000
    





Full lesson:

Variable names must consist ONLY of letters, numbers and underscores and they must start with a letter or underscore.

Bad variable names:

$name
18spam
var.15

If you try to create a variable with any of these names, Python will throw a SyntaxError: invalid syntax.


Naming conventions: camelCase and snake_case

Sometimes a variable name might consist of multiple words, for example if you want to store the first name of a person. You might be tempted to separate those names by whitespaces, like this:

first name = "Kate"

This code will also throw a SyntaxError.

When you name your variables, you want to use one of these two conventions:

snake_case = separate different words with an underscore (_), like this:

first_name = "Jane"
last_name = "Doe"

camelCase = separate different words with capital letters, like this:

firstName = "Jane"
lastName = "Doe"

It's important to be consistent with the casing technique you use. Do not combine both of them in the same code, like this:

first_name = "Jane"
lastName = "Doe"

Case sensitive:

Variable names are case sensitive:

name = "Kate"
Name = "Andy"
NAME = "George"

print(name, Name, NAME) # Output: Kate Andy George

Although Python allow us to do this, it's always confusing and a bad coding practice to differentiate variable names just by case!


Mnemonic Variable Names

Since we programmers are given a choice in how we choose our variable names, there is a bit of "best practice".

Sometimes we want them short like x and y, but sometimes we want them descriptive, especially if they are important.

Here is a great example:

a = 25
b = 13
c = a * b
print(c)

compared to:

hours = 25
rate = 13
pay = hours * rate
print(pay)

Python understands and is happy with both of these pieces of code. But it's clearly which version makes your reader happier.


Assignment
Follow the Coding Tutorial and let's name some variables well!


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore the rules and best practices for naming variables in Python. Proper variable naming is crucial for writing clear and maintainable code. It helps in understanding the code better and makes collaboration with other developers easier. Variable naming conventions are particularly useful in scenarios where code readability and maintainability are important, such as in large projects or when working in teams.

Understanding the Basics

Before diving into the specifics of variable naming conventions, let's understand the fundamental rules:

Here are some examples of valid and invalid variable names:

# Valid variable names
company_name = "Apple"
founding_year = 1976
is_unicorn = True
number_of_employees = 137000

# Invalid variable names
$name = "John"  # SyntaxError
18spam = "Hello"  # SyntaxError
var.15 = 100  # SyntaxError

Main Concepts

There are two main naming conventions in Python: snake_case and camelCase.

snake_case involves separating words with underscores:

first_name = "Jane"
last_name = "Doe"

camelCase involves capitalizing the first letter of each word except the first one:

firstName = "Jane"
lastName = "Doe"

It's important to be consistent with the naming convention you choose. Mixing both conventions in the same code can lead to confusion:

first_name = "Jane"
lastName = "Doe"  # Not recommended

Examples and Use Cases

Let's look at some examples to understand the application of these conventions:

# Using snake_case
user_name = "Alice"
user_age = 30
is_active_user = True

# Using camelCase
userName = "Alice"
userAge = 30
isActiveUser = True

In real-world scenarios, using descriptive variable names can make your code more readable and maintainable:

# Less descriptive
a = 25
b = 13
c = a * b
print(c)

# More descriptive
hours_worked = 25
hourly_rate = 13
total_pay = hours_worked * hourly_rate
print(total_pay)

Common Pitfalls and Best Practices

Here are some common mistakes to avoid and best practices to follow:

Advanced Techniques

As you become more comfortable with basic naming conventions, you can explore advanced techniques such as:

Code Implementation

Here is a well-commented code snippet demonstrating proper variable naming:

# Define user information using snake_case
user_name = "Alice"
user_age = 30
is_active_user = True

# Calculate total pay using descriptive variable names
hours_worked = 25
hourly_rate = 13
total_pay = hours_worked * hourly_rate

# Print the results
print(f"User: {user_name}, Age: {user_age}, Active: {is_active_user}")
print(f"Total Pay: ${total_pay}")

Debugging and Testing

When debugging code related to variable naming, consider the following tips:

Writing tests for functions or scripts can help ensure correctness:

import unittest

class TestVariableNaming(unittest.TestCase):
    def test_total_pay(self):
        hours_worked = 25
        hourly_rate = 13
        total_pay = hours_worked * hourly_rate
        self.assertEqual(total_pay, 325)

if __name__ == '__main__':
    unittest.main()

Thinking and Problem-Solving Tips

When approaching problems related to variable naming, consider the following strategies:

Conclusion

In this lesson, we covered the importance of proper variable naming in Python. We discussed the basic rules, naming conventions, common pitfalls, and best practices. By following these guidelines, you can write clear, efficient, and maintainable code. Remember to practice and explore further applications to master these concepts.

Additional Resources

For further reading and practice, consider the following resources: