2

I'm trying to complete an assignment regarding pygame for my computer programming class; I'm not particularly well versed in this kind of thing, so excuse me if I make some mistakes when asking my question.

I'm trying to modify some source code from our textbook, with the goal of allowing the user to set what speed a group of blocks move in a window, as well as the delay between position updates. In the beginning of the program is a while loop, designed to let the user pick between predetermined settings, or create their own.

choice = ""
while choice != "E" or "e" or "Elect" or "elect" or "ELECT" or "C" or "c" or "Create" or "create" or "CREATE" :
    choice = input("Would you like to elect a speed setting for the vectors, or create your own? (Type 'E' for elect or 'C' for create) ")

When I tried running the program in the shell, upon typing 'e', it gave me the input statement for the while loop again. Why is 'choice' not being set to my input?

totoro
  • 2,469
  • 2
  • 19
  • 23

3 Answers3

2

if choice != "E" or "e" can be explicitly translated to if (choice != "E") or ("e"). In other words, regardless of whether choice != "E" is true or false, the overall expression always returns True as "e" is not an empty string so always evaluates to True.

>>> if True or "e":
...     print("entered")
entered

>>> if False or "e":
...     print("entered")
entered

What you should do instead is:

while choice.lower() not in ("e", "elect", "c", "create"):
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
1

Your other or's evaluate to True. So, you're while condition breaks down to while choice != 'E' or True which isn't going to terminate. You need to use if choice != 'string' repeatedly, or preferrably you can just check while choice not in list_of_bad_strings

Pythonista
  • 11,377
  • 2
  • 31
  • 50
  • Oh, I think I understand that; you're saying: if choice != 'string' or choice != 'string" or choice != 'string'.... Right? – Kaleb Myers Apr 16 '16 at 17:15
1

Try:

choice = ""
while choice.lower() not in ("e", "elect", "c", "create"):
    choice = input("Would you like to elect a speed setting for the vectors,, create your own? (Type 'E' for elect, 'C' for create) ")

WHY

The problem you have is choice != "E" or "e" or ... means (choice != "E") or ("e") or (...). And "e" evaluates to True since it not None, 0, False, or an empty sequence. So your conditional is ALWAYS true.

totoro
  • 2,469
  • 2
  • 19
  • 23