about_pet
我编写的代码:
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")
我尝试了其他一些方法,但卡住了。你能帮我解决一下吗?
提前谢谢!
谢谢大家的帮助!我挖出了课程论坛,在我看来,教练正在投球使用布尔值。即about_pet.lower()中的'dog'== True表示输入语句是否有多个宠物。我被困在这里如何利用布尔值来检查输入语句。
再次感谢大家的帮助!
答案 0 :(得分:1)
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")
答案 1 :(得分:1)
elif 'dog, cat' in about_pet.lower():
print ("Ah, there is more than one pet")
将上述条件改为下述条件:
if 'dog' in about_pet.lower() or 'cat' in about_pet.lower():
print ("Ah, there is more than one pet")
答案 2 :(得分:0)
使用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"):
import re
has_dog = re.search(r'\bdog\b',about_pet,re.IGNORECASE) # note: raw prefix before \b word boundary!
has_cat = re.search(r'\bcat\b',about_pet,re.IGNORECASE)
其余测试保持不变
答案 3 :(得分:0)
在宠物超过1只的情况下列出清单很有用。
def pet_convo():
about_pet=input('What pets do you have? ')
myList = about_pet.split(',')
if len(myList)>1:
print('Ah, you have many animals')
elif 'cat' in about_pet.lower():
print("Ah, a cat")
elif 'dog' in about_pet.lower():
print('Ah, a dog')
print('Thank you for your story')
答案 4 :(得分:0)
记住正确的位置;)
about_pet = input("Enter a sentence about a pet: ")
if "cat" in about_pet and "dog" in about_pet:
print("Ah! there is one or more pet!")
elif "cat" in about_pet:
print("Ah! a cat ")
elif "dog" in about_pet:
print("Oh! a dog ")
print("Thank you for your story!")