😺Keywords and Identifiers

In Python, keywords and identifiers are used to define and manipulate variables, functions, and other programming elements.

Python Keywords

Keywords in Python are predefined reserved words that have specific meanings and purposes. These words cannot be used as variable or function names because they have a special meaning in the Python language.

Python Keywords List

False
await
else
import
pass

None

break

except

in

raise

True

class

finally

is

return

and

continue

for

lambda

try

as

def

from

nonlocal

while

assert

del

global

not

with

async

elif

if

or

yield

It is important to remember that these keywords have a specific meaning in Python and cannot be used as variable or function names.

Python Identifiers

In Python, an identifier is a name given to a variable, function, class, module or other object. An identifier can be made up of letters, digits, and underscores (_), and must begin with either a letter or an underscore. Identifiers are case-sensitive, which means that my_variable and My_Variable are different identifiers.

Here are some examples of valid identifiers in Python:

x
my_var
My_Var
myVar
my_var_1
_my_var

And here are some examples of invalid identifiers:

2myvar (starts with a digit)
my-var (contains a hyphen)
my var (contains a space)
my@var (contains a special character)

It's important to choose meaningful and descriptive names for your identifiers, to make your code more readable and understandable.

Rules for Naming an Identifier

  1. The first character of an identifier must be a letter or an underscore (_).

  2. The rest of the identifier can contain letters, digits, and underscores.

  3. Identifiers are case-sensitive, which means that my_variable and My_Variable are different identifiers.

  4. Python keywords cannot be used as identifiers.

  5. Identifiers should be descriptive and meaningful, to make your code more readable and understandable.

  6. Identifiers cannot start with a digit.

Following these rules will help ensure that your identifiers are valid and easy to understand.

Some Valid and Invalid Identifiers in Python

Valid Identifiers:

  • my_variable

  • MY_VARIABLE

  • _my_variable

  • my_variable_1

  • myVariable

  • var_1

Invalid Identifiers:

  • 1_variable (starts with a digit)

  • my-variable (contains a dash, which is not allowed)

  • import (a Python keyword)

  • break (a Python keyword)

  • while (a Python keyword)

  • my variable (contains a space, which is not allowed)

It's important to follow the rules for naming identifiers in Python to avoid errors in your code.

Last updated