Python Keywords and Identifiers#
You will learn about keywords (reserved words in Python) and identifiers (names given to variables, functions, etc.).
Keywords#
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier.
In Python, keywords are case sensitive.
All the keywords except True
, False
and None
are in lowercase and they must be written as they are. The list of all the keywords is given below.
Keywords in Python
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
You can see this list any time by typing help keywords
to the Python interpreter.
Trying to create a variable with the same name as any reserved word results in an error:
>>>for = 6
File "<ipython-input-1-50b154750974>", line 1
for = 6 # It will give error becasue "for" is keyword and we cannot use as a variable name.
^
SyntaxError: invalid syntax
for = 6 # It will give error becasue "for" is keyword and we cannot use as a variable name.
File "<ipython-input-1-473137c03db7>", line 1
for = 6 # It will give error becasue "for" is keyword and we cannot use as a variable name.
^
SyntaxError: invalid syntax
For = 6 # "for" is keyword but "For" is not keyword so we can use it as variable name
For
6
Identifiers#
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.
Rules for writing identifiers#
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore
_
. Names likemyClass
,var_1
andprint_this_to_screen
, all are valid example.An identifier cannot start with a digit.
1variable
is invalid, butvariable1
is perfectly fine.Keywords cannot be used as identifiers
>>>global = 3
File "<ipython-input-2-43186c7d3555>", line 1
global = 3 # because "global" is a keyword
^
SyntaxError: invalid syntax
global = 3 # because "global" is a keyword
File "<ipython-input-3-3e859d37287a>", line 1
global = 3 # because "global" is a keyword
^
SyntaxError: invalid syntax
We cannot use special symbols like !, @, #, $, % , etc. in our identifier.
>>>m@ = 3
File "<ipython-input-3-4d4a0e714c73>", line 1
m@ = 3
^
SyntaxError: invalid syntax
m@ = 3
File "<ipython-input-4-0f73a35e8ce2>", line 1
m@ = 3
^
SyntaxError: invalid syntax
NOTE
Python is a case-sensitive language. This means,
Variable
andvariable
are not the same.Always give the identifiers a name that makes sense. While
c = 10
is a valid name, writingcount = 10
would make more sense, and it would be easier to figure out what it represents when you look at your code after a long gap.Multiple words can be separated using an underscore, like
this_is_a_long_variable
.
this_is_a_long_variable = 6+3
this_is_a_long_variable
9
add_6_and_3 = 6+3
add_6_and_3
9