In Python, a keyword is a reserved word that has a special meaning and purpose in the language. These words are used to define the syntax and structure of the code and cannot be used as variable names or identifiers.
Python has a set of 35 keywords that are predefined and cannot be used as variable names or function names. Some of the commonly used Python keywords are:
and
,or
,not
: Used for boolean logicif
,elif
,else
: Used for conditional statementsfor
,while
,break
,continue
: Used for looping constructsdef
,return
,lambda
: Used for defining functionsclass
,import
,from
,as
: Used for object-oriented programming and module imports
Using a keyword as a variable name or function name will result in a syntax error. Therefore, it is important to be aware of the keywords in Python and avoid using them as identifiers.
# Conditional statement using if-else
x = 10
if x < 5:
print("x is less than 5")
else:
print("x is greater than or equal to 5")
# Looping construct using for
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Defining a function using def
def add_numbers(x, y):
return x + y
# Object-oriented programming using class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is", self.name)
# Module import using import
import math
print(math.sqrt(16))
In this example, we use the keywords if
, else
, for
, def
, class
, and import
to define conditional statements, looping constructs, functions, classes, and module imports in Python. We also use the and
and or
keywords to perform boolean logic operations within the conditional statement. These keywords have predefined meanings in Python and cannot be used as variable or function names.