Python Keywords List questions and answers

Python Keywords List questions and answers
Python Keywords List questions and answers

Python Keywords List Databases MySQL

    Python Keywords Lists A python keyword is a reserved keyword. It can be used in all python programs. python keywords can not use python variables. because it is already defined python library.

    Python Keywords List is the reserved word in Python. We cannot use a keyword as a variable name, function name, or any other identifier.

    Python keywords are unique words reserved with defined meanings and functions that we can only apply for those functions. You'll never need to import any keyword into your program because they're permanently present.

    Python's built-in methods and classes are not the same as the keywords. Built-in methods and classes are constantly present; however, they are not as limited in their application as keywords.


    Python keywords list databases Postgres

    Every scripting language has designated keywords, with particular definitions and usage guidelines. Python is no exception. The fundamental constituent elements of any Python program are Python keywords.

    This course will give you a basic overview of all Python keywords list and a detailed discussion of some important keywords that are frequently used in python language. 


    Here's a list of all keywords in Python Programming

    False

    await

    else

    import

    pass

    None

    break

    except

    in

    raise

    True

    class

    finally

    is

    return

    and

    continue

    for

    lambda

    try

    as

    def

    from

    nonlocal

    while

    assert

    del

    global

    not

    with

    async

    Elif

    if

    or

    yield


    The above keywords may get altered in different versions of Python. Some extra might get added or some might be removed. You can always get the list of keywords in your current version by typing the following in the prompt.

    >>> 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']  


    Description of Keywords in Python with Examples

    Keywords: True, False True, and False are truth values in Python. They are the results of comparison operations or logical (Boolean) operations in Python.

    >>> 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 true so the interpreter returns True and returns False for the remaining three statements. True and False in python are the same as 1 and 0.

    >>> True == 1

    True

    >>> False == 0

    True

    >>> True + True

    2 


    Keyword:  None is a special constant in Python that represents the absence of a value or a null value.

    It is an object of its own datatype, the NoneType. We cannot create multiple None objects but can assign them to variables. These variables will be equal to one another.

    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


    Void functions that do not return anything will return a None object automatically. None is also returned by functions in which the program flow does not encounter a return statement.

    def a_void_function():

        a = 1

        b = 2

        c = a + b

     

    x = a_void_function()

    print(x)

     

    *****OUTPUT*****

    None  


    This program has a function that does not return a value, although it does some operations inside. So when we print x, we get None which is returned automatically (implicitly).

    def improper_return_function(a):

        if (a % 2) == 0:

            return True

     

    x = improper_return_function(3)

    print(x)

     

    *****OUTPUT*****

    None 


    Although this function has a return statement, it is not reached in every case. The function will return True only when the input is even.

    If we give the function an odd number, None is returned implicitly.


    Keywords: and, or, not and, or, not are the logical operators in Python. and will result in True only if both the operands are True. The truth table for and is given below.


    Truth Table for and Keyword

    A

    B

    A and B

    True

    True

    True

    True

    False

    False

    False

    True

    False

    False

    False

    False


    Truth Table for or Keyword

    A

    B

    A or B

    True

    True

    True

    True

    False

    True

    False

    True

    True

    False

    False

    False


    Truth Table for not Keyword

    A

    NotA

    True

    .False

    False

    True


    Example of and, or, not in Python.

    >>> True and False

    False

    >>> True or False

    True

    >>> not False

    True  


    Keyword: as keyword is used to create an alias while importing a module. It means giving a different name (user-defined) to a module while importing it.

    For example, Python has a standard module called math. Suppose we want to calculate what cosine pi is using an alias. We can do it as follows using as.

    >>> import math as data

    >>>myAlias.cos(data.pi)

    -1.0  


    Here we imported the math module by giving it the name myalgias. Now we can refer to the math module with this name. Using this name we calculated cos(pi) and got -1.0 as the answer.


    Keyword: assert keyword is used for debugging purposes.While programming, sometimes we wish to know the internal state or check if our assumptions are valid. assert helps us do this and find bugs more conveniently. announce is followed by a condition.

    If the condition is true, nothing happens. But if the condition is false, AssertionError is 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  


    For our better understanding, we can also provide a message to be printed 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  


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

    import asyncio

    async def main():

        print('Hello')

        await asyncio.sleep(2)

        print('world')  


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

    Here, the first Hello is printed. The await keyword makes the program wait for 1 second. And then the world is printed.


    Keywords: Break, Continue break, and continue are used inside for and while loops to alter their normal behavior.

    the break will end the smallest loop it is in and control flows to the statement immediately below the loop. continue causes to end the current iteration of the loop, but not the whole loop.

    for i in range(1,11):

        if i == 5:

            break

        print(i)

     

    *****OUTPUT*****

    1

    2

    3

    4 


    Here, the for loop intends to print numbers from 1 to 10. But the if condition is met when I equal 5 and we break from the loop. Thus, only the range 1 to 4 is printed.


    or i in range(1,11):

        if i == 5:

            continue

        print(i)

     

    *****OUTPUT*****

    1

    2

    3

    4

    6

    7

    8

    9

    10 


    Here we use to continue the same program. So, when the condition is met, that iteration is skipped. But we do not exit the loop. Hence, all the values except 5 are printed out.


    Keyword: Class Keyword class is used to define a new user-defined class in Python. Class is a collection of related attributes and methods that try to represent a real-world situation. This idea of putting data and functions together in a class is central to the concept of object-oriented programming (OOP).

    Classes can be defined anywhere in a program. But it is a good practice to define a single class in a module. Following is a sample usage.

    class ExampleClass:

        def function1(parameters):

            …

        def function2(parameters): 


    Keyword: def keyword def is used to define a user-defined function.

    The function is a block of related statements, which together do some specific task. It helps us organize code into manageable chunks and also to do some repetitive tasks.

    def function_name(parameters):

        … 


    Keyword: del keyword del is used to delete the reference to an object. Everything is an object in Python. We can delete a variable reference using 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 of the variable a was deleted. So, it is no longer defined. But b still exists.

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

    >>> a = ['x's,'y','Z]

    >>> del a[1]

    >>> a

    ['x', 'z'] 


    Keyword: if, else, elif keywords are used for conditional branching or decision making. When we want to test some condition and execute a block only if the condition is true, then we use if and elif. elif is short for else if. else is the block which is executed if the condition is false.

    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*****

    Two

    Something else

    On 


    Here, the function checks the input number and prints the result if it is 1 or 2. Any input other than this will cause the else part of the code to execute.


    Keywords: except, raise, and try-except, raise, try are used with exceptions in Python. Exceptions are basic errors that suggest something went wrong while executing our program. IOError, ValueError, ZeroDivisionError, ImportError, NameError, TypeError etc. are a few examples of exceptions in Python. try...except blocks are used to catch exceptions in Python. We can raise an exception explicitly with the raise keyword.

    def reciprocal(num):

        try:

            r = 1/num

        except:

            print('Exception caught')

            return

        return r

    print(reciprocal(10))

    print(reciprocal(0))

     

    *****OUTPUT*****

    0.1

    Exception caught

    None 


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

    When we enter 10, we get the normal output of 0.1. But when we input 0, a ZeroDivisionError is raised automatically.

    This is caught by our try…except block and we return None. We could have also raised the ZeroDivisionError explicitly by checking the input and handling it elsewhere as follows:

    if num == 0:

        raise ZeroDivisionError('cannot divide') 


    Keyword: Finally finally keyword is used with try…except block to close up resources or file streams.

    Using finally ensures that the block of code inside it gets executed even if there is an unhandled exception.

    try:

        Try-block

    except for exception1:

        Exception1-block

    except exception2:

        Exception2-block

    else:

        Else-block

    finally:

        Finally-block


    Here if there is an exception, it is handled in the except or else block. But no matter in what order the execution flows, we can rest assured that the Finally block is executed even if there is an error. This is useful in cleaning up the resources.


    Keyword: For for keyword is used for looping. Generally, we use it the sequence the number of times we want to loop.

    In Python, we can use it with any type of sequence like a list or a string. Here is an example in which for is used to traverse through a list of names.

    names = ['Ravi','Baby','Nivi','Vijay']

    for I in names:

        print('Hello '+i)

     

    *****OUTPUT*****

    Hello Ravi

    Hello Baby

    Hello Nivi

    Hello Vijay


    Keyword: import the keyword is used to import modules into the current namespace. from…import is used to import specific attributes or functions into the current namespace.

    import math


    Keyword: Global global keyword is used to declare that a variable inside the function is global (outside the function).

    If we need to read the value of a global variable, it is not necessary to define it as global. This is understood.

    If we need to modify the value of a global variable inside a function, then we must declare it global. Otherwise, a local variable with that name is created.

    globvar = 10

    def read1():

        print(globvar)

    def write1():

        global globvar

        globvar = 5

    def write2():

        globvar = 15

     

    read1()

    write1()

    read1()

    write2()

    read1()

     

    *****OUTPUT*****

    10

    5

    5 


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

    We can see in our output that the modification did take place (10 is changed to 5). The write2() also tries to modify this value. But we have not declared it global.

    Hence, a new local variable globvar is created which is not visible outside this function. Although we modify this local variable to 15, the global variable remains unchanged. This is clearly visible in our output.


    Keyword: in keyword is used to test if a sequence (list, tuple, string, etc.) contains a v

    value. It returns True if the value is present, else it returns False.

    >>> a = [1, 2, 3, 4, 5]

    >>> 5 in a

    True

    >>> 10 in a

    False 


    Keyword: this is the keyword used in Python for testing object identity. While the == operator is used to test if two variables are equal or not, is used to test if the two variables refer to the same object. It returns True if the objects are identical and False if 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.

    >>> [] == []

    True

    >>> [] is []

    False

    >>> {} == {}

    True

    >>> {} is {}

    False 


    An empty list or dictionary is equal to another empty one. But they are not identical objects as they are located separately in memory. This is because the list and dictionary are mutable (value can be changed).

    >>> '' == ''

    True

    >>> '' is ''

    True

    >>> () == ()

    True

    >>> () is ()

    True 


    Unlike lists and dictionaries, strings and tuples are immutable (value cannot be altered once defined). Hence, two equal strings or tuples are identical as well. They refer to the same memory location.


    Keyword: lambda keyword is used to create an anonymous function (function with no name). It is an inline function that does not contain a return statement. It consists of an expression that is evaluated and returned.

    a = lambda x: x*2

    for i in range(1,6):

        print(a(i))

     

    *****OUTPUT*****

    2

    4

    6

    8

    10 


    Here, we have created an inline function that doubles the value, using the lambda statement. We used this to double the values in a list containing 1 to 5.


    Keyword: nonlocal The use of nonlocal keywords is very much similar to the global keyword. nonlocal is used to declare that a variable inside a nested function (function inside a function) is not local to it, meaning it lies in the outer enclosing function. If we need to modify the value of a non-local variable inside a nested function, then we must declare it nonlocal. Otherwise, a local variable with that name is created inside the nested function.

    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*****

    Inner function:  10

    Outer function:  10


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

    The variable a is in the outer_function(). So, if we want to modify it in the, we must declare it as nonlocal. Notice that a is not a global variable.

    Hence, we see from the output that the variable was successfully modified inside the nested inner_function(). The result of not using the nonlocal keyword is as.

    def outer_function():

        a = 5

        def inner_function():

            a = 10

            print("Inner function: ",a)

        inner_function()

        print("Outer function: ",a)

     

    outer_function()

     

    *****OUTPUT*****

    Inner function:  10

    Outer function:  5


    Here, we do not declare that the variable a inside the nested function is nonlocal. Hence, a new local variable with the same name is created, but the non-local a is not modified as seen in our output.


    Keyword: Pass keyword is a null statement in Python. Nothing happens when it is executed. It is used as a placeholder.

    Suppose we have a function that is not implemented yet, but we want to implement it in the future.

    def function(args):

        pass 


    Keyword: return keyword is used inside a function to exit it and return a value. If we do not return a value explicitly, None is returned automatically.

    def func_return():

        a = 10

        return a

     

    def no_return():

        a = 10

     

    print(func_return())

    print(no_return())

     

    *****OUTPUT*****

    10

    None


    Keyword: While the keyword is used for looping in Python. The statements inside a while loop continue to execute until the condition for the while loop evaluates to False a break a statement is encountered.

    data_tyi = 5

    while(i):

        print(i)

        i = i – 1

     

    *****OUTPUT*****

    5

    4

    3

    2

    1pe variable_name=value; 


    Keyword: with the keyword used to wrap the execution of a block of code within methods defined by the context manager. A context manager is a class that implements __enter__  __exit__ methods. The use of a 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.

    with open('example.txt', 'w') as my_file:

        my_file.write('Hello world!')


    This example writes the text Hello world! to the file example.txt. File objects have __enter__ and __exit__ the method defined within them, so they act as their own context manager.

    First, the __enter__ method is called, then the code within with the statement is executed and finally, the __exit__ method is called. __exit__ the method is called even if there is an error. It basically closes the file stream.


    Keyword: yield keyword is used inside a function like a return statement. But yield returns a generator. The generator is an iterator that generates one item at a time. A large list of values will take up a lot of memory. Generators are useful in this situation as it generates only one value at a time instead of storing all the values in memory.

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


    will create a generator g which generates powers of 2 up to the number two raised to the power 99. We can generate the numbers using the next() function shown below.

    >>> next(g)

    1

    >>> next(g)

    2

    >>> next(g)

    4

    >>> next(g)

    8

    >>> next(g)

    16 


    Read More Others Languages Keywords List

    Post a Comment

    0 Comments
    * Please Don't Spam Here. All the Comments are Reviewed by Admin.