Sure! Here are several Python snippets each in their own code block:
1. Hello World
print("Hello, World!")
2. List Comprehension: Squaring Numbers
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)
# Output: [1, 4, 9, 16, 25]
3. Reading a File
file_path = 'example.txt'
try:
with open(file_path, 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
4. Writing to a File
file_path = 'output.txt'
data = "This is some sample text."
with open(file_path, 'w') as file:
file.write(data)
print(f"Data has been written to {file_path}")
5. Defining a Simple Class
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
# Usage
my_dog = Dog("Buddy", 3)
print(my_dog.bark())
# Output: Buddy says woof!
6. Making an HTTP GET Request (using requests library)
import requests
url = 'https://api.github.com'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")
7. Using a Decorator
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Usage
say_hello()
Output:
Before the function is called.
Hello!
After the function is called.
8. Handling Exceptions
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
print(f"The result is {result}")
finally:
print("Execution completed.")
# Usage
divide(10, 2)
divide(10, 0)
Output:
The result is 5.0
Execution completed.
Error: Cannot divide by zero.
Execution completed.
Feel free to ask if you need snippets for specific tasks or functionalities!