-1

I was following along with a video discussing the basics of using argparse by calculating a Fibonacci number. I typed the code into my pycharm editor and when I run the code I don't get any output. It completes with the following message "Process finished with exit code 0". Thoughts?

import argparse
def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a
def Main():
    parser = argparse.ArgumentParser()
    parser.add_argument("num", help="Fibonacci number to calculate", type=int)
    args = parser.parse_args()
    result = fib(args.num)
    print("The " + str(args.num) + "th fib number is " + str(result))
if __name__ == '__Main__':
    Main()
zeusbella
  • 49
  • 6
  • How exactly are you "run the code"? Do you know how to provide commandline arguments when using `pycharm`? Or even know what we mean by that? – hpaulj Jan 25 '21 at 20:48
  • While learning it's a good idea to include a `print(args`)` statement right after the `parse_args`. – hpaulj Jan 25 '21 at 20:54
  • Hi @hpaulj and thanks for the comments! Yes, I added the commandline arguments when using pychart. Also, thanks for the print(args) tip. I will use that as I continue to enhance the program. – zeusbella Jan 26 '21 at 01:44

2 Answers2

1

This line is the problem:

if __name__ == '__Main__':

When you are running the script, __name__ magic variable is set to __main__ with lowercase m. Fix it and it would work.

This great answer has plenty of details about magic variables and what does if __name__ == '__main__': line do:

https://stackoverflow.com/a/419185/12118546

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28
  • 1
    Thanks @Roman for the quick help and link!! That solved the problem and I am able to move on with adding more functionality to the program. – zeusbella Jan 25 '21 at 18:37
0

Your code should be like this:

import argparse

def fib(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("num", help="Fibonacci number to calculate", type=int)
    args = parser.parse_args()
    result = fib(args.num)
    print("The " + str(args.num) + "thw fib number is " + str(result))

if __name__ == '__main__':
    main()

When run as a program, __name__ will be set to__main__ and not __Main__. Please note also that function and variable names should always start with lowercase letters. And leave a blank line between functions, that makes the code more readable !

TheEagle
  • 5,808
  • 3
  • 11
  • 39