1

I want it to give 'Number of donuts: many' when the argument is more than 10 and 'Number of donuts: ' when the argument is count<10. But it always gives me 'Number of donuts: many'

#!/usr/bin/python2.6 -tt
import sys
def donuts(count):
  if count < 10:
    x = str(count)
  else:
    x = 'many'
  print 'Number of donuts: ' + x

def main():
  donuts(sys.argv[1])

if __name__ == "__main__":
  main()
scwagner
  • 3,975
  • 21
  • 16
Nima Alidoust
  • 55
  • 1
  • 4

5 Answers5

6

sys.argv will only contain strings, even if you provide integers as arguments, so for example if you called this as python donuts.py 4, then sys.argv[1] would be '4' and you would attempt the comparison '4' < 10 when you actually want 4 < 10.

So first, try to convert sys.argv[1] to an int:

def main():
    donuts(int(sys.argv[1]))

You may want to add some error handling as well, in case an argument is not provided or it is not an integer:

def main():
    try:
        donuts(int(sys.argv[1]))
    except IndexError:
        print 'Missing argument'
    except ValueError:
        print 'Invalid argument'
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
5

count is a string. Try count = int(count)

bluepnume
  • 16,460
  • 8
  • 38
  • 48
3

You should convert count to an int before comparing it to 10:

#!/usr/bin/python2.6 -tt
import sys
def donuts(count):
    if int(count) < 10:
        x = count
    else:
        x = 'many'
    print 'Number of donuts: %s' % x

def main():
    donuts(sys.argv[1])

if __name__ == "__main__":
    main()
Andbdrew
  • 11,788
  • 4
  • 33
  • 37
3

Try converting the count parameter to an int for the comparison:

if int (count) < 10:
  x = str (count)
else:
  x = 'many'

Because you're passing in a string argument for the count parameter, the comparison is failing.

scwagner
  • 3,975
  • 21
  • 16
3

You don't take the input in as an integer to begin with.

Change:

def main():
  donuts(sys.argv[1])

to:

def main():
  donuts(int(sys.argv[1]))

You will run into an issue if they put in a string or decimal instead of a numerical value, though.

Makoto
  • 104,088
  • 27
  • 192
  • 230