-2
while True:
    a = raw_input("Your number: ")
    if a == int: # letters:
        if a > 0 and a % 3 == 0:
            print 'fizz'
        if a > 0 and a % 5 == 0:
            print 'buzz'
        if a > 0 and a % 3 != 0 and a % 5 != 0:
            print a
        if a <= 0:
            print 'bad value'
    else:
        print "Not integer, try again"`

How do I make this raw_input work? I want this to run the game when the user input is an integer and "try again" when it is not.

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

5

raw_input() always returns a string. If you want to make it an int, call the int() builtin function. If the contents of the string cannot be converted, a ValueError will be raised. You can build the logic of your program around that, if you wish.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
2

raw_input is a string. You can convert it to an int using int. If it's not convertible, this returns an error. So use try... except to handle the error. It's a good idea to put as little as possible into the try... part because otherwise some other error might be accidentally caught. Then put in a continue into the except part to skip back to the start.

while True:
    try:
        a= int(raw_input("Your number: "))
    except ValueError:
        print "not integer, try again"
        continue
    if a > 0:
        if a % 3 == 0:
            print 'fizz'
        if a % 5 == 0:
            print 'buzz'
        if a % 3 != 0 and a % 5 != 0:
            print a
    else:  #a<=0
            print 'bad value'
Joel
  • 22,598
  • 6
  • 69
  • 93