2

in windows: I would like this program to run on commandline. However, I am getting an error. What am I doing wrong?

# create a method that append the letter stored in variable letter, ntimes.

import sys
def appender(letter,ntimes, sentence):
    print sentence+(letter*ntimes)


appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))

The below is the error i get from command line in windows

C:\Users\QamarAli\Documents\afaq's stuff>appender.py "F" 10 "Hello this is sent"

Traceback (most recent call last):
  File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 8, in <modul
e>
    appender(str(sys.argv[1]),sys.argv[2], str(sys.argv[3]))
  File "C:\Users\QamarAli\Documents\afaq's stuff\appender.py", line 5, in append
er
    print sentence+(letter*ntimes)
TypeError: can't multiply sequence by non-int of type 'str'

C:\Users\QamarAli\Documents\afaq's stuff>
Foon
  • 6,148
  • 11
  • 40
  • 42
Afaq Qamar
  • 39
  • 5

3 Answers3

5

The error is pretty clear:

TypeError: can't multiply sequence by non-int of type 'str'

You're trying to multiply a sequence (in this case, a string) by something that isn't a number. Convert your argument to an integer:

appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])

Also, sys.argv arguments are strings by default, so there's no need to explicitly convert them again.

Blender
  • 289,723
  • 53
  • 439
  • 496
3

The values in sys.argv are all strings. Instead of trying to convert some to strings, you need to convert the other ones to whatever non-string types you need. If you want the middle one to be an integer, call int on it.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

All commandline arguments are seen by Python as strings.

Change your call to

appender(sys.argv[1], int(sys.argv[2]), sys.argv[3])
Ray Toal
  • 86,166
  • 18
  • 182
  • 232