我一直在处理一个我正在处理的简单代码的问题。它询问你的名字,以及你的一天如何,根据你的答案,它应该做与该答案相关的行动。感谢您提前获得所有帮助。
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?"
答案 0 :(得分: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", ...):
...
答案 1 :(得分:4)
这是错误的:
if answer == "Bad" or "bad":
你可能意味着:
if answer == "Bad" or answer == "bad":
或
if answer in ("Bad", "bad"):
答案 2 :(得分: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
子句有用。
答案 3 :(得分: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
答案 4 :(得分:1)
如果您要使用逻辑运算符,请始终记住您还需要将布尔值作为操作数。
意思,在你的代码中
if answer == "Good" or "good":
您正在尝试比较,answer == "Good"
,它产生一个布尔值,"good"
,它基本上是一个字符串文字。
要解决此问题,您需要重写条件
if answer == "Good" or answer == "good":