Simple While True Loop And If Statements Fail To NOT Trigger
The relevant code is: while True: command = raw_input('Please enter a command: ') cls() if command == 'quit': cls() quit() break if command
Solution 1:
All of your if statements containing or
will run regardless of command
's value. This is because a string literal is evaluated as True
The condition if command == "start" or "run"
evaluates the value of command
first, then evaluates the "truthiness" of the string run
. This condition is always satisfied and will always run the code following it.
This should be changed to:
if command == "start" or command =="run":
do.something()
Solution 2:
Comparisions like
command == "print" or "optimize" or "list"
will always evaluate to True
. Python evaluates this as
(command == "print") or bool("optimize") or bool("list") # non-empty strings evaluate to True
Here is how to correct your code:
command == "print" or command == "optimize" or command == "list"
The pythonic way of writing this is:
command in ("print", "optimize", "list")
Solution 3:
Instead of typing:
command == "start" or "run"
You should type:
command == "start" or command == "run"
Because in the first case the or "run" will unconditionally evaulate to True and hence will be executed every time
Post a Comment for "Simple While True Loop And If Statements Fail To NOT Trigger"