使用“if”而不是“else”来完成此操作

2024-04-24 22:42:56 发布

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

又是新手了。我正试图完成以下问题,但仍以粗体字表示:

  • 在变量中获取用户输入:about_pet
  • 使用一系列的if语句以适当的对话进行回应
  • 检查“dog”是否在关于_pet的字符串中(示例回答“Ah,a dog”)
  • 检查“猫”是否在“宠物”的字符串中
  • 检查是否有一个或多个动物是关于“宠物”的字符串
  • 不需要其他的
  • 最后感谢你的故事

我写的代码:

about_pet = input("Enter a sentence about a pet: ")

if 'dog' in about_pet.lower():
    print ("Ah, a dog")
if 'cat' in about_pet.lower():
    print ("Ah, a cat")
elif 'dog, cat' in about_pet.lower():
      print ("Ah, there is one or more pet")

print("Thank you for your story")

我没试过别的办法,但还是坚持住了。你能帮我解决这个问题吗?在

提前谢谢你!在

谢谢大家的帮助!我翻开了课程论坛,在我看来,老师在推销布尔函数。i、 “狗”在附近_宠物。下()==True,验证输入语句是否有多个pet。我被困在这里如何利用布尔来检查输入语句。在

再次感谢大家的帮助!在


Tags: 字符串用户in宠物if语句lowercat
3条回答
if 'dog' in about_pet.lower():
print ("Ah, a dog")
if 'cat' in about_pet.lower():
    print ("Ah, a cat")
if 'dog' in about_pet.lower() or 'cat' in about_pet.lower():
      print ("Ah, there is one or more pets")
elif 'dog, cat' in about_pet.lower():
    print ("Ah, there is more than one pet")

将上述条件改为下述条件:

^{pr2}$

这个使用2个标志和条件优化的简单逻辑如何(好吧,有一个else,但这只是节省了一些测试,没有else的编码是一个不合理的约束):

about_pet = about_pet.lower()
has_dog = 'dog' in about_pet
has_cat = 'cat' in about_pet

if has_dog:
    if has_cat:
        print ("Ah, there is more than one pet")
    else:
        print ("Ah, a dog")
elif has_cat:
    print ("Ah, a cat")

请注意,单词边界正则表达式最好避免在单词中匹配(如“caterpillar”):

^{pr2}$

其余测试保持不变

相关问题 更多 >