Python - Variable Names

 

Python - Variable Names


In Python, a variable is a named location in memory that stores a value. A variable name is used to reference the value stored in the variable.

There are a few rules for naming variables in Python:

  1. Variable names can only contain letters, numbers, and underscores. They cannot begin with a number.
  2. Variable names are case-sensitive, so myVariable and myvariable are different variables.
  3. Python reserves a set of words that cannot be used as variable names, known as keywords. Some examples of keywords include for, while, def, and class.
  4. Variable names should be descriptive and meaningful, but they should also be concise. It is a good idea to use short, all-lowercase names for most variables, and to use underscores to separate words (e.g., my_variable).

Here are some examples of valid and invalid variable names in Python:

# Valid variable names

my_variable = 10

x = 5

student_name = "Alice"

# Invalid variable names

2nd_variable = 15 # cannot begin with a number

my-variable = 20 # cannot contain hyphens

for = 10 # cannot use a keyword as a variable name


Multi Words Variable Names in python

 

In Python, it is common to use multi-word names for variables. These names are known as "snake case," because the underscores look like the eyes and mouth of a snake.

For example:

student_name = "Alice"

student_age = 20

student_gpa = 3.5

 

Snake case is the most common naming convention for variables in Python, and it is used by the Python style guide known as PEP 8.

Another naming convention that is sometimes used in Python is "camel case," which is similar to snake case but without the underscores. In camel case, Each word, except the first letter of each word is capitalized, and the words are combined into a single name.

For example:

studentName = "Alice"

studentAge = 20

studentGpa = 3.5

Both snake case and camel case are widely used in Python, and the choice of which one to use is generally a matter of personal preference. It is important to be consistent in your use of variable names within a project, however.

Pascal Case

Pascal case in Python is a naming convention where each word in a multi-word name is capitalized, with no spaces or underscores

MyVariableName = "John"

 

Comments