English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced knowledge in Python

Python reference manual

Python keyword list and examples

This tutorial provides a brief introduction to all the keywords used in Python.

Keywords are reserved words in Python. We cannot use keywords as variable names, function names, or any other identifiers.

This is a list of all keywords in Python programming

Keywords in the Python programming language
Falseawaitelseimportpass
Nonebreakexceptinraise
Trueclassfinallyisreturn
andcontinueforlambdatry
asdeffromnonlocalwhile
assertdelglobalnotwith
asyncelififoryield

The above keywords may change in different versions of Python. Some additional content may be added or some content may be deleted. You can always obtain the list of keywords in the current version by the following method.

>>> import keyword
>>> print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'

Examples of the use of keywords in Python

True, False

True and False are the truth values in Python. They are the results of comparison operations or logical (boolean) operations in Python. For example:

>>> 1 == 1
True
>>> 5 > 3
True
>>> True or False
True
>>> 10 <= 1
False
>>> 3 > 7
False
>>> True and False
False

Here we can see that the first three statements are correct, so the interpreter returns True, and the other three statements return False. True and False in Python are with1It is the same as 0. This can be proven by the following example:

>>> True == 1
True
>>> False == 0
True
>>> True + True
2

None

None is a special constant in Python that represents the absence of a value or an empty value.

It is an object of its own data type NoneType. We cannot create multiple None objects, but we can assign them to variables. These variables are equal.

We must pay special attention that None does not represent False, 0, or any empty list, dictionary, string, and so on. For example:

>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True

Functions that do not return any content will automatically return a None object. Functions that do not encounter a return statement in the program flow also return None. For example:

def a_void_function():
    a = 1
    b = 2
    c = a + b
x = a_void_function()
print(x)

Output results

None

This program, although it performs some operations internally, does not return a value. Therefore, when we print x, we get the automatic (implicit) return of None. Similarly, here is another example:

def improper_return_function(a):
    if (a % 2) == 0:
        return True
x = improper_return_function(3)
print(x)

Output results

None

Although this function has a return statement, it is not always possible to return in every case. The function only returns True when the input is even.

If we pass an odd number to a function, it implicitly returns None.

and, or, not

and, or, not are logical operators in Python. And only when both operands are True, the result will be True. The and truth table is as follows:

 and
ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

or if any of the operands is True, the result will be True. The or truth table is as follows:

or truth table
ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

The not operator is used to reverse the truth value. The not truth table is as follows:

not truth table
Anot A
TrueFalse
FalseTrue

The following are some usage examples

>>> True and False
False
>>> True or False
True
>>> not False
True

as

as is used to create an alias when importing a module. This means giving a different name (user-defined) to the module when importing it.

For example, Python has a standard module called math. Suppose we want to calculate the cosine of pi using an alias. We can do this by the following method:

>>> import math as myAlias
>>> myAlias.cos(myAlias.pi)
-1.0

Here, we import the module myAlias by naming the module math. Now, we can use this name to refer to the module. Using this name, we calculated cos(pi) and got-1.0 and the answer.

assert

assert is used for debugging purposes.

When programming, sometimes we want to understand the internal state or check if our assumptions are correct. assert helps us do this and makes it easier to find errors. assert is followed by a condition.

If the condition is true, nothing will happen. But if the condition is false, an AssertionError will be raised. For example:

>>> a = 4
>>> assert a < 5
>>> assert a > 5
Traceback (most recent call last):
  File '<string>', line 301, in runcode
  File '<interactive input>', line 1, in <module>
AssertionError

To better understand, we can also provide a message that will be printed along with the AssertionError.

>>> a = 4
>>> assert a > 5, "The value of a is too small"
Traceback (most recent call last):
  File '<string>', line 301, in runcode
  File '<interactive input>', line 1, in <module>
AssertionError: The value of a is too small

At this point, we can notice that,

assert condition, message

is equivalent to

if not condition:
    raise AssertionError(message)

