Is this condition is wrong or the comparison?

Question:

For any argument I pass, the result is wrong input only

script.py:-

    try:
        command_line = sys.argv[1].strip()
    except IndexError:
        print "n***PLEASE READ THE HEADER NOTE FOR RUNNING THIS PROGRAM***n"
        exit(1)

    if command_line != "run" or command_line != "fullrun":
        print "n***WRONG INPUT, PLEASE READ THE HEADER NOTE FOR RUNNING THIS
 PROGRAM***n"
        exit(1)

output:-

$script.py run

***WRONG INPUT, PLEASE READ THE HEADER NOTE FOR RUNNING THIS PROGRAM***

What is wrong with the comparison or condition?

Asked By: SeasonedNoob

||

Answers:

You have your boolean logic wrong. Use and:

if command_line != "run" and command_line != "fullrun":

You are saying that if the user did not enter run or they did not enter fullrun, the command is wrong. But if I enter run I didn’t enter fullrun and vice versa, making one of the two conditions always true.

You may want to use not in and a set instead:

if command_line not in {"run", "fullrun"}:

This is a lot more readable.

Answered By: Martijn Pieters

if command_line != “run” and command_line != “fullrun”:

will work better! 🙂

You are using or but either condition will always be true in such case.

Also, I suggest you take a look at the argparse module which will help you to make nicely featured arguments handling and help summaries.

https://docs.python.org/2/library/argparse.html#module-argparse

Answered By: Fabien
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.