开发者

Fixing an Or Statement With Variables

How would I change t开发者_开发问答he below code so Python reads the list which is inside the two variables and then perform an action after that without reeving an error? My code:

bad = ['bad','terrible', 'dumb']
good = ['good','happy','awesome']
talk = raw_input("type:")
if (bad) in talk:
     print "I'm sorry to hear that :("
elif (good) in talk:
     print "That's good!"


Try this:

bad = set(['bad','terrible', 'dumb'])
good = set(['good','happy','awesome'])
talk = raw_input("type:")
if bad & set(talk.lower().split()):
     print "I'm sorry to hear that :("
elif good & set(talk.lower().split()):
     print "That's good!"


Does this get you what you want?

bad = ['bad','terrible', 'dumb']
good = ['good','happy','awesome']
talk = raw_input("type:")

talk_list = talk.lower().split()

is_bad = any(w in bad for w in talk_list)
is_good = any(w in good for w in talk_list)

if is_bad:
     print "I'm sorry to hear that :("
elif is_good:
     print "That's good!"


Use for loop and apply the same logic for 'good' too.

for badStr in bad:
    if badStr in talk:
       print "I'm sorry to hear that :("
       break

for goodStr in good:
    if goodStr in talk:
       print "That's good!"
       break
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