2

Brand new to using python, need help figuring out why my command line is spitting out huge strings of numbers and not the fib sequence up to the var I pass in. Here is what I have so far:

import sys

def fib(n):
    a, b = 0, 1
    while a < n:
        print a
        a, b = b, a+b

if __name__ == "__main__":
    fib(sys.argv[1])

Now before I did sys.argv[1] or [1:] I was able to put in a sequence in n up to the number I wanted. I.e if I entered n as 12 I would get 0,1,1,3,5,8 which is correct. However I cannot get this to work. I did a print statement after the def fib(n): as print n. It would return my sys.argv pass in.

Where am I going wrong? Thanks for your time.

2 Answers 2

6

Don't forget to convert the input argument (a string) into an integer type:

fib(int(sys.argv[1]))
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you that did work, I will close the question come min 8. If I might bother you enough, why would I need to specify that it is an integer and not have python assume that on its own if I pass in the value? Is it seeing the name of the program then the string I pass in?
@camihan In all programming languages that have some mechanism for receiving command-line arguments, they're passed as string types. Reflect on it, Python doesn't have a way to know what data type is being passed as parameter (is it a "1", a 1 or a 1.0?), so it assumes they're all strings and it's the programmer's task to convert them to the appropriate data type.
1

Try fib(int(sys.argv[1])), that might be the problem, but I didn't try it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.