如何创建*if*语句循环?

2024-06-18 13:10:30 发布

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

我是python新手,我只是尝试使用if语句进行简单的练习,但我希望我的语句能够循环,我拥有的是

species = "cat"
if species == "cat":
    print("yep, it's a cat")
    species = "dog"
if species == "dog":
    print("and that's a dog")
    species = "horse"
if species == "horse":
    print("look at that horse over there")
    species = "cheetah"
if species == "cheetah":
    print("WHERE DID THE CHEETAH COME FROM?")

(是的,这有点傻)有没有办法连续循环语句,有没有办法限制它循环的次数?如果有更好的方法做我想做的事情,如果是什么


Tags: andifthatit语句catspeciesprint
1条回答
网友
1楼 · 发布于 2024-06-18 13:10:30

我会将这些数据存储在字典中,然后您可以循环:

responses = {
    "cat": "yep, it's a cat",
    "dog": "and that's a dog",
    "horse": "look at that horse over there",
    "cheetah": "WHERE DID THE CHEETAH COME FROM?"
}


for species in ['cat', 'dog', 'horse', 'cheetah']:
    response = responses.get(species, 'none of those here')
    print(response)

相关问题 更多 >