I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says :
TypeError: %d format: a number is required, not str
from sys import argv
file_name, num1, num2 = argv
int(argv[1])
int(argv[2])
def addfunc(num1, num2):
print "This function adds %d and %d" % (num1, num2)
return num1 + num2
addsum = addfunc(num1, num2)
print "The final sum of addfunc is: " + str(addsum)
When I run filename.py 2 2, does argv put 2 2 into strings? If so, how do I convert these into integers?
Thanks for your help.
As a concept, ARGV is a convention in programming that goes back (at least) to the C language. It refers to the “argument vector,” which is basically a variable that contains the arguments passed to a program through the command line.
The type of argv[1] is char* .
The second argument to main, usually called argv, is an array of strings. A string is just an array of characters, so argv is an array of arrays. There are standard C functions that manipulate strings, so it's not too important to understand the details of argv, as long as you see a few examples of using it.
sys.argv
is indeed a list of strings. Use the int()
function to turn a string to a number, provided the string can be converted.
You need to assign the result, however:
num1 = int(argv[1])
num2 = int(argv[2])
or simply use:
num1, num2 = int(num1), int(num2)
You did call int()
but ignored the return value.
Assign the converted integers to those variables:
num1 = int(argv[1]) #assign the return int to num1
num2 = int(argv[2])
Doing just:
int(argv[1])
int(argv[2])
won't affect the original items as int
returns a new int
object, the items inside sys.argv
are not affected by that.
Yo modify the original list you can do this:
argv[1:] = [int(x) for x in argv[1:]]
file_name, num1, num2 = argv #now num1 and num2 are going to be integers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With