async, await

The asyncio library in Python provides the async and await keywords. They are used to write concurrent code in Python. For example,

import asyncio
async def main():
    print('Hello')
    await asyncio.sleep(1)
    print('world')

To run the program, we use

asyncio.run(main())

In the above program, the async keyword specifies that the function will be executed asynchronously.

Here, first print 'Hello'. The await keyword makes the program wait1seconds. Then print 'world'.

break, continue

break and continue are used within for and while loops to change their normal behavior.

break ends the smallest loop it is in, and the control flow will directly flow to the statement below the loop. continue ends the current iteration of the loop, not the entire loop.

This can be illustrated by the following two examples:

for i in range(1,11):
    if i == 5:
        break
    print(i)

Output results

1
2
3
4

Here, the for loop is intended to print from1to10are printed. But if when i equals5 the condition is met, we break out of the loop. Therefore, only the numbers in the range1to4.

for i in range(1,11):
    if i == 5:
        continue
    print(i)

Output results

1
2
3
4
6
7
8
9
10

Here, we use the same program as continue. Therefore, when the condition is met, the iteration will be skipped. But we will not exit the loop. Therefore, the output will be the numbers except5except all other values.

Learn aboutPython break and Continue statementsMore information.

class

class is used to define new user-defined classes in Python.

A class is a collection of related properties and methods that attempt to represent real-world situations. The idea of putting data and functions in a class is crucial to the concept of object-oriented programming (OOP).

Classes can be defined at any location in the program, but it is a good habit to define a single class in a module. Here is an example usage:

class ExampleClass:
    def function1(parameters):
        ...
    def function2(parameters):
        ...

Learn aboutPython objects and classesMore information.

def

def is used to define user-defined functions.

A function is a set of related statements that execute certain specific tasks together. It helps us organize code into manageable blocks and complete some repetitive tasks.

The usage of def is as follows:

def function_name(parameters):
    ...

Learn aboutPython functions'More information.

del

del is used to delete references to objects. Everything is an object in Python. We can use the following method to delete variables, through the reference del

>>> a = b = 5
>>> del a
>>> a
Traceback (most recent call last):
  File '<string>', line 301, in runcode
  File '<interactive input>', line 1, in <module>
NameError: name 'a' is not defined
>>> b
5

Here we can see that the reference to the variable a has been deleted. Therefore, it is no longer defined. However, b still exists.

del is also used to delete items from lists or dictionaries:

>>> a = ['x','y','z']
>>> del a[1]]
>>> a
['x', 'z']

if, else, elif

if, else, elif are used for conditional branching or decision-making.

We use if and elif when we want to test a condition and only execute the block if the condition is true. elif is an abbreviation for else if. else is the block that is executed when the condition is false. This will be clear through the following example:

def if_example(a):
    if a == 1:
        print('One')
    elif a == 2:
        print('Two')
    else:
        print('Something else')
if_example(2)
if_example(4)
if_example(1)

Output results

Two
Something else
One

Here, the function checks the input number (if it is1or2),and output the result. Otherwise, any input will cause the code in the else part to be executed.

Learn aboutPython if and if ... else statementsMore information.

except, raise, try

except, raise, try are used with exceptions in Python.

Exceptions are basically errors that indicate that there has been a problem while executing our program. In Python, several instances of exceptions are IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError, etc. The try...except block is used to catch exceptions in Python.

We can use the raise keyword to explicitly raise an exception. Here is an example:

def reciprocal(num):
    try:
        r = 1/num
    except:
        print('Exception caught')
        return
    return r
print(reciprocal(10))
print(reciprocal(0))

Output results

0.1
Exception caught
None

Here, the function reciprocal() returns the reciprocal of the input number.

Input10The normal output is 0 when1. But when we input 0, it will automatically raise a ZeroDivisionError exception.

This is caught by our try...except block, and we return None. We can also explicitly raise ZeroDivisionError by checking the input and handling it as follows elsewhere:

if num == 0:
    raise ZeroDivisionError('cannot divide')

finally

finally is used together with try...except blocks to close resources or file streams.

Use finally to ensure that the code block inside can be executed even if there are unhandled exceptions. For example:

try:
    Try-block
except exception1:
    Exception1-block
except exception2:
    Exception2-block
else:
    Else-block
finally:
    Finally-block

Here, if there is an exception in the Try-block, it will be handled in the except or else block. However, regardless of the execution order, even if there is an error, we can safely execute Finally-block. This is very useful for cleaning up resources.

Learn aboutexception handling in Python programmingMore information.

for

for is used for looping. Generally, we use for when we know the number of iterations to be performed.

In Python, we can use it with any type of sequence (such as a list or string). This is an example of using 'for' to traverse the names list:

names = ['John', 'Monica', 'Steven', 'Robin']
for i in names:
    print('Hello '+i)

Output results

Hello John
Hello Monica
Hello Steven
Hello Robin

Learn aboutPython for loop'sMore information.

from, import

The 'import' keyword is used to import a module into the current namespace. 'from…import' is used to import a specific attribute or function into the current namespace. For example:

import math

Importing the math module allows us to use the cos() function as math.cos(). However, if we only want to import the cos() function, we can use 'from' to do so

from math import cos

Now we can simply use the function cos() without writing math.cos().

Learn aboutMore information on Python modules and import statements.

global

The 'global' keyword is used to declare a variable as a global variable within a function (outside the function).

If we need to read the value of a global variable, we do not need to define it as global. This is where it is needed.

If you need to modify the value of a global variable inside a function, you must use the declaration 'global'. Otherwise, a local variable with that name will be created.

The following examples will help illustrate this point.

globvar = 10
def read1():
    print(globvar)
def write1():
    global globvar
    globvar = 5
def write2():
    globvar = 15
read1()
write1()
read1()
write2()
read1()

Output results

10
5
5

Here, read1() function is just reading the value of globvar. Therefore, we do not need to declare it as global. However, write1() function is modifying the value, so we need to declare the variable as global.

We can see in the output that the modification has indeed been made (changing10Changed to5()).write2() also tries to modify this value. But we have not declared it as global.

Therefore, we create a new local variable, 'globvar', that is not visible outside this function. Although we have modified this local variable to15, but the global variable remains unchanged. This is clearly visible in our output.

in

The 'in' keyword is used to test if a sequence (such as a list, tuple, or string) contains a value. If the value exists, it returns True; otherwise, it returns False. For example:

>>> a = [1, 2, 3, 4, 5]]
>>> 5 in a
True
>>> 10 in a
False

The secondary use of in is to traverse the sequence within the for loop.

for i in 'hello':
    print(i)

Output results

h
e
l
l
o

is

is is used in Python to test the identity of objects. The == operator is used to test if two variables are equal, while the is operator is used to test if two variables refer to the same object.

It returns True if the objects are the same, otherwise False.

>>> True is True
True
>>> False is False
True
>>> None is None
True

We know that there is only one instance of True, False, and None in Python, so they are the same.

>>> [] == []
True
>>> [] is []
False
>>> {} == {}
True
>>> {} is {}
False

An empty list or dictionary is equal to another empty list or dictionary. However, they are not the same objects because they are located in memory separately. This is because lists and dictionaries are mutable (values can be changed).

>>> '' == ''
True
>>> '' is ''
True
>>> () == ()
True
>>> () is ()
True

Unlike lists and dictionaries, strings and tuples are immutable (values cannot be changed once defined). Therefore, two equal strings or tuples are the same. They refer to the same storage location.

lambda

lambda is used to create anonymous functions (nameless functions). It is an inline function that does not contain a return statement. It consists of an expression that is evaluated and returned. For example:

a = lambda x: x*2
for i in range(1,6):
    print(a(i))

Output results

2
4
6
8
10

