[go: up one dir, main page]

0% found this document useful (0 votes)
3 views12 pages

Keywords in Python Python Variables Functions Classes

Subject in MBA courses

Uploaded by

scharancherry77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Keywords in Python Python Variables Functions Classes

Subject in MBA courses

Uploaded by

scharancherry77
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Python Keywords

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.

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 if, else, elif, for, while, break, continue, pass, try, except, finally, raise,
Keywords 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.

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

False

False

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

 and Keyword – return ‘True’ if both the operands are ‘True’

 or Keyword – return ‘True’ if at least one operand is ‘True’

 not keyword – returns ‘True’ if the expression is ‘False’, and vice versa.

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

 in keyword (membership operator) – Check if a value exists in a sequence (like a list, tuple,
or string). It returns True if value is found.
# 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")

 is keyword – Check if two variables point to the same object in memory. It returns True if the
objects are identical.

# 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

 if :Truth expression forces control to go in “if” statement block.

 else :False expression forces control to go in “else” statement block.

 elif : It is short for “else if”

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: This keyword is used to control flow and for looping.

 while: Has a similar working like “for”, used to control flow and for looping.

 break: “break” is used to control the flow of the loop. The statement is used to break out of
the loop and passes the control to the statement following immediately after loop.

 continue: “continue” is also used to control the flow of code. The keyword skips the current
iteration of the loop but does not end the loop.

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

 pass keyword: pass is the null statement in python. Nothing happens when this is
encountered. This is used to prevent indentation errors and used as a placeholder.
The code contains a for loop that iterates 10 times with a placeholder statement ‘pass',
indicating no specific action is taken within the loop.

n = 10

for i in range(n):
# pass can be used as placeholder

# when code is to added later

pass

Exception Handling Keywords

 try : This keyword is used for exception handling, used to catch the errors in the code using
the keyword except. Code in “try” block is checked, if there is any type of error, except block
is executed.

 except : As explained above, this works with “try” to catch exceptions.

 finally : No matter what is result of the “try” block, “finally” is always executed.

 raise: We can raise an exception explicitly with the raise keyword

 assert: This function is used for debugging purposes. Usually used to check the correctness
of code. If a statement is evaluated to be true, nothing happens but when it is false,
” AssertionError ” is raised. One can also print a message with the error, separated by a
comma .

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.

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.

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.

s = "GeeksForGeeks"

print(s)
del s

print(s)

Output

NameError: name 's' is not defined

Structure Keywords : def, class, return, lambda

 def keyword – Defines a function named fun using the def keyword. When the function is
called using fun().

def fun():

print("Inside Function")

fun()

Output

Inside Function

 class – class keyword is used to declare user defined classes.


This code defines a Python class named Dog with two class attributes, attr1 and attr2.

class Dog:

attr1 = "mammal"

attr2 = "dog"

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

Return Keywords – Return, Yield

 return : This keyword is used to return from the function.

 yield : This keyword is used like return statement but is used to return a generator.

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.

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

# Lambda keyword

g = lambda x: x*x*x

print(g(7))
Output

343

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.

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

import math as gfg

print(gfg.factorial(5))

Output

120

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.

# import keyword

from math import factorial


import math

print(math.factorial(10))

# from keyword

print(factorial(10))

Output

3628800

3628800

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 var1and prints it.

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

Output

25

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.

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.

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())

You might also like