Python, as a widely adopted programming language, comes with a set of keywords that form the foundation of its syntax. These keywords have specific meanings and are used to structure and define various program elements. In this blog post, we will delve into some of the main Python keywords and provide annotations to help understand their usage and significance.
1. def
Annotation: Used to define a function. Functions are blocks of code that perform specific tasks and can be called repeatedly.
Example:
pythondef greet(name):
return "Hello, " + name
2. class
Annotation: Used to define a new class. Classes are templates for creating objects that have attributes and methods.
Example:
pythonclass Dog:
def __init__(self, name, age):
self.name = name
self.age = age
3. if
, elif
, else
Annotation: These keywords are used to control the flow of execution based on certain conditions. They allow you to execute code conditionally.
Example:
pythonif x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
4. for
, while
Annotation: These keywords are used for looping. for
is typically used to iterate over sequences (like lists or strings), while while
is used for indefinite iteration based on a given condition.
Example (for loop):
pythonfor i in range(5):
print(i)
Example (while loop):
pythoncount = 0
while count < 5:
print(count)
count += 1
5. try
, except
, finally
Annotation: These keywords are used for exception handling. They allow you to specify code blocks that will be executed if a specific error occurs, as well as code that will always be executed regardless of the outcome.
Example:
pythontry:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always be printed.")
6. import
, from ... import ...
Annotation: These keywords are used to import modules or specific functions/classes from modules. This allows you to use code written by others or organize your own code into separate files.
Example:
pythonimport math
print(math.sqrt(16)) # Imports the entire math module
from os import path
print(path.exists("/some/path")) # Imports the path function from the os module
7. return
Annotation: Used inside a function to specify the value that will be returned when the function is called.
Example:
pythondef add(a, b):
return a + b
8. in
, not in
Annotation: These keywords are used to check if a value exists within a sequence or collection.
Example:
pythonif 'apple' in ['banana', 'apple', 'orange']:
print("Found!")
The list of keywords provided here is not exhaustive, but it covers some of the most commonly used and fundamental keywords in Python. Understanding these keywords and their usage is crucial for writing effective and maintainable Python code.