-3

我一直在处理我正在处理的简单代码时遇到问题。它会询问您的姓名,以及您今天过得怎么样,并且根据您的回答,它应该执行与该回答相关联的操作。感谢您提前提供的所有帮助。

import time
print "Hello."
time.sleep(.5)
print "What's your name?"
var = raw_input()
time.sleep(.3)
print "Hello", var
time.sleep(1)
print "How are you?"
i = 0
answer1 = False
answer2 = False
answer0 = False
repeat = True
while repeat == True:
        if i == 0:
                answer = raw_input()
        if answer == "Good" or "good":
                answer1 = True
        if answer == "Bad" or "bad":
                answer2 = True
        if answer is not "good" or "Good" or "ok" or "Ok" or "OK" or "Not so good" or "not so good" or "Not so good." or "not so good.":
                answer0 = True
        if answer2 == True:
                print "That sucks."
                time.sleep(1)
                print "Well that's end of my code", var
                time.sleep(1)
                print "See ya!"
                break
        if answer1 == True:
                print "That's awesome!"
                time.sleep(1)
                print "Well that's end of my code", var
                time.sleep(1)
                print "See ya!"
                break
        if answer0 == True:
                print "I'm sorry, I didn't understand you."
                time.sleep(1.5)
                print "Are you good, ok, or not so good?"        
4

5 回答 5

15

这些条件将始终为真,因为非空字符串文字在 python 中是真实的:

if answer == "Good" or "good":
if answer == "Bad" or "bad":
if answer is not "good" or "Good" or "ok" ...:
...
# is the same as
if (something == something_else) or (True) or (True) ... :`

所以用以下代码重新编写该代码:

if answer in ("Good", "good"):
if answer not in ("good", "Good", "ok", ...):
....

或者更好的是,如果您想包含“GOOD”和其他案例变体:

if answer.lower() == "good":
if answer.lower() not in ("good", "ok", ...):
...
于 2012-06-21T12:30:43.783 回答
4

这是错误的:

if answer == "Bad" or "bad":

你可能的意思是:

if answer == "Bad" or answer == "bad":

或者

if answer in ("Bad", "bad"):
于 2012-06-21T12:30:02.600 回答
2

正如评论所说,您应该更具体地说明出了什么问题,但下面这行肯定是:

if answer is not "good" or "Good" or "ok" or "Ok" or "OK" or "Not so good" or "not so good" or "Not so good." or "not so good."

这应该看起来像

if answer not in ('good', 'Good', ...):

此外,您else有时可能会发现从句很有用。

于 2012-06-21T12:30:24.440 回答
1

用这些代替你的条件。

if i == 0:
        answer = raw_input().strip() #use strip(), because command prompt adds a \n after you hit enter
        if answer == ("Good") or answer ==("good"):
                answer1 = True
        if answer == "Bad" or answer =="bad":
                answer2 = True
于 2012-06-21T12:32:35.377 回答
1

如果您要使用逻辑运算符,请始终牢记您还需要将布尔值作为操作数。

意思是,在你的代码中

if answer == "Good" or "good":

您正在尝试比较,answer == "Good",它产生一个布尔值,和"good",它基本上是一个字符串文字。

要解决这个问题,你需要重写你的条件

if answer == "Good" or answer == "good":
于 2012-06-21T12:34:31.640 回答