How many Keywords are used in Python?
Python Keywords: The pre-defined word in the library is referred to as a keyword. Its capabilities are also predetermined. A keyword cannot be used as an identifier for a variable, function, class, or in any other way. There are a number of reserved words in the Python language that cannot be used as variable names, function names, or any other kind of identifiers.
|
Best Python Language Keywords List with Description |
Python Keywords List with Description
What are the 33 keywords of Python? Keyword Description and: and keyword is a logical operator. as: as keyword to create an alias (Anonymous) name. assert: assert keyword use for debugging. break: break keyword use to break out of a loop. class: class keyword to use to define a class. continue: continue keyword to continue to the next iteration of a loop. def: def keyword to define a function. del: del keyword to delete any object in python. elif: elif keyword used in conditional statements. else: else, keyword used in conditional statements. except: except keyword used with exceptions. False: False keyword used Boolean value like True or False. finally: finally, keyword used exception handling. for: for keyword to create a for loop. from: from keyword, use to import any module in python. global: global keyword to declare a global variable in python. if: if keyword to make a conditional statement. import: import keyword to import a module in python. in: in keyword used to check if a value is present in a list, tuple, and dictionary etc. is: is keyword to test if two variables are equal. lambda: lambda keyword to create an anonymous function in python. None: none keyword represents a null value. nonlocal: nonlocal to declare a non-local variable. not: not keyword, is a logical operator. or: or keyword is a logical operator. pass: pass a null statement, a statement that will do nothing. raise: raise keyword to raise an exception. return: return to exit a function and return a value. True: true keyword Boolean value, result of comparison operations. try: try keyword to make a try...except exception statement in python. while: while keyword to create a while loop. with: with keyword used to simplify exception handling. yield: yield keyword to end a function, returns a generator in python. |
and Keyword in Python: In Python, the and keyword is a logical operator that returns True if both the operands are True, and False otherwise.
The and operator has a lower precedence than comparison operators, so you might need to use parentheses to specify the order of evaluation if you are using multiple and operators in a single expression.
x = True y = False
if x and y: print("Both x and y are True") else: print("Either x or y or both are False")
**********OUTPUT**********
Either x or y or both are False |
You can use the and operator to test multiple conditions in an if statement or in a boolean expression.
if x > 0 and y > 0: print("Both x and y are positive numbers")
**********OUTPUT********** Both x and y are positive numbers |
as Keyword: as is used in import statements to give an imported module or object a different alias.
import math as m
x = m.pi print(x)
**********OUTPUT**********
3.141592653589793 |
Here, we have imported the math module and given it the alias m. We can then use the m alias to access the functions and variables in the math module, such as pi.
assert keyword: In Python, the assert keyword is used to test a condition, and raise an exception if the condition is False.
x = 5 assert x > 0, "x must be positive"
**********OUTPUT********** x must be positive |
In this example, we are testing whether the value of x is greater than zero. If x is greater than zero, the assert statement will do nothing. If x is not greater than zero, the assert statement will raise an AssertionError exception with the message "x must be positive".
def add(x, y): assert isinstance(x, int) and isinstance(y, int), "Both arguments must be integers" return x + y
print(add(1, 2)) # prints 3 print(add(1, '2')) # raises AssertionError
|
In this example, we are using the assert statement to ensure that both x and y are integers before performing the addition. If either x or y is not an integer, the assert statement will raise an AssertionError exception.
By default, Python's interpreter ignores assert statements when running a program. To enable assert statements, you can use the -O flag when running the program or set the PYTHONOPTIMIZE environment variable to 0.
break keyword: In Python, the break keyword is used to exit a loop early, before the loop condition is False.
for i in range(10): if i == 5: break print(i)
**********OUTPUT********** |
In this example, we are using a for loop to iterate over the numbers 0 to 9. If the value of i is equal to 5, we use the break statement to exit the loop. As a result, the loop will only print the numbers 0 to 4.
class keyword: In Python, the class keyword is used to define a new class. A class is a template for creating objects, and an object is an instance of a class.
This defines a class called MyClass with no attributes or methods. To create an object of this class, you can use the class name followed by parentheses:
You can define attributes and methods in a class by using the self keyword. Attributes are variables that belong to an object, and methods are functions that belong to an object.
class MyClass: def __init__(self, x, y): self.x = x self.y = y
def sum(self): return self.x + self.y
obj = MyClass(1, 2) print(obj.sum()) |
In this example, we have defined a class with two attributes, x and y, and a method called sum that returns the sum of the x and y attributes.
We have also defined a special method called __init__ that is used to initialize an object when it is created. The __init__ method takes three arguments: self, which is a reference to the object itself; and x and y, which are the arguments passed to the class when the object is created.
You can also define class-level attributes and methods, which belong to the class itself rather than to individual objects. To define a class-level attribute or method, you don't need to use the self keyword.
continue keyword: In Python, the continue keyword is used to skip the rest of the current iteration of a loop and move on to the next iteration.
for i in range(10): if i % 2 == 0: continue print(i)
**********OUTPUT********** |
In this example, we are using a for loop to iterate over the numbers 0 to 9. If the value of i is even, we use the continue statement to skip the rest of the current iteration and move on to the next one. As a result, the loop will only print the odd numbers.
def keyword: In Python, the def keyword is used to define a function. A function is a block of code that can be called by name to perform a specific task.
def greet(): print("Hello, World!")
greet()
**********OUTPUT********** Hello, World! |
This defines a function called greet that prints the message "Hello, World!". To call the function, you can use its name followed by parentheses.
del Keyword: In Python, the del keyword is used to delete an object, such as a variable, a list element, or an item in a dictionary.
# Delete a variable x = 10 del x
# Delete a list element lst = [1, 2, 3, 4] del lst[1] # lst is now [1, 3, 4]
# Delete an item in a dictionary d = {'a': 1, 'b': 2, 'c': 3} del d['b'] # d is now {'a': 1, 'c': 3} |
In the first example, we are deleting the variable x, which will remove it from the current scope and make it unavailable for use.
In the second example, we are deleting the element at index 1 in the list lst, which will remove the element and shift the remaining elements to the left.
In the third example, we are deleting the item with the key 'b' in the dictionary d, which will remove the item and its corresponding value.
Note that the del statement cannot be used to delete elements from a tuple, since tuples are immutable.
elif keyword: In Python, the elif keyword is used in an if statement to specify additional conditions that are checked only if all the previous conditions are False.
x = 10
if x > 5: print("x is greater than 5") elif x < 5: print("x is less than 5") else: print("x is equal to 5") |
In this example, the first if statement checks whether x is greater than 5. Since x is equal to 10, which is greater than 5, the first if statement evaluates to True and the string "x is greater than 5" is printed. The elif and else statements are not executed because the first if statement is True.
If the value of x were changed to 3, the first if statement would evaluate to False and the elif statement would be executed. Since 3 is less than 5, the string "x is less than 5" would be printed. The else statement would not be executed because one of the previous conditions was True.
You can use as many elif statements as you like in an if statement, and they will be checked in order until one of them evaluates to True or all of them are False. If all the elif statements are False, the else statement (if there is one) will be executed.
else keyword: In Python, the else keyword is used in an if statement to specify a block of code that should be executed if all the previous conditions are False.
except keyword: In Python, the except keyword is used in a try statement to specify a block of code that should be executed if an exception is raised during the execution of the code in the try block.
try: x = 10 / 0 except ZeroDivisionError: print("You can't divide by zero!")
**********OUTPUT********** You can't divide by zero |
In this example, the code in the try block attempts to divide 10 by 0, which will raise a ZeroDivisionError exception. The except block specifies that if a ZeroDivisionError exception is raised, the string "You can't divide by zero!".
You can specify multiple except blocks to handle different types of exceptions, or you can use the Exception class to catch any type of exception.
try: x = 10 / 0 except ZeroDivisionError: print("You can't divide by zero!") except Exception as e: print("An error occurred:", e) |
In this example, if a ZeroDivisionError exception is raised, the first except block will handle it and print the appropriate message. If any other type of exception is raised, it will be caught by the second except block and the error message will be printed.
It's important to note that the except block will only be executed if an exception is raised during the execution of the try block. If no exception is raised, the except block will be skipped.
false keyword: In Python, the False keyword is a Boolean value that represents the absence of truth. It is one of the two possible values for a Boolean expression, along with True.
Boolean values are often used in control statements such as if and while to check whether a condition is True or False.
x = 10
if x > 5: print("x is greater than 5") else: print("x is not greater than 5") |
In this example, the if statement checks whether the value of x is greater than 5. Since x is equal to 10, which is greater than 5, the condition is True and the string "x is greater than 5" is printed. If the value of x were changed to 3, the condition would be False and the string "x is not greater than 5" would be printed.
for keyword: In Python, the for keyword is used to create a loop that iterates over a sequence of objects, such as a list or a string.
colors = ["red", "green", "blue"]
for color in colors: print(color)
**********OUTPUT********** red green blue |
from keyword: In Python, the from keyword is used in a number of different contexts, including:
In an import statement to specify which specific elements or modules to import from a package.
from math import pi, sin
print(pi) print(sin(pi / 2)) |
This code will import the pi and sin elements from the math module and print their values.
global keyword: In Python, the global keyword is used to indicate that a variable is a global variable, rather than a local variable. Global variables are variables that are defined outside of any function or class and are available to all parts of the program.
x = 10
def foo(): global x x = 20
print(x) foo() print(x)
**********OUTPUT********** 10 20 |
In this example, the variable x is defined outside of any function and is therefore a global variable. The foo function uses the global keyword to indicate that it will be modifying the global variable x. When the function is called, it changes the value of x to 20. When the value of x is printed after the function is called, it has been changed to 20.
yield Keyword: In Python, the yield keyword is used in a function to specify that the function should be a generator. Generators are special iterators that generate a sequence of values one at a time, rather than creating a whole sequence in memory at once.
def count_up_to(max): count = 1 while count <= max: yield count count += 1
for number in count_up_to(5): print(number) |
The count_up_to function is a generator function that uses the yield keyword to yield each number in the sequence one at a time. When the generator is iterated over using a for loop, the generator function is executed from the beginning until a yield statement is encountered.
The value of the yield expression is returned to the caller, and the state of the generator function is saved. The next time the generator is iterated over, execution resumes after the most recent yield statement. This process continues until the generator function completes, at which point the generator is exhausted and the for loop terminates.
Generators are often used when it is not practical to create and store a large sequence in memory all at once, such as when iterating over a large dataset or when the elements of the sequence are generated on the fly. They can also be used to implement infinite sequences, where the generator function never completes.
0 Comments