Python Variables Naming Rules

In this tutorial, we would learn about Python variables – their use and naming rules.

What are the variables?

Variables are considered to be identifiers having a physical memory location, which are used to hold values temporarily during the program execution.

Assigning values to variables in Python

Python interpreter can determine on itself that what type of data is stored in the variable, so before assigning a value, variables do not need to be declared.

We use the equal to sign ‘=’ to assign values to a variable. It assigns the values of the right side operand to the left side operand i.e. the variable.

Naming rules for variables in Python

Firstly, the variables should have a meaningful name. Also, the length of the variable name should be maintained and the names should be consistent.

Example

'stud_id' is better than 'sid' or 'id_of_a_student'

Points to remember

  • Since Python is a case sensitive language so are the variable names used in it.

Example

'name' and 'Name' will be treated as different variables in Python.

Similarly,

'class' cannot be considered as a valid variable because it is a reserved keyword while 'Class' is a valid variable.
  • The variable names must always begin with either a letter or an underscore and not digits.

Example

Valid variable names-

_name, id

Invalid variable names-

9name, 888, 6_id
  • The variable can contain only alphanumeric characters (A-Z, a-z, 0-9) and underscore (_) and no other special characters.

Example

Valid variable names-

roll_no

Invalid variable names-

$roll#no
  • The variable names must not contain any space.

Example

Valid variable names-

stud_id, stud_name1

Invalid variable names-

stud id, 1stud name
  • The variable names should not be reserved words.

Example

Valid variable names-

Max, Min, List

Invalid variable names-

max, min, list
(This is because max, min and list are reserved words in Python)

How to check if a string is a valid identifier or not in Python

Leave a Reply

Your email address will not be published. Required fields are marked *