开发者

Python Adventure Game -> Chose A or B in a while loop not working!

开发者 https://www.devze.com 2023-02-16 06:10 出处:网络
I\'m trying to create a simple adventure game in Python. I\'ve come to a point where I need to ask the user if they wish to choose option A or B and am using a while loop to try and do this:

I'm trying to create a simple adventure game in Python. I've come to a point where I need to ask the user if they wish to choose option A or B and am using a while loop to try and do this:

AB = input("A or B?")

while AB != "A" or "a" or "B" or "b":
    input("Choose either A or B")

if AB == "A" or "a":
    print("A")
elif AB == "B"开发者_如何学Python or "b":
    print("B")

The thing is, no matter what you input, the question "Choose either A or B" comes up. What am I doing wrong?


Your while statement is evaluating on the conditionals or, which is always true for the strings you provided.

while AB != "A" or "a" or "B" or "b":

means:

while (AB != "A") or "a" or "B" or "b":

Non-empty strings are always True, so writing or "B" will always be true, and will always ask for input. Better to write:

while AB.lower() not in ('a','b'):


AB != "A" or "a" or "B" or "b" should be AB.upper() not in ('A','B')


AB != "A" or "a" or "B" or "b"

is interpreted as

(AB != "A") or ("a") or ("B") or ("b")

and since "a" is always true, the result of this check will always be true.


It would be better to use:

AB = raw_input("A or B?").upper()

and then the not in construct as others have suggested.


Use the raw_input() function, instead, like this:

ab = raw_input('Choose either A or B > ')
while ab.lower() not in ('a', 'b'):
    ab = raw_input('Choose either A or B > ')

input() expects a Python expression as input; according to the Python documentation, it is equivalent to eval(raw_input(prompt)). Just use raw_input(), along with the other suggestions posted here.


try:
    inp = raw_input    # Python 2.x
except NameError:
    inp = input        # Python 3.x

def chooseOneOf(msg, options, prompt=': '):
    if prompt:
        msg += prompt
    options = set([str(opt).lower() for opt in options])
    while True:
        i = inp(msg).strip().lower()
        if i in options:
            return i

ab = chooseOneOf('Choose either A or B', "ab")

lr = chooseOneOf('Left or right', ('left','right'))
0

精彩评论

暂无评论...
验证码 换一张
取 消