Python编程决策结构

2024-09-30 16:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

通常,当我编程和使用决策结构(以及原始输入)时,我选择的答案会被忽略并转到第一个“if”语句并显示该语句的输出。在

在课堂上,我们必须使用循环和决策结构创建一个游戏。当我运行这个程序时,我经常遇到程序输出“if”语句的输出而不是用户选择的答案的问题。在

例如:

score=0
while True:

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


    if (optionOne=="one" or "One" or "ONE"):
        print "You have succesfully sneaked out without alerting your parents!"
        print "Your current score is " + str(score)
        break
    elif (optionOne=="two" or "Two" or "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=="three" or "Three" or "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

在这里,尽管用户选择了第二个选项,但使用了第一个“if”语句的输出。我搞不清是什么语法错误或错误,我犯了这一切发生。在


Tags: ortoyourifis语句current结构
2条回答

你必须这么做

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

或更短-将文本转换为小写

^{pr2}$

{cd1>你可以用不同的词

optionOne = optionOne.lower()

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

顺便说一句:代码

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

被视为

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

并且"One"(和"ONE")被视为True,所以你有

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

总是True

错误在这里: if (optionOne=="one" or "One" or "ONE"):

在Python中,空字符串(或序列)被视为False,而字符串(或带值的序列)被视为True。在

>>> bool('')
False

>>> bool('One')
True

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

在上面的比较中,'two'=='one'False,但是{}将返回{},即{}。在

这样实施:

^{pr2}$

相关问题 更多 >