1

How to make the program choose a value from 1 to 100? The program cannot print the correct value

while True:
    regage = raw_input('Enter your age:')
    if regage not in range(1,100):
        print 'Please put an apropriate number for your age'
    else:
        print 'you are', regage,'years old'
Eutos
  • 19
  • 8
  • you mean you want to break out of the while True if the age is within 1 to 100? Then just put a "break" statement within that final else statement. https://docs.python.org/2/reference/simple_stmts.html#break – hft Sep 21 '15 at 01:30
  • No. i mean i can pick a value from 1 to 100 not more or less and can print the value that i pick – Eutos Sep 21 '15 at 01:32
  • 1
    Tough luck on your 101-year-old users, huh? – nekomatic Sep 21 '15 at 08:51
  • Nope. I'm still 101 years too early to be a coder – Eutos Sep 21 '15 at 09:37
  • You can use `1 <= regage <= 100` instead of `range(1,100)`. – Psytho Sep 21 '15 at 09:44

1 Answers1

0

This should work. The problem was that raw_input returns a string, so the value should be converted to an integer before you can check if it's in the array of integers that range returns.

while True:
    regage = raw_input('Enter your age:')
    if int(regage) not in range(1,101):
        print 'Please put an apropriate number for your age'
    else:
        print 'you are', regage,'years old'

Also, I changed the range to include 100.

Jason
  • 2,553
  • 2
  • 9
  • 17
  • 1
    The answer is incorrect. `range(1,100)` generates integers from 1 to 99, excluding 100. Test your code with 100 and you will see. Also, note that `range` generates a list of integers. If the range was larger (like checking 1 to 1,000,000) this would be noticeably inefficient. There is no reason to use `range` -- just use an `if x>1 and x<101` style test. – Chris Johnson Sep 21 '15 at 02:48
  • @ChrisJohnson Interestingly, if this were Python3 this would be just as efficient as the alternative you suggest: see [here](http://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3). But on Python2 (which the tag says it is) you are absolutely correct. – SethMMorton Sep 21 '15 at 05:54