Skip to content Skip to sidebar Skip to footer

Python Programming Decision Structures

Often when I do programming and use decisions structures (along with raw input), the answer I pick is ignored and goes to the first 'if' statement and displays the output for that.

Solution 1:

You have to do

if optionOne == "one" or optionOne == "One" or optionOne == "ONE":

or shorter - converting text to lower case

optionOne = optionOne.lower()

if optionOne == "one":
    # ...
elif optionOne == "two":
    # ...

If you have different words then you can use in

optionOne = optionOne.lower()

if optionOne in ("one", "1"):
    # ...
elif optionOne in ("two", "2"):
    # ...

BTW: Code

if optionOne=="one" or "One" or "ONE":

is treated as

if (optionOne == "one") or ("One") or ("ONE")

and "One" (and "ONE") is treated as True so you have

if (optionOne == "one") or True or True:

which always is True


Solution 2:

The error is here: if (optionOne=="one" or "One" or "ONE"):

In Python an empty string(or sequence) is considered False while a string(or sequence with values) is considered True.

>>> bool('')
False

>>> bool('One')
True

>>>'two'=='one' or 'One' or "ONE"
'One'

In above comparison 'two'=='one' is False but False or 'One' will return 'One' which is True.

Implement it like this:

score=0
while True:

    optionOne=raw_input("Please pick one of the options!")


    if (optionOne in ["one", "One", "ONE"]):
        print "You have succesfully sneaked out without alerting your parents!"
        print "Your current score is " + str(score)
        break
    elif (optionOne in ["two", "Two", "TWO"]):
        print "Due to stress from work, your mom does not notice your lies and allows you to leave."
        print "Your current score is " + str(score)
        break
    elif (optionOne in ["three", "Three", "THREE"]):
        print "Your mom is understanding and allows you go to the party!"
        score=score+10
        print "You get 10 additional points for being honest!"
        print "Your current score is " + str(score)
        break

Post a Comment for "Python Programming Decision Structures"