All 39 Python Keywords Explained
5 min read
7 months ago
Published on Aug 05, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Introduction
This tutorial provides a comprehensive overview of the 39 keywords in Python, including both standard and soft keywords. Understanding these keywords is essential for writing effective Python code, as they form the foundation of the language's syntax and structure. This guide will walk you through each keyword, explaining its purpose and providing practical examples.
Chapter 1: False
- Definition:
False
is a Boolean constant representing the state of being false. - Usage:
has_money = False print(has_money) # Outputs: False print(int(has_money)) # Outputs: 0
Chapter 2: None
- Definition:
None
represents the absence of a value or a null value. - Usage:
selected_user = None print(selected_user) # Outputs: None
Chapter 3: True
- Definition:
True
is a Boolean constant representing the state of being true. - Usage:
has_money = True print(has_money) # Outputs: True print(int(has_money)) # Outputs: 1
Chapter 4: and
- Purpose: Used to check multiple conditions, all of which must be true.
- Usage:
age = 19 name = "Bob" if len(name) > 0 and age > 18: print("User is eligible to sign up.")
Chapter 5: as
- Purpose: Used to create an alias for a module or function.
- Usage:
import math as m print(m.cos(10))
Chapter 6: assert
- Purpose: Used to enforce a condition that must be true.
- Usage:
assert database_exists, "Database is required to run the program."
Chapter 7: async
- Purpose: Indicates that a function is asynchronous.
- Usage:
import asyncio async def main(): # Asynchronous code here pass
Chapter 8: await
- Purpose: Used to pause execution until a result is returned from an asynchronous function.
- Usage:
result = await my_async_function()
Chapter 9: break
- Purpose: Exits a loop prematurely.
- Usage:
for i in range(10): if i == 5: break print(i) # Outputs: 0, 1, 2, 3, 4
Chapter 10: class
- Purpose: Defines a new class.
- Usage:
class Person: def __init__(self, name): self.name = name
Chapter 11: continue
- Purpose: Skips the current iteration in a loop and continues with the next one.
- Usage:
names = ["Tom", "Bob", "James"] for name in names: if name == "Bob": continue print("Hello", name) # Outputs: Hello Tom, Hello James
Chapter 12: def
- Purpose: Defines a new function.
- Usage:
def my_function(): return "Hello, World!"
Chapter 13: del
- Purpose: Deletes an object.
- Usage:
name = "Python" del name
Chapter 14: elif
- Purpose: Adds additional conditions in if-else statements.
- Usage:
if weather == "rainy": print("Take an umbrella.") elif weather == "cloudy": print("Might need a jacket.")
Chapter 15: else
- Purpose: Executes code if none of the previous conditions are met.
- Usage:
if weather == "sunny": print("Wear sunglasses.") else: print("Check the weather.")
Chapter 16: except
- Purpose: Catches exceptions during code execution.
- Usage:
try: result = 1 / 0 except ZeroDivisionError as e: print("Caught an exception:", e)
Chapter 17: finally
- Purpose: Executes code regardless of whether an exception occurred.
- Usage:
try: # Code that may raise an exception pass finally: print("This will always execute.")
Chapter 18: for
- Purpose: Used to iterate over a sequence (like a list).
- Usage:
for element in [1, 2, 3]: print(element)
Chapter 19: from
- Purpose: Imports specific functions or classes from a module.
- Usage:
from math import sqrt print(sqrt(16)) # Outputs: 4.0
Chapter 20: global
- Purpose: Refers to variables defined in the global scope.
- Usage:
global_var = 10 def my_function(): global global_var global_var += 5
Chapter 21: if
- Purpose: Checks a condition and executes code if true.
- Usage:
if age > 100: print("Wow, good job!")
Chapter 22: import
- Purpose: Imports modules.
- Usage:
import random print(random.random())
Chapter 23: in
- Purpose: Checks for membership in an iterable.
- Usage:
if "Bob" in names: print("Found Bob")
Chapter 24: is
- Purpose: Checks object identity.
- Usage:
a = [1, 2, 3] b = a print(a is b) # Outputs: True
Chapter 25: lambda
- Purpose: Creates an anonymous function.
- Usage:
double = lambda x: x * 2 print(double(5)) # Outputs: 10
Chapter 26: nonlocal
- Purpose: Refers to variables in the nearest enclosing scope that is not global.
- Usage:
def outer_function(): x = "local" def inner_function(): nonlocal x x = "nonlocal" inner_function() print(x) # Outputs: nonlocal
Chapter 27: not
- Purpose: Negates the boolean value.
- Usage:
if not is_valid: print("Invalid input.")
Chapter 28: or
- Purpose: Checks if at least one of multiple conditions is true.
- Usage:
if a > b or c == d: print("At least one condition is true.")
Chapter 29: pass
- Purpose: A placeholder statement for future code.
- Usage:
def function_that_does_nothing(): pass
Chapter 30: raise
- Purpose: Triggers an exception.
- Usage:
raise ValueError("An error occurred.")
Chapter 31: return
- Purpose: Exits a function and optionally returns a value.
- Usage:
def add(a, b): return a + b
Chapter 32: try
- Purpose: Executes code that may raise an exception.
- Usage:
try: risky_code()
Chapter 33: while
- Purpose: Creates a loop that continues while a condition is true.
- Usage:
while condition: # Loop code here
Chapter 34: with
- Purpose: Simplifies exception handling by encapsulating common preparation and cleanup tasks.
- Usage:
with open("file.txt") as file: data = file.read()
Chapter 35: yield
- Purpose: Used in generators to produce a series of values.
- Usage:
def generate_numbers(limit): for i in range(limit): yield i
Chapter 36: underscore
- Purpose: Has multiple uses, including as a variable name for throwaway variables.
- Usage:
for _ in range(3): print("Hello") # Outputs: Hello three