-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?

1

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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?') 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.