Sitemap
BeginnerPython

Beginner Level Python Articles

13 min readOct 29, 2023

--

In Computer Programming, Keywords are reserved words or reserved identifiers that cannot be used as an identifier, such as the name of a variable, function, or label — they are “reserved from use”. Such words cannot have any user defined meaning.

The terms Keywords and Reserved Words need not coincide but in most modern programming languages keywords are a subset of reserved words, as this makes parsing easier, since keywords cannot be confused with identifiers. In some languages, like C or Python, reserved words and keywords coincide, while in other languages, like Java, all keywords are reserved words, but some reserved words are not keywords, being reserved for future use.

Keywords consist of built-in operators, statements and functions that are available with the programming language.

This post discusses keywords available in Python till Python 3.13.

Python differentiates between “Hard” Keywords and Soft Keywords.

  • “Hard” Keywords are treated as keywords in every context and cannot be used as identifiers
  • Soft Keywords (introduced in Python 3.10) are only reserved under specific contexts. These identifiers can syntactically act as keywords in certain contexts, but this distinction is done at the parser level, not when tokenizing. As soft keywords, their use in the grammar is possible while still preserving compatibility with existing code that uses these names as identifier names

→ Keywords in Python [Screenshot from https://docs.python.org/3/reference/lexical_analysis.html#keywords]

Keywords

Datatype Keywords

None

The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own : NoneType.

  • By default, a standalone return statement yields a NoneType object.
  • A function call which doesnt return anything is essentially a NoneType object
Press enter or click to view image in full size

None does have a Boolean value of False.

See GitHub file for examples:

https://github.com/AdityaGarg1995/BeginnerPython/blob/main/Keywords%20and%20Identifiers/Keywords.ipynb

True, False

True and False represent Boolean values in Python.

Boolean variables can be initialised with either of these keywords as values. Python’s built-in bool() function can be used to evaluate Boolean values (called Truthy and Falsy values) of non-boolean values, variables, and expressions.

Furthermore, output of statements comparing 2 variables also yields True or False, which can be printed using print() function on console.

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/python_booleans.asp.

Please visit my GitHub file for Boolean operations:

https://github.com/AdityaGarg1995/BeginnerPython/blob/main/Boolean%20Operations/Boolean%20Entities%20and%20Functions.ipynb

Operator Keywords

and, or, not, is, in

The not keyword is a unary logical operator that negates the value of its operand: the result is False if the operand’s Boolean value is True and vice versa. It can also be used in conjunction with is and in operators as discussed later.

The keywords and and or are binary logical operators evaluating to Boolean values: and evaluates to True if both operands are True while or evaluates to True if any one of the operands are true, they otherwise evaluate to False.

The is keywords is an identity operator evaluating to True if its operands are equal otherwise evaluates as False.

  • The is not keyword cluster acts as the opposite of is operator with the expression evaluating to False if the operands are equal

The in keyword is a membership operator: if the specified value/sequence exists in the specified object, it evaluates to True.

  • The not in keyword cluster acts as the opposite of in operator with the expression evaluating to False if the value/sequence exists in the specified object

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/python_operators.asp

as

as keyword is used to create aliases.

It is primarily used with from…import statements and aliasing exception names when raising exceptions → these uses have been explained later in this post.

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/ref_keyword_as.asp

Scope Defining Keywords

global, nonlocal

The global keyword is used to declare a variable’s scope as global irrespective of where that variable is defined. Names listed in a global statement must not be used in the same code block textually preceding that global statement. Names listed in a global statement must not be defined as formal parameters, or as targets in with statements or except clauses, or in a for target list, class definition, function definition, import statement, or variable annotation.

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function. The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding global identifiers. This is important because the default behaviour for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).

