Introduction
Welcome to PythonSage! In this post, we will dive into Python keywords.
These are special words in Python that have specific meanings and
roles.
They are reserved and cannot be used for purposes like variable names.
Python keywords define how the language works and are essential for writing
code in Python.
What are Python Keywords?
Python keywords are special words with predefined meanings in Python. They
serve specific purposes in the language and cannot be used as variable names
or identifiers. Currently, Python 3.12 has 39 keywords, including some that
depend on context. In this post, we'll explore each keyword, explaining what
they mean, how they are used, and providing practical examples to understand
their importance in Python programming.
Python Keywords
1. False
Definition: Represents a Boolean false value.
Usage: Used in conditional statements and logical operations.
Example:
is_raining = False
print(is_raining) # Output: False
2. None
Definition: Represents the absence of a value.
Usage: Indicates that a variable doesn't hold any value.
Example:
result = None
print(result) # Output: None
3. True
Definition: Represents a Boolean true value.
Usage: Used in conditional statements and logical operations.
Example:
is_sunny = True
print(is_sunny) # Output: True
4. and
Definition: Combines multiple conditions that must all be true.
Usage: Used in conditional statements and loops.
Example:
x = 5
if x greater than 0 and x less than 10:
print("x is between 0 and 10")
5. as
Definition: Creates an alias for a module.
Usage: Often used with imports and context managers.
Example:
import math as m
print(m.sqrt(25)) # Output: 5.0
6. assert
Definition: Tests if a condition is true; raises an AssertionError
if not.
Usage: Commonly used in debugging.
Example:
x = 10
assert x > 0, "x should be greater than 0"
7. async
Definition: Declares an asynchronous function.
Usage: Used in asynchronous programming.
Example:
import asyncio
async def example_async_function():
await asyncio.sleep(1)
print("Async function executed")
8. await
Definition: Waits for an asynchronous operation to complete.
Usage: Used within async functions.
Example:
async def example_async_function():
await some_async_operation()
9. break
Definition: Exits the nearest enclosing loop.
Usage: Terminates loops prematurely.
Example:
for i in range(5):
if i == 3:
break
print(i) # Output: 0, 1, 2
10. class
Definition: Declares a class.
Usage: Used to create user-defined objects.
Example:
class MyClass:
def __init__(self, name):
self.name = name
11. continue
Definition: Skips the rest of the loop for the current iteration
only.
Usage: Skips certain conditions in loops.
Example:
for i in range(5):
if i == 3:
continue
print(i) # Output: 0, 1, 2, 4
12. def
Definition: Declares a function.
Usage: Defines user-defined functions.
Example:
def greet(name):
print(f"Hello, {name}!")
13. del
Definition: Deletes objects.
Usage: Removes variables or objects.
Example:
x=10
del x
14. elif
Definition: Stands for "else if"; used in conditional
statements.
Usage: Checks multiple conditions.
Example:
weather = "rainy"
if weather == "sunny":
print("Bring sunglasses")
elif weather == "rainy":
print("Bring umbrella")
15. else
Definition: Executes a block of code if no conditions are true.
Usage: Used in conditional statements.
Example:
weather = "sunny"
if weather == "sunny":
print("Enjoy the sunny day!")
else:
print("Hope it clears up soon!")
16. except
Definition: Catches exceptions in a try block.
Usage: Handles errors.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
17. finally
Definition: Executes a block of code no matter what in
a try block.
Usage: Used for cleanup actions.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
18. for
Definition: Declares a for loop.
Usage: Iterates over a sequence.
Example:
for i in range(5):
print(i)
19. from
Definition: Imports specific parts of a module.
Usage: Used with imports.
Example:
from math import pi
print(pi) # Output: 3.141592653589793
20. global
Definition: Declares a global variable.
Usage: Refers to a variable outside of the current scope.
Example:
x = 10
def func():
global x
x += 5
print(x) # Output: 15
21. if
Definition: Declares a conditional statement.
Usage: Executes code based on a condition.
Example:
x = 10
if x > 5:
print("x is greater than 5")
22. import
Definition: Imports modules.
Usage: Includes external libraries.
Example:
import random
print(random.randint(1, 10)) # Output: Random number between 1 and 10
23. in
Definition: Checks if a value is in a sequence.
Usage: Used in membership tests and for loops.
Example:
names = ["Abdullah", "Ali", "Faisal"]
if "Ali" in names:
print("Ali is in the list")
24. is
Definition: Tests object identity.
Usage: Compares if two objects are the same.
Example:
a = [1, 2, 3]
b = a
if a is b:
print("a and b reference the same object")
25. lambda
Definition: Creates an anonymous function.
Usage: Used for short, throwaway functions.
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
26. nonlocal
Definition: Declares a non-local variable.
Usage: Refers to a variable in the nearest enclosing scope.
Example:
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
inner()
print(x) # Output: nonlocal
27. not
Definition: Negates a boolean expression.
Usage: Used in logical operations.
Example:
x = False
if not x:
print("x is not True")
28. or
Definition: Combines multiple conditions where at least one must be true.
Usage: Used in conditional statements and logic operations.
Example:
x = 10
if x < 0 or x > 100:
print("x is outside the range")
29. pass
Definition: Does nothing; acts as a placeholder.
Usage: Used in empty code blocks.
Example:
def placeholder():
pass
30. raise
Definition: Raises an exception.
Usage: Triggers exceptions.
Example:
x = -1
if x *use less than symbol 0:
raise ValueError("x cannot be negative")
31. return
Definition: Exits a function and optionally returns a value.
Usage: Used in functions.
Example:
def add(a, b):
return a + b
32. try
Definition: Begins a block of code that tests for exceptions.
Usage: Used for error handling.
Example:
try:
result = 10 / 0
33. while
Definition: Declares a while loop.
Usage: Repeats a block of code while a condition is true.
Example:
x = 0
while x < 5:
print(x)
x += 1
34. with
Definition: Simplifies exception handling by encapsulating common setup and teardown
code.
Usage: Used with context managers.
Example:
with open("file.txt", "r") as f:
content = f.read()
35. yield
Definition: Pauses a function, saving its state for later, and returns a value to the
caller.
Usage: Used in generators.
Example:
def generator():
yield 1
yield 2
yield 3
36. match
Definition: Begins a pattern-matching statement.
Usage: Used to match a value against a series of patterns, making the code more
readable and expressive, especially when dealing with multiple
conditions.
Example:
value = 2
match value:
case 1:
print("One")
case 2:
print("Two")
case _:
print("No match")
Conclusion
Python keywords are the building blocks
that shape how Python code is written and run. Knowing their meanings and uses
helps you tap into Python's powerful features to create strong and efficient
programs.
We've discussed the key Python keywords
here, but this is just the start of your journey to mastering Python. Keep
practicing and experimenting to get better at using them in your projects.
Visit the Links Below to Learn More:
Python Official Documentation on Keywords
Python Books and Courses:
Automate the Boring Stuff with Python
Coursera - Python for Everybody
Stay tuned to PythonSage for more tips and tutorials to boost your Python skills.
Happy coding!