Argv - String in the Whole

I am new to python and I played with argv. I wrote this simple program here and received an error message:

TypeError: format% d: 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 in lines? If so, how do I convert them to integers?

Thank you for your help.

+6
source share
3 answers

sys.argv really is a list of strings. Use the int() function to turn a string into a number if the string can be converted.

However, you need to assign a result:

 num1 = int(argv[1]) num2 = int(argv[2]) 

or just use:

 num1, num2 = int(num1), int(num2) 

You called int() but ignored the return value.

+9
source

Assign the converted integers to these variables:

 num1 = int(argv[1]) #assign the return int to num1 num2 = int(argv[2]) 

The execution is simple:

 int(argv[1]) int(argv[2]) 

does not affect the original elements, since int returns a new int object, elements inside sys.argv do not affect this.

Yo change the original list you can do:

 argv[1:] = [int(x) for x in argv[1:]] file_name, num1, num2 = argv #now num1 and num2 are going to be integers 
+4
source

Running int(argv[1]) does not actually change the value of argv[1] (or num1 to which it is assigned).

Replace this:

 int(argv[1]) int(argv[2]) 

Wherein:

 num1 = int(num1) num2 = int(num2) 

and it should work.

Functions int (..), str (...), etc. Do not change the values ​​passed to them. Instead, they return the reinterpretation of the data as another type.

+1
source

Source: https://habr.com/ru/post/948392/


All Articles