W3docs

python

Which of the following is not a valid variable name in Python?

Practice Your Knowledge

Which of the following is not a valid variable name in Python?

Explanation

Understanding Valid Variable Names in Python

The quiz question asks about valid variable names in Python. The correct answer is "2variable". This isn't a valid variable name in Python, and it's important to grasp why this is the case.

In Python, variable names must adhere to certain rules and conventions. Variables are essentially names given to data that we want to manipulate. But, not every string can be used as a variable name.

Python Variable Naming Rules

The reasons why the name "2variable" couldn't pass as a variable name in Python are:

  • A variable name can't start with a number: This is the main reason why "2variable" isn't a valid variable name. Variable names in Python should start with either a letter or an underscore (_). For example, _variable and my_variable are both valid Python variable names.

  • A variable name can only contain alphanumeric characters and underscores (A-z, 0-9, and _ ). Thus, the name "variable_2" is a valid variable name in Python.

  • Variable names are case-sensitive: This means that casevar, Casevar, CASEVAR, and CaSeVaR will each be treated as distinct variables in Python.

Here's an example that demonstrates the contrast between valid and invalid variable names:

my_variable = 10    # valid
_variable = 20      # valid
variable_2 = 30     # valid

2variable = 40      # invalid, causes a syntax error

With these rules in mind, you can easily identify whether a given string can be used as a variable name in Python.

Remember, following these rules not only prevents SyntaxErrors but also adheres to Python's philosophy of making code as clear and readable as possible. This becomes particularly important in large projects or when you're collaborating with other developers.

Want more like this? Take the full Python Basics quiz.

Start Quiz