Keywords Related to Flow Control
- if, elif, else: Used for conditional branching, controlling which blocks of code execute based on conditions.
- for: Used for iterating over a sequence of items (like lists, tuples, strings, ranges).
- while: Used for creating loops that continue as long as a condition is true.
- break: Exits a loop prematurely.
- continue: Skips to the next iteration of a loop.
- pass: Placeholder statement that does nothing; often used during development when syntax requires a statement, but you haven’t written the code yet.
1# Flow Control
2count = 0
3while count < 5:
4 print(f"Count: {count}")
5 count += 1
6
7for i in range(3):
8 print(f"Iteration: {i}")
9
10if count == 5:
11 print("Count reached 5!")
12else:
13 print("Count is not 5.")
Keywords Related to Functions and Scope
- def: Defines a function, a reusable block of code.
- return: Sends a value back from a function.
- lambda: Creates a small, anonymous function.
- global: Accesses a global variable from within a function’s scope.
- nonlocal: Modifies a variable in an enclosing function’s scope (not the global scope).
1# Functions
2def greet(name):
3 return f"Hello, {name}!"
4
5message = greet("Alice")
6print(message)
7#Output: Hello, Alice
Keywords Related to Classes and Objects
- class: Defines a class, a blueprint for creating objects (instances).
- self: A reference to the current instance of the class.
- init: The constructor method, called when an object is created.
- super: Provides access to methods and attributes of a parent class.
1# Classes
2class Dog:
3 def __init__(self, name, breed):
4 self.name = name
5 self.breed = breed
6
7 def bark(self):
8 return "Woof!"
9
10my_dog = Dog("Jack", "GoldenDoodle")
11print(f"{my_dog.name} says {my_dog.bark()}")
12# Jack says Woof!
Keywords Related to Error Handling
- try: A block of code where you anticipate potential errors.
- except: Handles a specific type of exception (error).
- finally: A block of code that always executes, whether an exception occurred or not.
- raise: Manually triggers an exception.
1# Error Handling
2try:
3 result = 10 / 0
4except ZeroDivisionError:
5 print("You cannot divide by zero!")
Keywords Related to Boolean Logic and Comparisons
- True, False: The two Boolean values, representing truthiness or falseness.
- and, or, not: Logical operators used to combine or modify Boolean expressions.
- is, is not: Identity operators, checking if two variables refer to the same object in memory.
- in, not in: Membership operators, checking if a value is present in a sequence.
1temperature = 25
2is_sunny = True
3wind_speed = 15
4
5# Comparisons
6is_warm = temperature > 20 # True
7is_windy = wind_speed > 10 # True
8
9# Boolean Logic
10good_weather = is_warm and is_sunny # True (both conditions are True)
11stay_inside = not is_sunny or is_windy # True (at least one condition is True)
Keywords with Special Meanings
- None: Represents the absence of a value.
- as: Used for aliasing (giving a different name to an imported module or exception).
- with: Simplifies working with resources that need to be opened and closed properly (e.g., files).
- yield: Used in generator functions, which produce a sequence of values one at a time.
- del: Deletes objects, variables, or slices from a list.
- assert: Checks if a condition is true; if not, it raises an exception.
1# Other Keywords
2my_list = [1, 2, 3]
3del my_list[0]
4print(my_list)
5
6x = 5
7assert x > 0, "x should be a positive number"
Notes:
- Case-Sensitivity: Python keywords are case-sensitive (e.g.,
for
is different fromFor
). - Reserved: You cannot use keywords as variable, function, or class names.