Your code has several errors in it.
While True
will do exactly that: it will loop until True
becomes False
. The problem is that your code has no way of doing that, i.e. looping infinitely.
You can either use break
after a successful input, as other answers have already provided, or you can do something like this:
x = 0
flag = True
while flag:
choice = int(input('Choose 1 or 2: '))
if choice in [1, 2]:
print('You chose', choice)
x = choice
flag = False
else:
print('I said 1 or 2.')
Initially a the boolean flag
is set to True. The while
loop checks the condition and sees that flag
is set to true, so it enters the loop.
The user's input will be taken, assigned to variable choice
, and if choice in [1, 2]:
is an easy way of checking if the input is either 1
or 2
. It checks if choice
matches any element of the list [1, 2]
. If so, then the user's input is valid.
On successful input, you assign the input to x
and then set the flag to False. The next iteration of the while
loop will again check the condition, but see that flag
is set to False, and will break itself out of the loop.
An invalid input will print but will keep flag
to True, initiating another iteration of the loop.
Your code also includes x == 0
where you meant x = 0
. What you are intending to do is assign a value to variable x
, but ==
is a boolean operator that checks for equality between two boolean expressions. You want to use the assign operator =
instead.