Here, we create an inline function using the lambda statement to double the value. We use it to double the values of1to5values in the list are doubled.

Learn aboutPython lamda function'sMore information.

nonlocal

The usage of the nonlocal keyword is very similar to the global keyword. nonlocal is used to declare variables within nested functions (functions within functions) that are not local variables, which means they are located within the outer enclosing function. If you need to modify the value of a nonlocal variable within a nested function, you must use the declaration nonlocal. Otherwise, a local variable with the same name will be created within the nested function. The following example will help illustrate this point.

def outer_function():
    a = 5
    def inner_function():
        nonlocal a
        a = 10
        print("Inner function: ", a)
    inner_function()
    print("Outer function: ", a)
outer_function()

Output results

Inner function:  10
Outer function:  10

Here, the inner_function() is nested within the outer_function.

Variable a is located within the outer_function(). Therefore, if you want to modify a in the inner_function(), you must declare it as nonlocal. Please note that this a is not a global variable.

Therefore, from the output, we can see that the variable has been successfully modified within the nested inner_function(). The result without using the nonlocal keyword is as follows:

def outer_function():
    a = 5
    def inner_function():
        a = 10
        print("Inner function: ", a)
    inner_function()
    print("Outer function: ", a)
outer_function()

Output results

Inner function:  10
Outer function:  5

In this case, we do not declare that the variable a in the nested function is nonlocal. Therefore, a new local variable with the same name will be created, but the nonlocal variable a will not be modified, as shown in our output.

pass

pass is an empty statement in Python. It does nothing when executed and is used as a placeholder.

Suppose we have a feature that has not been implemented yet, but we want to implement it in the future. Simply write,

def function(args):

We will get an IndentationError in the middle of the program. Instead, we use the pass statement to construct an empty body.

def function(args):
    pass

We can also do the same thing with an empty class.

class example:
    pass

return

The return statement is used within a function to exit and return a value.

If we do not explicitly return a value, None will be returned automatically. The following example verifies this.

def func_return():
    a = 10
    return a
def no_return():
    a = 10
print(func_return())
print(no_return())

Output results

10
None

while

while is used for looping in Python.

The statements within the while loop continue to execute until the evaluation result of the while loop condition is False or a break statement is encountered. The following program illustrates this.

i = 5
while(i):
    print(i)
    i = i - 1

Output results

5
4
3
2
1

Please note that 0 is equal to False.

Learn aboutPython while loop'sMore information.

with

The with statement is used to wrap the execution of a code block within the methods defined by the context manager.

The context manager is a class that implements the __enter__ and __exit__ methods. The with statement ensures that the __exit__ method is called at the end of the nested block. This concept is similar to the use of try...finally blocks. Here is an example.

with open('example.txt', 'w') as my_file:
    my_file.write('Hello world!')

This example writes the text Hello world! to the example.txt file. The file object defines the __enter__ and __exit__ methods, so they act as their own context managers.

First __enter__ calls this method, then executes the code in the with block, and finally __exit__ calls this method. __exit__ will be called even if there is an error. It will basically close the file stream.

yield

yield is used in functions like return statements. However, yield returns a generator.

Generators are iterators that generate one item at a time. A large number of values will take up a large amount of memory. Generators are very useful in this case because they generate one value at a time, rather than storing all values in memory. For example,

>>> g = (2**x for x in range(100))

It will create a generator g that generates a2The power, up to the sum generated99The2The power. We can use next() as shown in the following function to generate these numbers.

>>> next(g)
1
>>> next(g)
2
>>> next(g)
4
>>> next(g)
8
>>> next(g)
16

And so on... This type of generator is returned by the statements of the yield function. Here is an example.

def generator():
    for i in range(6):
        yield i*i
g = generator()
for i in g:
    print(i)

Output results

0
1
4
9
16
25

Here, the function generator() returns a generator that generates numbers from 0 to5The square of the number. Print it in the for loop.