Python Forum
Argparse error when inputting values - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Argparse error when inputting values (/thread-29600.html)



Argparse error when inputting values - tqader - Sep-11-2020

I'm trying to resolve the errors in this code. We are trying to use argparse, and I get to num_nums = len(args.n) and I get errors. The error gets generated when reading the next line and reads as:

ERROR CODE
Error:
print("Adding %d numbers." % num_nums) TypeError: %d format: a number is required, not NoneType
I can't figure out what is failing with the %d argument that is being passed.
I am looking for assistance with the code to get it to a working state. Full code is:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", help="Number to add")
parser.add_argument("--indent", help="Indent output")

args = parser.parse_args()

num_nums = (args.n)
print("Adding %d numbers." % num_nums)
sum = 0
for n in range(0, num_nums):
    sum = sum + args.n[n]

if (args.i):
    print("\tSum = %d" % sum)
else:
    print("Sum = %d" % sum)



RE: Argparse error when inputting values - bowlofred - Sep-11-2020

First, put your code inside python tags so it is easily readable (and so indentation can be seen).

Second, how are you running it? Are you giving an argument to -n? When I do I get a str error instead of a NoneType error.

You haven't told argparse that -n is required, so it will let you run without the argument. Also, the default is to read the argument as a string. So num_nums is a string and the print won't work when you ask it to format a string with %d.

You can modify the add_argument to resolve both. Something like

parser.add_argument("-n", type=int, required=True, help="Number to add")



RE: Argparse error when inputting values - buran - Sep-11-2020

as a side note, you are using old-style string formatting, there is str.format() method and in 3.6+ - f-strings. better use f-strings.
also sum is built-in function. don't use it as name/variable.