The following Python code generates the first n numbers in the Fibonacci sequence. The code is straightforward and returns a list as the output. To run this code, provide the value of n as a command-line argument:
python fibo.py 10
Here, fibo.py is the name of the program containing the code. If you use a different filename, replace fibo.py with your program’s name. The number 10 specifies how many terms you want in the Fibonacci sequence.
import sys
def generate_fibonacci(n):
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
return fib_sequence[:n]
def main():
"""
this program generate first n numbers in the Fibonacci sequence
"""
# provide the number as command-line argument
args = sys.argv
# check if user provided a number or not
if len(args) < 2:
print("no number provided")
else:
num = int(args[1])
if num > 0:
print(f"the first {num} terms of the Fibonacci sequence are: {generate_fibonacci(num)}")
else:
print("please enter a positive integer")
if __name__ == "__main__":
main()
Please let me know in the comments if you find any errors in the code.