17.Functions II and Environment, Errors, Files
Environment Variables
Environment variables store configuration outside the code. Python can access them using the os module.
Example:
import os
# Get environment variable
path = os.getenv(‘PATH’)
print(path)
# Set environment variable
os.environ[‘MY_VAR’] = ‘Hello’
2.Error Handling
Python uses try/except blocks to handle exceptions gracefully. You can also use finally for cleanup and else for code that runs if no exception occurs.
Example:
try:
num = int(input(“Enter a number: “))
print(10 / num)
except ZeroDivisionError:
print(“Cannot divide by zero.”)
except ValueError:
print(“Invalid input.”)
else:
print(“Operation successful.”)
finally:
print(“Execution finished.”)
3.File Operations
Python provides built-in functions for file handling. Use context managers (with statement) to ensure files are properly closed.
Example:
# Writing to a file
with open(‘example.txt’, ‘w’) as f:
f.write(‘Hello, World!’)
# Reading from a file
with open(‘example.txt’, ‘r’) as f:
content = f.read()
print(content)
Best Practices for File Handling
– Always use context managers to handle files.
– Handle exceptions when working with files.
– Use absolute paths or pathlib for better path management.
– Avoid hardcoding sensitive information in files.