Hi there.

I am trying write a module that can be executed at the command line and for some reason it's not working. Does anyone know why?

import sys

def fibonacci(N):
	a,b =0,1
	while b < N:
		a,b = b, a+b
		print b

N=sys.argv[1]

Does it matter that I'm running it on a windows command prompt?

Dani AI

Generated

A few quick, practical points that tie the replies together and explain why the original run failed (Windows is not the problem).

sys.argv is a list of strings where the first element is the script name, so trying to read a numeric value from the wrong index or when no argument was given will raise an error. The string you get must be parsed to a numeric type before doing numeric comparisons. Also be aware of interpreter differences: print is a function in Python 3, and syntax will differ from Python 2. correctly pointed at argv indexing, highlighted the need for numeric conversion, and ’s script-vs-module distinction is useful — protect runnable code with the usual main guard so the file can also be imported.

A more robust, maintainable pattern is to let a small argument-parsing tool validate and convert the input for you and to isolate the Fibonacci logic from the I/O. This avoids IndexError/ValueError and produces a friendlier usage message when the user calls the script incorrectly.

Example pattern (Python 3) that validates input and prints Fibonacci numbers:

import argparse

def fib(limit):
    a, b = 0, 1
    while b < limit:
        yield b
        a, b = b, a + b

if __name__ == "__main__":
    p = argparse.ArgumentParser(description="Print Fibonacci numbers less than LIMIT")
    p.add_argument("limit", type=int, help="upper bound (exclusive)")
    args = p.parse_args()
    for n in fib(args.limit):
        print(n)

Troubleshooting checklist: run the script explicitly with the intended interpreter (e.g. python script.py 10), check python --version if syntax errors occur, test with debug prints of sys.argv to see what is actually passed, and avoid indexing tricks like grabbing the last element unless you know there will be arguments.

Recommended Answers

All 4 Replies

Try this:
sys.argv[0]
or
sys.argv[-1]
that should work.

Thank you all very much! This worked for me:

import sys

N = int(sys.argv[1])

a,b =0,1
while b < N:
	a,b = b, a+b
	print b

I would prefer to call your nice, little code script, not module. Module I call code, which is imported to other Python code to call useful functions from it. Script is something traditional C coding like stdin to stdout input/output or using command arguments from invocation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.