Modules and fibonacci codes

I’ve been learning 6.1.1 executing modules as scripts from this site and i’m so confused. This is my code and its correct up to the <if name == “main”:> part but then i keep getting an error saying IndexError and i don’t understand why, i practically just copied the code off the site but the sites pretty confusing too… Can you pls tell me where i went wrong? thank you!

def fib(n):         #write Fibonacci series up to n

    a,b = 0,1

    while a<n:

        print(a, end = '')

        a, b = b, a+b

    print()

def fib2(n):    # return Fibonacci series up to n

    result = []

    a, b = 0,1

    while a < n:

        result.append(a)

        a, b = b, a+b

    return result

    print()

if __name__ == "__main__":

    import sys

    print(fib(int(sys.argv[1])))

here:

    print(fib(int(sys.argv[1])))

I would validate this argument actually exists. Because the user needs to (or whoever runs the program) needs to provide an argument:

python script.py 3

you just assume the argument is present

2 Likes

hey, thanks for the answer! but im a total newbie to coding so i dont get what i am supposed to do now. Could you please explain how you validate the argument step-by-step? Anyways, sorry for all the trouble :sweat_smile: and thank u again!

1 Like

haven’t done python in a while, but for example you could look at the length of sys.argv:

if len(sys.argv != 2):
   # some error
1 Like