Python Keywords (original) (raw)

Keywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier.

List of Keywords in Python

**True **False **None **and
**or **not **is **if
**else **elif **for **while
**break **continue **pass **try
**except **finally **raise **assert
**def **return **lambda **yield
**class **import **from **in
**as **del **global **with
**nonlocal **async **await

Getting List of all Python keywords

We can also get all the keyword names using the below code.

Python `

import keyword

printing all keywords at once using "kwlist()"

print("The list of keywords is : ") print(keyword.kwlist)

`

**Output:

The list of keywords are: 
['False', 'None', 'True',"peg_parser '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']

How to Identify Python Keywords ?

**With Syntax Highlighting – Most of IDEs provide syntax-highlight feature. You can see Keywords appearing in different color or style.

**Look for SyntaxError – This error will encounter if you have used any keyword incorrectly. Note that keywords can not be used as identifiers (variable or a function name).

Let’s categorize all keywords based on context and understand each with help of example.

Category Keywords
**Value Keywords True, False, None
**Operator Keywords and, or, not, in, is
**Control Flow Keywords if, else, elif, for, while, break, continue, pass, try, except, finally, raise, assert
**Function and Class def, return, lambda, yield, class
**Context Management with, as
**Import and Module import, from, as
**Scope and Namespace global, nonlocal
**Async Programming async, await

**Value Keywords: True, False, None Keyword, del

**True, False: These represent a boolean values.

**None: This is a special constant used to denote a null value or a void. It’s important to remember that 0, any empty container(e.g. empty list) does not compute to None. It is an object of its datatype – NoneType. It is not possible to create multiple None objects and can assign them to variables.

Python `

print(False == 0) print(True == 1)

True + True + True is 3

print(True + True + True)

True + False + False is 1

print(True + False + False)

None isn't equal to 0 or an empty list []

print(None == 0) print(None == [])

`

Output

True True 3 1 False False

Operator Keywords: and, or, not, in, is

a = True b = False

Logical operations

print(a and b) # AND: True if both a and b are True print(a or b) # OR: True if at least one of a or b is True print(not a) # NOT: Inverts the value of a

`

example 1

print(3 in [1,2,3])

example 2

if 's' in 'geeksforgeeks': print("s is part of geeksforgeeks") else: print("s is not part of geeksforgeeks")

`

example 1

print(2 is 2)

example 2

a = [1, 2, 3] b = a c = [1, 2, 3]

True: a and b refer to the same object

print(a is b)

False: a and c have same value but are different objects

print(a is c)

`

Conditional keywords in Python: if, else, elif

x = 0

python if elif else statement

if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero")

`

Iteration Keywords: for, while, break, continue, pass in Python

'for' loop example

for num in range(3): if num == 2: continue # Skip number 2 print(num)

Output: 0 1

'while' loop example

count = 0 while count < 4: count += 1 if count == 3: break # Exit the loop when count reaches 4 print(count)

Output: 1 2

`

n = 10 for i in range(n):

# pass can be used as placeholder
# when code is to added later
pass

`

Exception Handling Keywords

**Example 1: The provided code demonstrates the use of several keywords in Python:

  1. **try and except : Used to handle exceptions, particularly the ZeroDivisionError , and print an error message if it occurs.
  2. **finally : This block is always executed, and it prints “This is always executed” regardless of whether an exception occurs.
  3. **assert : Checks a condition, and if it’s False , raises an AssertionError with the message “Divide by 0 error.”
  4. **raise : Raises a custom exception ( TypeError ) with a specified error message if a condition is not met. Python `

a, b = 4, 0

try: k = a // b # Attempt integer division (4 // 0) print(k)

This block catches the ZeroDivisionError

except ZeroDivisionError: print("Can't divide by zero")

finally: # This block is always executed regardless of the exception print('This is always executed')

print("The value of a / b is : ")

Will raise an AssertionError because b == 0

assert b != 0, "Divide by 0 error"

Division is attempted but will not reach due to assert

print(a / b)

Raise a TypeError if the strings are different

temp = "geeks for geeks" if temp != "geeks": raise TypeError("Both the strings are different.")

`

**Output

Can't divide by zero
This is always executed
The value of a / b is :
AssertionError: Divide by 0 error

**Example 2: This code uses the raise keyword to raise a custom TypeError exception if two strings are not equal.

Python `

temp = "geeks for geeks" if temp != "geeks": raise TypeError("Both the strings are different.")

`

**Output

TypeError: Both the strings are different.

**Note: For more information refer to our tutorial Exception Handling Tutorial in Python.

del Keyword in Python

**del is used to delete a reference to an object. Any variable or list value can be deleted using del.

Python `

s = "GeeksForGeeks" print(s)

del s print(s)

`

**Output

NameError: name 's' is not defined

Structure Keywords : def, class, return, lambda

def fun(): print("Inside Function")

fun()

`

class Dog: attr1 = "mammal" attr2 = "dog"

`

**Note: For more information, refer to our Python Classes and Objects Tutorial .

**Return Keywords – Return, Yield

Return and Yield Keyword use in Python

The return' keyword is used to return a final result from a function, and it exits the function immediately. In contrast, the ‘yield'** keyword is used to create a generator, and it allows the function to yield multiple values without exiting. When ‘**return'** is used, it returns a single value and ends the function, while ‘**yield'** returns multiple values one at a time and keeps the function’s state.

Python `

Return keyword

def fun():

 # Assign the value 2 to variable S
s = 2  

# Return the value of S
return s

Call the function and print the result

print(fun())

Yield Keyword

def fun():

  # Yield the value 1, pausing the function here
yield 1
# Yield the value 2, pausing the function again
yield 2
# Yield the value 3, pausing the function once more
yield 3  

Iterate through the values yielded by the function

for value in fun(): print(value)

`

**Output

2
1
2
3

Lambda Keyword in Python

**Lambda keyword is used to make inline returning functions with no statements allowed internally.

Python `

Lambda keyword

g = lambda x: xxx

print(g(7))

`

Context Keywords: With, as Keyword in Python

with Keyword in Python

**with keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming.

This code demonstrates how to use the with statement to open a file named **'file_path' **in write mode ****(** 'w' ). It writes the text **'hello world !'**to the file and automatically handles the opening and closing of the file. **with **statement is used for better resource management and ensures that the file is properly closed after the block is executed.

Python `

using with statement

with open('file_path', 'w') as file: file.write('hello world !')

`

as Keyword In Python

**as keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath.

This code uses the Python **math **module, which has been imported with the alias gfg . It calculates and prints the factorial of 5. The math.factorial() function is used to calculate the factorial of a number, and in this case, it calculates the factorial of 5, which is 120.

Python `

import math as gfg

print(gfg.factorial(5))

`

**Import and Module: Import, From in Python

**import : This statement is used to include a particular module into current program.

**from : Generally used with import, from is used to import particular functionality from the module imported.

Import, From Keyword uses in Python

The import' keyword is used to import modules or specific functions/classes from modules, making them accessible in your code. The from' keyword is used with‘** import' to specify which specific functions or classes you want to import from a module. In your example, both approaches import the ** factorial' function from the ** math' module, allowing you to use it directly in your code.

Python `

import keyword

from math import factorial import math print(math.factorial(10))

from keyword

print(factorial(10))

`

Scope and Namespace: Global, Nonlocal in Python

**global: This keyword is used to define a variable inside the function to be of a global scope.

**non-local : This keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions.

Global and nonlocal keyword uses in Python

In this code, the global' keyword is used to declare global variables a' and ** b'. Then, there’s a function ** add' that adds these global variables and prints the result.

The second part of the code demonstrates the ** nonlocal' keyword. The function fun contains a variable var1, and within the nested function gun, we use nonlocal to indicate that we want to modify the var1 defined in the outer function fun . It increments the value of **var1**and prints it.

Python `

a = 15 b = 10

def add():

  # Add global variables a and b
c = a + b  
print(c)

add() # Output: 25

def fun():

Local variable in fun()

var = 10  

def gun():
  
      # Modify var1 in the enclosing scope (fun)
    nonlocal var  
    var += 10  
    print(var)  

gun() 

fun() # Output: 20

`

**Note: For more information, refer to our Global and local variables tutorial in Python.

Async Programming: async, await

Async programming allows you to run tasks concurrently, improving efficiency, especially when dealing with I/O-bound operations. The async and await keywords in Python are used to define and manage asynchronous functions.

async: Used to declare a function as asynchronous, allowing it to run concurrently with other tasks.

Python `

import asyncio

async def func(): print("Hello, async world!")

`

await: Used to pause the execution of an async function until the awaited task is complete.

Python `

import asyncio

Define an asynchronous main function

async def main(): await func()

Define another async function that prints a message

async def func(): print("Hello, async world!")

Run the main function using asyncio.run

asyncio.run(main())

`

Suggested Quiz

10 Questions

Which of the following keywords is used to define a function in Python?

Explanation:

def is the keyword used to define a function in Python. After def, you specify the function name, followed by parentheses () and a colon : to start the function's body.

What keyword is used to handle exceptions in Python?

Explanation:

try is used to define a block of code that might raise an exception. except follows the try block and defines the code that runs if an exception occurs.

Which keyword is used to create a new class in Python?

Explanation:

class is used to define a new class in Python.

In Python, which keyword is used to indicate that a variable is global?

Explanation:

In Python, the keyword global is used to indicate that a variable is global. This keyword is used inside a function to refer to a variable that is defined in the global scope, allowing the function to modify the global variable directly.

What does the elif keyword do in Python?

Explanation:

elif is short for "else if" and is used after an if block to check for additional conditions when the original if condition fails.

What keyword is used to return a value from a function in Python?

Explanation:

The return keyword is used inside a function to send back a result or value to the caller, effectively ending the function.

Which of the following keywords is used to define an object constructor in Python?

Explanation:

__init__ is a special method in Python used to initialize an object's state when a new instance of a class is created.

Which of the following keywords is used to declare an alias for a module in Python?

Explanation:

The import as syntax allows you to import a module and give it a shorthand alias, which is useful for convenience.

What keyword is used to define an empty function or class in Python?

Explanation:

pass is a placeholder keyword that does nothing. It is used in scenarios where we need to define a function or class but haven’t implemented it yet.

Which keyword is used to define an anonymous function in Python?

Explanation:

The lambda keyword is used to create anonymous (unnamed) functions in Python, typically for short, simple operations.

Quiz Completed Successfully

Your Score : 2/10

Accuracy : 0%

Login to View Explanation

1/10

1/10 < Previous Next >