Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argv - String into Integer

Tags:

python

argv

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.

like image 210
Andrew Blanchette Avatar asked Jun 29 '13 18:06

Andrew Blanchette


People also ask

What does * argv [] mean?

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.

What type is argv 1 in C?

The type of argv[1] is char* .

Is argv a string?

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.


2 Answers

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.

like image 188
Martijn Pieters Avatar answered Sep 28 '22 01:09

Martijn Pieters


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
like image 24
Ashwini Chaudhary Avatar answered Sep 28 '22 03:09

Ashwini Chaudhary