简体   繁体   English

Python 在不应该打印的时候打印,而打印不应该打印的内容

[英]Python is printing when it should not print, and printing what should not print


animals = [('dog','Fort','brown'), ('dog', 'Nutmeg', 'brown'), ('cat', 'Oreo', 'black'), ('cat','Tiger','brown'), ('dog', 'Taco', 'white'), ('cat', 'Menoly', 'calico')]

for animal in animals: 
    print(animal[1] + ' is a ' + animal[2] + " " + animal[0])

color = input("Please choose one of the above colors: ").lower() 

for animal in animals:
    if color in animal[2]:
        print(animal[1] + ' is ' + color)
    else:
        print('No pets are ' + color)
        break

Output should be:输出应该是:
Fort is brown堡垒是棕色的
Nutmeg is brown肉豆蔻是棕色的
Tiger is brown老虎是棕色的

Why is it printing out?:为什么会打印出来?:
Fort is brown堡垒是棕色的
Nutmeg is brown肉豆蔻是棕色的
No pets are brown没有宠物是棕色的

In your code, if the condition is not True, it breaks.在您的代码中,如果条件不为 True,则会中断。

if color == animal[2]:  #==== Use == instead of in
        print(animal[1] + ' is ' + color) 
    else:
        print('No pets are ' + color) #===== Printing this
        break #====== Break. Because the condition: color==animal[2] were not met and break broke out of the loop

You can use list comprehension and check if the list is empty or not.您可以使用列表理解并检查列表是否为空。

color = input("Please choose one of the above colors: ").lower() 
x=[animal[1]+" is "+color for animal in animals if color==animal[2]]
if x==[]:
    print('No pets are ' + color)
else:
    for j in x:
        print(j)

Your loop prints "No pets are ..." too early.你的循环打印“没有宠物是......”太早了。

Logically, it should wait to print that message after all pets have been processed and no matches were found.从逻辑上讲,它应该在处理完所有宠物且未找到匹配项后等待打印该消息。 Instead, it prints that message when the current pet does not match.相反,它会在当前宠物不匹配时打印该消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM