Question

I am having an issue with putting a dynamic number of arguments into a list, then being able to access them later. Here is the code. I am passing arguments such as '2,3,4,5'

def puesdoPrime(*args):
    from string import ascii_lowercase
    primeInput = []
    print "puesdoPrime not yet implemeneted"
    for arg in args:
        primeInput.append(arg)

    for i in primeInput:
        print "primeInput value are %i" % primeInput[i]

I am getting the following error:

Traceback (most recent call last):
  File "homework3.py", line 41, in <module>
    main()  
  File "homework3.py", line 34, in main
    puesdoPrime(printInput)
  File "homework3.py", line 15, in puesdoPrime
    print "primeInput value are %i" % primeInput[i]
TypeError: list indices must be integers, not tuple

This is how the function is being called:

userInput = input()
    if userInput == 1:
        print "What numbers do you want to find that are simultaneously Puesdo Prime?"
        printInput = input()
        puesdoPrime(printInput)

Any help would be very much appreciated in helping solve this.

Était-ce utile?

La solution

Using for i in primeInput will loop over the values of your list, not the indices. So you would want to change your second for loop to the following:

for item in primeInput:
    print "primeInput value are %i" % item

Or to loop over the indices:

for i in range(len(primeInput)):
    print "primeInput value are %i" % primeInput[i]

It would also help to see how you are calling puesdoPrime(), but to use *args correctly your call should look something like the following:

puesdoPrime(2, 3, 4, 5)

Or if you have an existing collection of arguments:

the_args = (2, 3, 4, 5)
puesdoPrime(*the_args)

Without the * in the previous code you would only be passing a single argument which would be a four element tuple.

As a side note, I think you mean "pseudo", not "puesdo".

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top