How Declares Variable Names In Python?

Share Your Love

Variable Names:

Like other programming languages, in python the variable declaration having certain rules and regulations.

The variables are very short name like x and y or descriptive names like student_age, car_price etc.

So, some common rules follow while declaring the variables in python.

Rule-1:

A variable name must start with a letter( a-z, A-Z) or underscore character ( _ ).

Rule-2:

A variable name can’t start with a number.

Rule-3:

A variable name can only be a alpha numeric characters and underscores  (A-z, 0-9, and _ ).

Rule-4:

Generally variables are case-sensitive like age, Age and AGE these three variables are different.

Because each variables play different role in python syntax.

Examples Of Python Legal Variable Names:

myvar = "Rahul"
my_var = "Rahul"
_my_var = "Rahul"
myVar = "Rahul"
MYVAR = "Rahul"
myvar2 = "Rahul"


print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

The output will be,

Rahul
Rahul
Rahul
Rahul
Rahul
Rahul

Some Illegal variable declaration are:

myvar = "Rahul"
my-var = "Rahul"
my var = "Rahul"

This program produces an error in this code,

Traceback (most recent call last):
  File "/usr/lib/python3.7/py_compile.py", line 143, in compile
    _optimize=optimize)
  File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./prog.py", line 1
    2myvar = "John"
         ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/py_compile.py", line 147, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 1
    2myvar = "John"
         ^
SyntaxError: invalid syntax

In Python variable names are case-sensitive.

Python Multi Words Variable Names:

If variable name is small it easy to read but big it difficult to read.

There are several techniques to read the variable very easily. Like Camel case, Pascal Case, Snake Case.

Camel Case:

Each word, except the first, starts with a capital letter:

myVariableName = "Rahul"

Pascal Case:

Each word starts with a capital letter:

MyVariableName = "Rahul"

Snake Case:

Each word is separated by an underscore character:

my_variable_name = "John"

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter