Python Keywords and Identifiers

Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Learn via video course

Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
By Rahul Janghu
Free
star4.90
Enrolled: 1000
Python Certification Course: Master the essentials
Python Certification Course: Master the essentials
Rahul Janghu
Free
4.90
icon_usercirclecheck-01Enrolled: 1000
Start Learning

Overview

Keywords in Python are unique reserved words that cannot use a keyword as a variable, function, or other identifiers. These special words are used to define the syntax and structure of the Python language. On the other hand, an identifier is a name used to identify entities like class, functions, variables, etc.

Scope of article

  • In this topic, we are going to know about keywords in Python and how to identify them.
  • Then, we will discuss different types of keywords available in Python.
  • We will also take a brief look at Identifiers with some examples.

Introduction

If you have decided to finally learn one of the industry's easiest and sought-after programming languages, then let’s check out two fundamental features of python programming which truly makes it coder friendly: Keywords and Identifiers.

What are Python Keywords?

what are python keywords

Keywords in python are these unique sets of predefined words reserved to perform a specific function or purpose. These keywords are part of the python syntax. Most of them have a purpose very similar to their actual meaning in English. This makes python easy to understand and code.

Like built-in functions, keywords are also built-in. But, they cannot alter their purpose or naming convention like other built-in functions: ZeroDivisionError, NameError, etc.

According to version 3.8 in python, there are 35 keywords that it supports.

Built – in Functions:

Python has several functions readily available for use once you install python on your PC. These functions are called built-in functions.

Example of Python Keywords

How to Identify Keywords in Python?

Keywords keep being added and removed depending on the version of python installed on your system. For example: print and exec were part of version 2.7X of python, but are now built-in functions* and hence removed from the keywords list. On the other hand, async and await were only recently added to the list, i.e. version 3.7+ of python.

There are numerous ways to identify these keywords. Some of them are:

1. Syntax Highlighting in IDEs:

Most of the good python friendly IDEs usually highlight keywords while writing codes. Hence easily identifiable. E.g. Spyder, PyCharm, Vim, Visual Studio Code, etc.

2. Python REPL Commands:

Python comes installed with its interpreter, the interactive Read-Eval-Print Loop (REPL) environment. Here you can obtain the keywords with the following command:

3. Python Libraries:

You can use libraries like kwlist, to get a list of keywords supported by the current version of python you are running the code on.

Click Here, to learn more about python libraries.

4. iskeyword() function:

This function is part of the keyword package and is used to check if a term is a python keyword or not.

List of All Python Keywords

Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield

Types of Keywords in Python

1. Value Keywords

These python keywords are used to denote values. These values are single values that can be used multiple times and about the same object or variable. These keywords are the only keywords that begin with a capital letter. Let's see the different types of value keywords possessed by python:

Python KeywordUsage
TrueUsed for assigning the value to a variable or represents the result of a boolean expression evaluating to true
FalseUsed for assigning the value to a variable or represents the result of a boolean expression evaluating to false
NoneRepresents null, nil, none, undef, or undefined values in python

Example:

2. Operator Keywords

Many operators are used as symbols in other languages; on the contrary, python uses keywords for defining these operators. Their function is similar to their literal meaning, making coding in python lucid to understand. Let’s take a look at these keywords:

Python KeywordMath Operator
andAND, Intersection(^)
orOR, Union(v)
notNOT, Negation (¬)
inCONTAINS, (∈)
isChecking Identity

Example:

3. Control Flow Keywords

These keywords help us perform conditional logic and execute code given certain conditions. They are commonly used in forming a pipeline on how the code should perform based on decision-making conditions and hence are essential in python. Let's see how these control flow keywords work:

Python KeywordSyntaxFunction
ifif <expression>: <body of code>Executes the body of code if the expression evaluates to True
elifelif <expression>:<body of code>Similar to ‘if’, ‘elif’ is used to execute the body of code if the expression evaluates to True. You can use ‘elif’ only after ‘if’ and multiple times. The function literally translates to ‘ else – if ‘.
elseelse:<body of code>Executes the body of code when all of the above expressions gets evaluated to False

Example:

Output:

4. Iteration Keywords

In python programming, these keywords indicate the type of looping initiated. Synonymous with python’s ease of usage, the function of these keywords are literally the same as what we type. Let's see the various types of iteration keywords:

Python KeywordSyntaxFunction
forfor <element> in <condition>:<body of code>Loops the element according to the condition and executes the body of code until the element is unable to fit in the condition.
whilewhile <condition>:<body of code>Executes body of code until condition is evaluated to False
breakfor <element> in <condition1> <condition2>:breakIt exits from the loop if condition2 evaluates to True . Also works with while loop
continuefor <element> in <condition1> <condition2>:continueContinues the looping if condition2 evaluates to True. Also works with while loop

Example:

Output:

5. Structural Keywords

We use various keywords in python to define the structure of certain pieces of code. These keywords are very often used to make code modular and understandable. Let’s take a look at these functions and their uses:

Python KeywordSyntaxFunction
defdef <name of function>(<parameters>):<body of code>Defines the beginning of a function in python
classclass <name of class>(<extends>):<body of code>Defines the beginning of a class in python
withwith <context manager> as <variable>: <body of code>We use with to run codes within the context manager functions. Like: reading and writing of files
asimport <module> as <alias>It is used to provide an alias to modules, functions, etc.
passdef function()Used with functions classes, if-else statements, etc. to indicate ‘no – operation’ taking place
lambdalambda <arguments>:<function>It is used to create a nameless function. It is an inline function that does not contain a return statement.

6. Return Keywords

These keywords help us give out results of functions. They are essential keywords that help us determine with what value must exist the function. Let’s take a look at its functionalities.

Python KeywordSyntaxFunction
returndef <function>() <statement>Returns the statement when this function is called
yield>>> def <function>(): … yield <statementl> … yield <statement2>>>> test = <function() >>> next(test)<statement1> >>> next(test)<statement2>Through yield we can have numerous return statements which will perform sequentially using the in built next() function in python

Check out this article to learn more about Return in Python.

7. Import Keywords

There are many useful packages and libraries in python that can be installed and used to form your code that is not available in the installed version of python. These libraries can be used in the codebase using the following keywords:

Python KeywordSyntaxFunction
importimport <module>Imports all functions of the specified modules to be used in the python file’s execution.
fromfrom <module> import <function>The from keyword is used together with import to import specific functions from a module.
asimport <module> as <alias>Import module with a alias

8. Exception Handling Keywords

The following keywords are used to raise and catch exceptions in python. Let’s take a look at these keywords and their functions:

Python KeywordSyntaxFunction
trytry: <statements>Initiates try block where the statement is executed if there is no exception
excepttry:<statement1>except <exception>: <statement2>Specifies the type of exception that should occur and what subsequent statements should execute
raiseraise <exception>This statement can be used to raise a particular exception to any block of code
finallytry: <statements>finally:<statements>Finally defines a piece of code that should run no matter what
assertassert <expression>An assert statement will result in performing no operation if the expression is executed as truthful, and it will raise an AssertionError if the expression is executed as False.

9. Asynchronous Programming Keywords

In python, to perform asynchronous programming, we used keywords defining these functions: async and await. Let’s take a look

Python KeywordSyntaxFunction
asyncasync def <function>(<params>):<statements>Indicates that the following function needs to run asynchronously
awaitawait <some async function call> OR <var> = await <some async function call>It is used in asynchronous functions to specify a point in the function where control is given back to the event loop for other functions to run

10. Variable Handling Keywords

These keywords are used to do manipulations on python variables. Let's take a look at their functionality and syntax.

Python KeywordSyntaxFunction
deldel <variable>The keyword is used to reset the variable to an unused one
globalglobal <variable>The keyword specifies that the variable is pulled from global scope
nonlocalnonlocal <variable>Similar to global, this keyword specifies that the variable has been pulled from parent scope

What are Python Identifiers?

An identifier is a name given to entities like variables, class, functions, etc. It helps to differentiate one entity from another and understand the flow of entities in code.

Rules for Identifiers in Python

  1. Combination of alphabets in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _
  2. Digits cannot be used as the starting of an identifier.
  3. Keywords cannot be used as identifiers
  4. Special symbols !, @, #, $, % etc. cannot be used in an identifier
  5. There is no limit on the length of an identifier

Example of Python Identifiers

example of python identifiers

Conclusion

Learning Outcomes:

  • What are keywords used in python and various methods to identify them
  • Different categories of keywords based on purpose and use cases with examples
  • Difference between keywords and identifiers
  • Rules used for forming identifiers with examples of valid and invalid identifiers

See Also: