A2. Python Keywords and Identifiers


In this tutorial, we will delve into the concepts of keywords and identifiers, where we will explore the reserved words in Python and the naming conventions for variables, functions, and other elements.

Python Keywords

In Python programming, keywords are specific words that have been set aside by the compiler and have a special meaning.

These words cannot be used as variable names, function names, or any other type of identifier. They play a crucial role in defining the syntax and structure of the language.

It is important to note that, except True, False, and None, all keywords are written in lowercase and must be used as written.


A Complete list of Python Keywords

The list might seem a bit overwhelming at first, but I have explained the keywords with examples below

Falseawaitelseimport
Nonebreakexceptin
Trueclassfinallyis
andcontinueforlambda
asdeffromnonlocal
assertdelglobalnot
asyncelififor
passwhileraisereturn
trywithraisereturn
yield

The above keywords may get altered in different versions of Python.

Some extra might get added or some might be removed, but you can always get the complete list by using by typing the following in the prompt, in the command prompt.

>>> import keyword
>>> print(keyword.kwlist)

The Output of the above command for Python version 2.7 :

Python Keywords


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

Description of Keywords in Python with examples


True or False Keyword in Python

  1. True and False are special keywords that represent boolean values, which are used to indicate if a statement is true or false.
  2. Boolean values are often used in conditional statements, such as “if” and “else” statements, to control the flow of a program.

For example:

x = 5
y = 10

if x > y:
    print("x is greater than y")
else:
    print("x is not greater than y")

In the above example, as x is less than y. The output will be “x is not greater than y”.


None Keyword in Python

  1. None is a special constant that represents the absence of a value or a null value.
  2. It is used to indicate that a variable has no value assigned to it.
  3. It is also used as a default value for function arguments that have no specified value.

For example, when defining a function with an optional parameter, you can set the default value to None:

def example_function(x = None):
    if x is None:
        print("x has no value")
    else:
        print("x has value of", x)
  1. We must take special care that None does imply False, 0 or any empty list, dictionary, string etc.
>>> None == 0
False
>>> None == []
False
>>> None == False
False
>>> x = None
>>> y = None
>>> x == y
True
  1. Void functions which do not return anything will return a None object by default. None is also returned by functions in which the program flow does not encounter a return statement. For example:

def void_function():
    // function defination

x = void_function()
print(x)

Output:

None

and, or , not keywords in Python

These keywords “and,” “or,” and “not” are used in Boolean expressions.

  1. The “and” keyword is used to determine whether both expressions on either side of it evaluate to True. If both expressions are True, the overall expression will evaluate to True, otherwise, it will be False.

For example :

x = 5
y = 6
if x<10 and y>5:
print("both the expressions are true")

Truth Table for AND :

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
  1. The “or” keyword is used to determine whether at least one of the expressions on either side of it evaluates to True. If either expression is True, the overall expression will evaluate to True, otherwise, it will be False.

For Example :

x = 5
y = 6
if x<10 or y<5:
print("one of the expressions is true")

Truth table for or :

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
  1. The “not” keyword is used to negate the value of an expression. If the expression is True, the “not” keyword will make it False, and vice versa.

For Example :

x = 5
if not x>10:
print("the expression is False")

Truth Table for NOT :

Anot A
TrueFalse
FalseTrue

These keywords are often used in conditional statements such as “if” and “while” to control the flow of the program and make decisions based on the values of different variables.

‘as’ Keyword in Python

The “as” keyword in Python is used in a variety of contexts to indicate that one thing is being assigned to another. It means giving a different name (user-defined) to a module while importing it.

  1. One of the most common uses of “as” is in an import statement. For example, when importing a module from another package, we can use the “as” keyword to give the module a different name when it is imported into our current script.

This allows us to avoid naming conflicts with modules that have the same name.

For example, the following import statement will import the module ‘math’ and give it the name ’m’:

import math as m

Here we imported the math module by giving it the name m. Now we can refer to the math module with ’m’ and performs actions.

assert keyword in python

The “assert” keyword in Python is used to check if a certain condition is true, and if not, it will raise an exception (AssertionError).

It is used for debugging and testing, as it allows you to check that certain assumptions about your code are being met.

For example :

  1. If you are writing a program that calculates the square root of a number, you might use an assert statement to check that the input is not negative.

  2. If the input is negative, the assert statement will raise an exception and stop the program, preventing it from continuing with invalid input.

The syntax of an assert statement is as follows:

assert condition, message

“condition” –> expression that you want to check.

“message” –> optional string that will be displayed if the condition is false.

For Example :

x = -5
assert x >= 0, "x cannot be negative"

In this case, the condition “x >= 0” is false, so the program will raise an exception with the message “x cannot be negative” and is equivalent to :

if not condition:
    raise AssertionError(message)

It’s important to note that the assert keyword is only used during the development process or when testing the code. It’s not meant to be used in production environments as it can be disabled globally using the python -O option.

async and await keywords in Python

async and await keywords are used in Python to create asynchronous programming, which allows multiple tasks to run concurrently without blocking the execution of the main/current program.

The async keyword is used to define a coroutine function.

Coroutines are special functions that use the async keyword and can be paused and resumed later.

These functions are often used to perform long-running tasks such as network requests, file operations, and other I/O operations.

The await keyword is used inside a coroutine function to call another asynchronous function and pause the execution of the current function until the called function has been completed.

This allows the program to continue running other tasks while it waits for the results of the async function.

async def fetch_data(url):
    response = await requests.get(url)
    return response.json()

In the above example, the fetch_data is an async function that fetches the data from the provided URL.

The await keyword is used to request the URL and the function will pause until the request has been completed.

Async and await allow developers to create non-blocking, high-performance programs that can handle many tasks simultaneously, improving the overall efficiency of the program.

break and continue keywords in Python

  1. Break

The “break” keyword in Python is used to exit or break out of a loop prematurely or when a particular condition is satisfied.

When a “break” statement is encountered within a loop, the loop will immediately exit and the program will continue to the next line of code after the loop. This can be useful for terminating a loop early if a certain condition is met.

for i in range(100,150):
    if i == 105:
        break
    print(i)

The Output :

100
101
102
103
104
  1. Continue

The “continue” keyword in Python is used to skip the current iteration of a loop and move on to the next one.

When a “continue” statement is encountered within a loop, the current iteration of the loop will be skipped and the program will move on to the next iteration. This can be useful for skipping certain iterations of a loop based on a certain condition.

for i in range(100,150):
    if i == 105:
        continue
    print(i)

The Output :

100
101
102
103
104
106
107....
150

Both break and continue can be used to modify the flow of control in a loop and help to optimize the code and are useful in situations where you want to end the loop before it reaches the end or skip some iterations and move to the next one.

Class in python Keywords

Class is used to define objects at the beginning of a script or in a separate module to keep the code organized and easy to understand.

In Python, the keyword “class” is used to create a new

  1. User-defined class,
  2. Allowing developers to model real-world scenarios through the combination of attributes and methods.

This approach, known as object-oriented programming, is a fundamental concept in modern software development.

It is always a good practice to define a single class in a module. For example :

class exampleClass:
    def functionA(parameters1):
        …
    def functionB(parameters2):
        …
    def functionC(parameters3):
        …

def in python keyword

A function, defined using the keyword ‘def’, is a cohesive group of statements designed to accomplish a specific task.

It allows for the organization of code into

  1. Manageable sections and
  2. The ability to perform repetitive actions. An example of the proper usage of ‘def’ is provided below.

For example :

def exampleDef(params):
    ....

del in python Keywords

  1. del is used to delete the reference to an object.
  2. Everything is an object in Python.
  3. We can delete a variable reference using the del keyword

For example:

>>> a = b = elon
>>> del a
>>> a
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'elon' is not defined
>>> b
elon

Python del keyword

As you can see in the above example, the del keyword removes the reference of the ‘a’ from elon. However, ‘b’ still exists.

del can also be used to delete items from a list or a dictionary:

x = ['elon','musk','tesla']
del x[1]
print(x)

if, else, elif in python keyword

If, else, and elif are utilized for making decisions and branching based on certain conditions.

These statements allow us to evaluate a specific condition and execute a specific block of code only if that condition is met. For example,

  1. if we want to check if a variable is greater than a certain value, we can use the “if” statement.
  2. If we want to check for multiple conditions, we can use the “elif” statement, which is short for “else if.”
  3. Lastly, the “else” statement is used when none of the previous conditions are met and the block of code within it will be executed.

For example :


def exampleIf(a):
   if a == 1:
       print('Its number 1')
   elif a == 2:
       print('Its number 2')
   else:
       print('Elon mush would be proud')

exampleIf(2)
exampleIf(4)
exampleIf(1)

Output :

Its number 2
Elon mush would be proud
Its number 1

Python if, else, elif keyword

The above function, check the input number and prints the results,

  1. Its number 2
  2. Elon mush would be proud
  3. Its number 1

based on the condition satisfied, when a number is based to the function.

except, raise, try keyword in Python

In Python, the keywords “except”, “raise”, and “try” are utilized in conjunction with exceptions.

Exceptions, also known as errors, indicate that something has gone wrong during the execution of a program.

Some examples of exceptions in Python include

  1. IOError,
  2. ValueError,
  3. ZeroDivisionError,
  4. ImportError,
  5. NameError, and
  6. TypeError.

To handle these exceptions, try…except blocks are utilized. Additionally, the “raise” keyword can be used to explicitly throw an exception in a program. For example:

def exmaplefun(a,b):
    try:
        x = a / b
    except:
        print('Exception caught')
        return
    return x

print(exmaplefun(10,'bar'))
print(exmaplefun(10,5))

Output :

Exception caught
None
2.0

Python except, raise, try keyword

As you can see in the exmaplefun()` returns the division of two numbers. However, passing two values one as a number and a string raised an exception.

This is caught by our try…except block and we return None. As a result, raised the ZeroDivisionError explicitly by checking the input and handled it elsewhere as follows:

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

finally keyword in python

The finally block is utilized in conjunction with a try-except block to properly close and release any resources, such as file streams, that were opened during the try block.

This ensures that the code within the finally block will always be executed, regardless of whether an exception was handled or not.

For example :

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

If an exception occurs within the Try-block, it will be handled in either the except or else block.

However, regardless of the order in which the code is executed, the Finally-block will always run, even in the event of an error.

This is beneficial for releasing and cleaning up resources.

for keyword in python

The for loop is commonly utilized for iterating through a set number of iterations.

It is commonly used when we have a specific number of repetitions in mind. In Python, loops can be utilized with various types of sequences, such as lists or strings.

As an example, we can use a for loop to iterate through a list of names.

names = ['Elon','Mark','Jeff','Andy']
for i in names:
    print('Yo '+i)

Output :

Yo Elon
Yo Mark
Yo Jeff
Yo Andy

Python for keyword

from, import keyword in python

The keyword “import” is utilized to bring modules into the current workspace.

On the other hand, the syntax “from…import” is used to selectively import specific attributes or functions into the current namespace.

For instance:

import math

will import the math module. now any function within the math module can be imported. As shown below, we import the sin() function from the math module.

from math import sin

Now we can use the function simply as sin(), no need to write math.sin().

global keyword in python

Declaring a variable as global within a function indicates that it is accessible outside of the function.

It is not necessary to declare a global variable as such when only reading its value, as this is understood.

However, if a global variable needs to be modified within a function, it must be declared as global to prevent the creation of a local variable with the same name.

For Example :

x = 5 # global variable

def my_function():
    global x # declare x as a global variable
    x = x + 2 # modify the value of x
    print(x) # prints 7

my_function()
print(x) # also prints 7

In this example, we first define a global variable x with the value of 5. Inside the function my_function(), we use the global keyword to indicate that we want to modify the global variable x.

We then add 2 to the value of x and print it, which results in 7.

When we print the value of x outside of the function, it also returns 7, showing that the global variable has been modified.

Output:

7
7

in Keyword in python

The “in” operator is utilized to check if a specific value is present within a sequence, such as a list, tuple, or string.

It returns a Boolean value of True if the value is found, or False if it is not.

Another use-case of in is to traverse through a sequence in for a loop.


a = [4535,12,43,56,5]
5 in a # True
10 in a #False

# OR

for i in 'hello':
    print(i)

is keyword in Python

In Python, the is operator is utilized to determine object identity, while the == operator is used to evaluate equality between variables. Specifically, it checks if two variables refer to the same object, and returns a Boolean value of True if they are identical and False if they are not.

>>> 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 identical.

Two empty lists or dictionaries may appear to be the same, but they are not identical objects as they exist in separate memory locations. This is because lists and dictionaries are mutable, meaning their values can be altered.

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

String and tuple are immutable, meaning their values cannot be altered once they are defined.

As a result, two identical strings or tuples refer to the same memory location.

This is different from lists and dictionaries, which are mutable and can be modified.

lambda keyword in python

Lambda functions, also known as anonymous functions, are a convenient way to create small, inline functions without the need for a named function.

These functions are defined using the keyword “lambda” and typically consist of a single expression that is evaluated and returned.

For Example:

# A lambda function to square a number
square = lambda x: x**2

# Using the lambda function
print(square(5)) # 25
print(square(10)) # 100

In this example, we use the lambda keyword to create a function called “square” that takes a single argument “x” and returns the value of “x” squared.

We can then use this function just like any other function, by calling it and passing in the desired argument.


# A lambda function to find the sum of two numbers
add = lambda x, y : x + y

# Using the lambda function
print(add(5,10)) # 15
print(add(2,8)) # 10

In this example, we use the lambda keyword to create a function called “add” that takes two arguments “x” and “y” and returns the sum of these two arguments.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

nonlocal keyword in python

The nonlocal keyword serves a similar purpose to the global keyword.

It is used to indicate that a variable within a nested function (a function within another function) is not exclusive to that function and can be accessed and modified by the outer enclosing function.

Without using nonlocal, a new local variable with the same name would be created within the nested function. The following example illustrates this concept.

def outer_function():
    x = 10  # x is a non-local variable
    def inner_function():
        nonlocal x  # Declaring x as non-local
        x += 5  # Modifying the value of x
        print("Inside inner_function, x =", x)
    inner_function()
    print("Inside outer_function, x =", x)

outer_function()
# Output:
# Inside inner_function, x = 15
# Inside outer_function, x = 15

In this example, the variable “x” is defined in the outer function and is accessed and modified within the nested inner function.

By using the nonlocal keyword, we can modify the value of the non-local variable x inside the inner function, and the changes made to x are reflected when we print the value of x inside the outer function.

Without the nonlocal keyword, a new local variable x would be created within the inner function and the value of x inside the outer function would not change.

pass keyword in python

The “pass” statement in Python serves as a placeholder, allowing for the creation of an empty function or loop without causing an IndentationError.

It is used when a specific action or implementation is yet to be determined, but the structure of the program requires it to be present.

For example, if a function is yet to be fully implemented, placing “pass” within its body allows for the program to continue running without error.

def function(args):


def function(args):
    pass

Similarly, it can be applied to class as well.

class example:
    pass

return keyword in python

The return statement serves as a means to exit a function and provide a value as output.

In the absence of an explicit return statement, the function will automatically return None, as demonstrated in the following example.

def func_return():
    a = 'elon'
    return a

def no_return():
    a = 'musk'

print(func_return()) # return elon
print(no_return()) # no return 


while Keyword in python

In Python, the while loop is utilized for the repeated execution of a set of statements.

The code within the loop will continue to execute until the specified condition evaluates to false or a break statement is encountered. The following program serves as an example of this concept.

i = 5
while(i < 10):
    print(i)
    i = i + 1

Output

5
6
7
8
9
10

10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

with keyword in python

The “with” keyword in Python is used in conjunction with the “as” keyword to create a context in which a specific action or set of actions will take place.

It is commonly used when working with external resources, such as files or databases, to ensure that these resources are properly closed and released when they are no longer needed.

For example, when working with a file, the “with” keyword can be used to open the file, perform some actions on the file, and then automatically close the file when the block of code within the “with” statement is finished executing.

This eliminates the need for the programmer to manually close the file, which can help reduce the risk of errors.

In addition to its use with external resources, the “with” keyword can also be used to manage other types of context, such as threading or database transactions.

A simple example for With keyword in python :

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

The with keyword in Python is used in combination with a context manager, which is an object that defines the methods enter() and exit() to set up and tear down a specific environment for a block of code.

The with statement is used to wrap the execution of the block of code, ensuring that the context manager’s exit() method is called at the end of the block, even if an exception is raised.

In the example, the open() function returns a file object, which is used as the context manager.

The with statement sets up the environment for the block of code by calling the file object’s enter() method, which opens the file.

Once the block of code is executed, the exit() method is called, which closes the file, even if an exception is raised.

It is important to note that using with statement saves us from the hassle of closing the file after reading it.

yield keyword in python

The yield keyword in Python is used in the body of a function, similar to the return keyword.

However, unlike return, when a function with a yield statement is called, it doesn’t return a value, instead, it returns a generator object. Generator is an iterator that generates one item at a time.

This generator can be used to iterate through a series of values using the next() function.

For example, let’s say we want to create a function that generates the Fibonacci sequence. We can be implemented with yield keyword :

def fibonacci(n):
    a, b = 0, 1
    for i in range(n):
        yield a
        a, b = b, a + b

# create a generator object
fib = fibonacci(10)

# iterate through the generator
for i in fib:
    print(i)

The above code will output the first 10 numbers of the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Note that each time when the yield statement is executed, the state of the function is saved, and the function can be resumed later on when next() is called again.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co