-3

I want to get a user input which is bigger than zero. If user enters anything else than a positive integer prompt him the message again until he does.

x = input("Enter a number:")
y= int(x)

while y<0:
    input("Enter a number:")
    if not y<0:
        break

If I add a bad value first then a good one it just keeps asking for a new one. Like Try -2 it asks again but then I give 2 and its still asking. Why?

sentence
  • 8,213
  • 4
  • 31
  • 40
PUrba
  • 7
  • 2
  • Possible duplicate of [Python: How to keep repeating a program until a specific input is obtained?](https://stackoverflow.com/questions/20337489/python-how-to-keep-repeating-a-program-until-a-specific-input-is-obtained) Also `y = int(input("Enter a number:"))` you need to assign `input()` return value to a variable – Devesh Kumar Singh Jun 12 '19 at 09:39

2 Answers2

1

You assign a value to y before the while loop, then you enter the loop without assigning a value to y from the input.

Just change your code:

x = input("Enter a number:")
y= int(x)

while y<0:
    y = int(input("Enter a number:"))
print('out?')
sentence
  • 8,213
  • 4
  • 31
  • 40
1

The first time you assign the result of input to x, and convert x to a number (int(x)) but after the second call to input you don't. That is your bug.

That you have a chance to get this bug is because your code has to repeat the same thing twice (call input and convert the result to a number). This is caused by the fact that Python unfortunately does not have the do/while construct, as you mentioned (because there was no good way to use define it using indentation and Python's simple parser, and now it's too late).

The usual way is to use while True with break:

while True:
    x = input("Enter a number:")
    y = int(x)
    if not y<0:
        break
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79