Convert to integers
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('number', help='the number to take to the square')
args = parser.parse_args()
print(args.number * args.number)
$ python argparse_number.py abc
Traceback (most recent call last):
File "examples/argparse/argparse_number.py", line 10, in <module>
print(args.number * args.number)
TypeError: can't multiply sequence by non-int of type 'str'
Trying to the argument received from the command
line as an integer, we get a TypeError. The same would happen
even if a number was passed, but you could call int()
on the parameter to convert to an integer.
However there is a better solution.
The same with the following
$ python argparse_number.py 23
Traceback (most recent call last):
File "examples/argparse/argparse_number.py", line 10, in <module>
print(args.number * args.number)
TypeError: can't multiply sequence by non-int of type 'str'