1

Why does the code below produce an infinite loop? If I hard code the value of y to be equal to 10 it doesn't go on forever, yet if I enter 10 through user input it does.

x = 0
y = raw_input("Enter a Number: ")

while x <= y:
    x = x + 1
    if x %2 == 0:
        print x
    else:
        print "odd"
vaultah
  • 44,105
  • 12
  • 114
  • 143
staredecisis
  • 157
  • 2
  • 3
  • 16
  • Use `while x <= int(y):`. `raw_input()` returns a string, not an integer. – zondo Mar 14 '16 at 18:23
  • @vaultah, it's not exactly a duplicate. The asker simply doesn't know that `raw_input()` returns strings regardless of the input. – Chuck Mar 14 '16 at 18:24
  • 1
    Another dupe target: [How can I read inputs as integers in Python?](http://stackoverflow.com/q/20449427/2301450) – vaultah Mar 14 '16 at 18:25

2 Answers2

2

You might want to transform your y value, which is now a string, to a number.

For example like:

y = int(raw_input("Enter a number: "))
SiggyF
  • 22,088
  • 8
  • 43
  • 57
0

Expounding on @SiggyF's answer, modify your code to this to get rid of unnecessary lines:

y = int(raw_input("Enter a number: "))
for x in range(0, y+1):
    if x % 2 == 0:
        print(x)
    else:
        print("odd")
Chuck
  • 866
  • 6
  • 17