From 0e7aa4727e2973e05a8add45405297548eaaae65 Mon Sep 17 00:00:00 2001 From: "Lennie S." Date: Sat, 11 Apr 2026 22:48:03 +0000 Subject: [PATCH] Add --output flag to write to file --- fibonacci.py | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/fibonacci.py b/fibonacci.py index dbe2692..dd8a66a 100644 --- a/fibonacci.py +++ b/fibonacci.py @@ -1,6 +1,9 @@ #!/usr/bin/env python3 """Fibonacci sequence calculator with colored output.""" +import argparse +import sys + # ANSI color codes GREEN = "\033[32m" CYAN = "\033[36m" @@ -30,18 +33,26 @@ def fibonacci(n: int) -> int: return b -if __name__ == "__main__": - import sys - - if len(sys.argv) != 2: - print(f"Usage: {sys.argv[0]} ") - sys.exit(1) - +def main(): + parser = argparse.ArgumentParser(description="Fibonacci sequence calculator") + parser.add_argument("n", type=int, help="The position n in the Fibonacci sequence") + parser.add_argument("--output", "-o", help="Write output to a file instead of stdout") + args = parser.parse_args() + try: - n = int(sys.argv[1]) - except ValueError: - print(f"{RED}Error: '{sys.argv[1]}' is not a valid integer{RESET}") + result = fibonacci(args.n) + except ValueError as e: + print(f"{RED}Error: {e}{RESET}") sys.exit(1) - - result = fibonacci(n) - print(f"{CYAN}fibonacci({n}){RESET} {GREEN}={RESET} {GREEN}{result}{RESET}") + + output_line = f"{CYAN}fibonacci({args.n}){RESET} {GREEN}={RESET} {GREEN}{result}{RESET}" + + if args.output: + with open(args.output, "w") as f: + f.write(output_line + "\n") + else: + print(output_line) + + +if __name__ == "__main__": + main()