Review of keywords Python: their purpose and use in programming

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Keywords in Python are reserved words that have special meanings in the programming language and cannot be used as identifiers (for example, names of variables, functions, or classes). Understanding Python keywords is crucial for effective programming.

How to get a list of Python keywords

In Python, the keyword module provides access to a list of all keywords:

import keyword
print(keyword.kwlist) # Displays a list of all keywords
print(len(keyword.kwlist))  # Number of keywords

Full list of Python keywords with examples

Logical operators

and - Logical "and". Returns True if both operands are true.

if age >= 18 and has_license:
    print("Can drive a car")

or is the logical operator "or". Returns True if at least one operand is true.

if day == "Saturday" or day == "Sunday":
    print("Day off")

not is the logical operator "not". Inverts the value of a boolean expression.

if not is_empty:
    print("The list is not empty")

Conditional operators

if is a conditional statement for checking conditions.

if temperature > 30:
print("Hot")

elif is short for "else if". Used to check additional conditions.

if score = 90:
print("Excellent")
elif score= 70:
print("Good")

else - Is executed if all the previous conditions are false.

if score >= 60:
print("Offset")
else:
print("Non-offset")

Cycles and flow control

for - A loop for iterating through the sequence.

for item in [1, 2, 3, 4, 5]:
    print(item)

while - A loop with a precondition.

while count < 10:
    print(count)
    count += 1

break - Interrupts the execution of the loop.

for i in range(10):
    if i == 5:
        break
    print(i)

continue - Proceeds to the next iteration of the loop.

for i in range(10):
    if i % 2 == 0:
        continue
    print(i) # Outputs only odd numbers

Defining functions and classes

def - Defines the function.

def greet(name):
    return f"Hello, {name}!"

class - Defines the class.

class Person:
    def __init__(self, name):
        self.name = name

return - Returns the value from the function.

def add(a, b):
    return a + b

Working with modules

import - Imports the module.

import math
print(math.pi)

from - Imports certain attributes from the module.

from math import sqrt, pi

as - Creates an alias when importing.

import numpy as np
import pandas as pd

Exception handling

try - Starts the exception handling block.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero!")

except - Defines the exception handling block.

try:
    file = open("test.txt")
except FileNotFoundError:
    print("File not found")

finally is a block of code that is always executed.

try:
    file = open("test.txt")
except FileNotFoundError:
    print("File not found")
finally:
print("Resource cleanup")

raise - Generates an exception.

def divide(a, b):
    if b == 0:
raise ValueError("Division by zero is unacceptable")
return a/b

Asynchronous programming

async - Declares an asynchronous function (routine).

async def fetch_data():
    await asyncio.sleep(1)
return "Data received"

await - Waits for the asynchronous operation to complete.

async def main():
    result = await fetch_data()
    print(result)

Scope of variables

global - Declares a variable as global.

counter = 0

def increment():
    global counter
    counter += 1

nonlocal - Declares a variable as extra-local.

def outer():
    x = 10
    def inner():
        nonlocal x
        x = 20
    inner()
print(x) # Outputs 20

Special values

True - The boolean value is true.

is_active = True

False - The boolean value is false.

is_complete = False

None - Represents the absence of a value.

def process_data():
return None # returns nothing

Validation operators

in - Checks the presence of a value in the sequence.

if "apple" in fruits:
    print("The apple is in the list")

is - Verifies the identity of objects.

if variable is None:
    print("The variable is not defined")

Additional keywords

lambda - Creates an anonymous function.

square = lambda x: x ** 2
numbers = [1, 2, 3, 4, 5]
squared = list(map(square, numbers))

pass is a placeholder for incomplete structures.

def future_function():
pass # To be implemented later

del - Deletes an object or element.

del my_list[0]  # Deletes the first element
del variable # Deletes a variable

with is a context manager for working with resources.

with open("file.txt", "r") as file:
    content = file.read()

yield - Used in generators.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

assert - Checking the condition for debugging.

def divide(a, b):
    assert b != 0, "Division by zero"
    return a / b

Tips for learning Python keywords

  1. Practice regularly - the more often you use keywords, the better you remember their meaning
  2. Learn with examples - each keyword is better understood through practical examples
  3. Use the IDE - modern editors highlight keywords, helping you remember them
  4. Read someone else's code - analyzing the finished code will help you understand the context of using keywords

Understanding and using Python keywords correctly is the foundation for writing high-quality and readable code. Regular practice will help you become fluent in all the features of the Python programming language.

 
 
Declares a routine (asynchronous function).  Defines the class. Continues executing the next iteration of the loop. Defines the function. Removes an object or item from the collection. Short for "else if". It is used in the construction of a conditional operator. A branch of a conditional statement that is executed if the condition in the preceding `if` or `elif` statement is false. Defines the exception handling block in the 'try' construction...except`./span> Defines a block of code that is always executed after the end of the `try' block...except`./span> Declares a variable as global inside a function./span> Creates an anonymous function./span> Declares a variable as extra-local inside a function. The logical operator "not" inverts the value of the logical expression. The logical operator "or" returns `True` if at least one of the operands is true./span> t: 68px;"> /span> Defines a loop with a precondition.
Keyword Description
 and The logical "and".
 as is used to create an alias when importing modules. For example, `import module_name as alias'.
 assert

Checking the condition. If the condition is false, an `AssertionError` exception is thrown.

 async
 await Is waiting for the asynchronous operation to complete.
 break Exit the loop.
 class
 continue
 def
 del
 elif
 else
 except
 False The boolean value is false.
 finallnbsp;finally
 for is used for sequence iteration.
 fron> from is used to import certain attributes from a module. For example, `from module_name import attribute_name`.
 global
 if Conditional operator.
 import Imports the module.
 ipan> in The occurrence verification operator. Checks whether the value is present in the sequence.
px;">  is The comparison operator. Checks whether two objects are the same.
 lambda
 None Represents the absence of meaning or nothing
 nonlocal
 noan> not
px;">  or
 pass

does not do anything. It is used as a filler for unfinished structures.

 rais> raise

Raises an exception.

 return

Returns the value from the function.

 True 

The boolean value is true.

 try The beginning of the exception handling block.
 whil> while
 with Announces the context manager.
 yield is used in generators to return a value without ter

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base