Python Keywords: 10 Example Code Snippets
This article introduces Python's essential keywords, explaining their purpose and demonstrating ten practical code examples that cover conditional statements, loops, functions, classes, exception handling, file management, module imports, return values, infinite loops with break, and extended conditional branches.
Python is an elegant and powerful programming language whose design emphasizes readability; its keywords are reserved identifiers that define the language's syntax. Understanding these keywords is fundamental for writing effective Python code.
Example 1: Using if for conditional judgment x = 10 if x > 5: print("x is greater than 5.")
Output: x is greater than 5.
Example 2: Using for to iterate over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Output: apple banana cherry
Example 3: Defining a function with def def greet(name): print(f"Hello, {name}!") greet("Alice")
Output: Hello, Alice!
Example 4: Defining a class with class class Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print(f"My name is {self.name} and I am {self.age} years old.") person = Person("Bob", 30) person.introduce()
Output: My name is Bob and I am 30 years old.
Example 5: Handling exceptions with try and except try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero.")
Output: Cannot divide by zero.
Example 6: Managing file operations with with with open('example.txt', 'w') as file: file.write("Hello, world!\n") with open('example.txt', 'r') as file: print(file.read())
Output: Hello, world!
Example 7: Importing a module with import import math print(math.sqrt(16))
Output: 4.0
Example 8: Returning a value from a function with return def add(a, b): return a + b result = add(5, 3) print(result)
Output: 8
Example 9: Creating an infinite loop with while and breaking out i = 0 while True: print(i) i += 1 if i >= 5: break
Output: 0 1 2 3 4
Example 10: Extending conditional branches with elif score = 85 if score >= 90: grade = "A" elif score >= 80: grade = "B" else: grade = "C" print(f"Your grade is {grade}.")
Output: Your grade is B.
Tip: Python 3.10 defines 35 keywords, including all shown above. Avoid using keywords as variable or function names to prevent unexpected behavior.
Keyword list (partial): False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.