→ global keyword [Source: Screenshot from https://www.w3schools.com/python/ref_keyword_global.asp]

→ nonlocal keyword [Source: Screenshot from https://www.w3schools.com/python/ref_keyword_nonlocal.asp]

Please visit this w3schools page for more details and hands-on practice:

Class and Function Keywords

class and def

class keyword is used to indicate a class definition → Python’s reserved keywords cannot be used to name a class.

def keyword is used to indicate a function → Python’s reserved keywords cannot be used to name a function.

These keywords are independent of each other : a class is not required to have functions and a function is not required to be in a class definition. In practice, however, classes are usually defined with one or more functions inside.

lambda

lambda keyword is used to create small anonymous functions. A lambda function can take any number of arguments, but can only have one expression.

→ [Screenshots from https://www.w3schools.com/python/python_lambda.asp]

Statement Keywords

These keywords act as parts of statements or complete statements in themselves.

return

return statement is used to return the output of a function or statement — if no operand is specified, it simply returns a NoneType result i.e. None value.

  1. If the return statement is without any expression, then the special value None is returned.
  2. The statements after the return statement are not executed.

Being a statement in itself, return doesn’t have a Boolean value.

del

del statement is used to delete the operand(s) succeeding the del keyword. It can take one or more operands i.e. a single variable or a sequence and then delete them. If the operand doesn’t exist, a NameError is raised {this error is raised by any operation, not just limited to del, for all variables that don’t exist}.

Deletion is recursively defined very similar to the way assignment is defined. Rather than spelling it out in full details, here are some hints.

  • Deletion of a target list recursively deletes each target, from left to right.
  • Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

del operation on existing variables → NameError is raised by the print() statement that tries to print the values of now deleted variables

del on non-existing variables → NameError raised by del statement itself

import

import statement is used to import modules into the current Python program. In case when only a subset of a module is needed, from...import statement can be used in conjunction with from keyword (discussed later).

→ Simple import of a complete module [Source: Screenshot from https://www.w3schools.com/python/python_modules.asp]

→ Import a module and assign an alias using as keyword [Source: Screenshot from https://www.w3schools.com/python/python_modules.asp]

from

Get Aditya Garg’s stories in your inbox

Join Medium for free to get updates from this writer.

from statement has following major uses:

  1. from…import statement : in case only a subset of a library is required to be imported, those modules can be imported using a from…import statement.
  2. Exception chaining with raise statement : in case of a raise statement (discussed later), from keyword is used to chain exceptions.

→ Usage of from…import statement [Screenshot from https://www.w3schools.com/python/python_modules.asp]

→ Usage of from keyword for exception chaining [Source: Screenshots from https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement

assert

assert statement evaluates if a condition evaluates to True. It can be used to fetch the Boolean value of a condition, and optionally raise an error if the condition evaluates to False.

The error raised by assert statement is called AssertionError.

assert condition evaluates to True → nothing happens

assert condition evaluates to False → Specified error is raised

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/ref_keyword_assert.asp#:~:text=Definition%20and%20Usage,False%2C%20check%20the%20example%20below.

yield

A yield statement is semantically equivalent to a yield expression.

Yield expressions and statements are only used when defining a generator function, and are only used in the body of the generator function. Using yield in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

Control Flow Statement Keywords

if, elif, else

if and elif indicate statements of corresponding names that evaluate a condition’s Boolean value and accordingly pass on control to succeeding set of statements.

In case where the if statement and the succeeding elif statement(s) evaluate to false, the control passes to else statement (if any) which always evaluates the succeeding set of statements.

else statement are also used in case of try…except blocks and succeeding loop code blocks.

→ Usage of else keyword in loops; break and continue have been discussed later [Source: docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops]

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/python_conditions.asp

Documentation:

try, except, finally

The try block tests a block of code for errors. If there are no errors, the try block is executed and control skips over except statements and passes on to succeeding statements.

The except block handles the error. Multiple except statements can be written after a try block to handle different types of errors.

The else block lets you execute code when there is no error.
{This is in relation to try…except statements}

The finally block executes code regardless of the result of the try- and except blocks.

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/python_try_except.asp#gsc.tab=0

raise

raise keyword is used to raise an error. It can be used in if…elif..else statements, try…except statements and match…case statements to raise the error that has occured (if any).

Please visit this w3schools page for more details and hands-on practice: https://www.w3schools.com/python/ref_keyword_raise.asp

→ Usage of raise keyword along with as and from (contextually) [Screenshot from https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement]

Loop Statement Keywords and In-Loop Keywords

  • Loop Statement Keywords: for, while
  • In-Loop Keywords: continue, break, else
  • else can also succeed a loop statement

for, while

for and while keywords represent the start of a loop.

for loop iterates over a sequence which can be a collection or a string, and evaluates a set of statements as long as iteration over that sequence is possible.

while loop executes a set of statements as long as the condition specified for the loop is true {i.e. the condition should evaluate to True}.

Please visit this w3schools page for more details and hands-on practice:

Documentation:

continue, break

continue and break statements can occur syntactically nested in a for or while loop including try..except blocks, but not nested in a function or class definition within that loop.

break terminates the nearest enclosing loop, skipping the optional else clause if the loop has one.

  • If a for loop is terminated by break, the loop control target keeps its current value.
  • When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

Documentation:

pass

A pass statement simply does nothing.

It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.

It can also be used in case of if…elif…else statements wherein one or more of those statements are required to not actually do anything.

Being a statement in itself, pass doesn’t have a Boolean value.

Soft Keywords

match, case

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks.
{ This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it’s more similar to pattern matching in languages like Rust or Haskell. }

Only the first pattern that matches gets executed and it can also extract components (sequence elements or object attributes) from the value into variables.

“Variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.

Screenshots from https://docs.python.org/3/tutorial/controlflow.html#tut-match

1. Cases with single value being matched

2. Single case with multiple values being checked

3. Otherwise regular example but with raise keyword used to raise the occurred exception

Reserved classes of identifiers

Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:

*

Importing all packages in module using from module import *.

_

In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard.

Separately, the interactive interpreter makes the result of the last evaluation available in the variable _. (It is stored in the builtins module, alongside built-in functions like print.)

Elsewhere, _ is a regular identifier. It is often used to name “special” items, but it is not special to Python itself.

__*__

System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

__*

Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names).

--

--