51 lines
1.4 KiB
Plaintext
51 lines
1.4 KiB
Plaintext
# my_module.py
|
|
|
|
def greet(name):
|
|
"""This function greets the person passed in as a parameter."""
|
|
return f"Hello, {name}!"
|
|
|
|
|
|
def add(x, y):
|
|
"""This function returns the sum of two numbers."""
|
|
return x + y
|
|
|
|
|
|
def write_to_file(filename, content):
|
|
"""This function writes the given content to the specified file."""
|
|
with open(filename, "w") as f:
|
|
f.write(content)
|
|
|
|
|
|
def read_from_file(filename):
|
|
"""This function reads the content of the specified file and returns it."""
|
|
try:
|
|
with open(filename, "r") as f:
|
|
return f.read()
|
|
except FileNotFoundError:
|
|
return "File not found."
|
|
|
|
def main():
|
|
"""Main function that runs when the script is executed directly."""
|
|
name = "Alice"
|
|
print(greet(name))
|
|
|
|
num1 = 5
|
|
num2 = 3
|
|
print(f"The sum of {num1} and {num2} is: {add(num1, num2)}")
|
|
|
|
file_content = "This is some content written to a file."
|
|
write_to_file("example.txt", file_content)
|
|
print(f"Content written to file: {file_content}")
|
|
|
|
read_file_content = read_from_file("example.txt")
|
|
print(f"Content read from file: {read_file_content}")
|
|
|
|
read_file_content = read_from_file("nonexistent.txt")
|
|
print(f"Content read from file: {read_file_content}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("This script is being run directly.")
|
|
main()
|
|
else:
|
|
print("This script is being imported as a module.") |