簡體   English   中英

如何制作 *if* 語句循環?

[英]how to make an *if* statement loop?

我是 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?")

(是的,這有點傻)有沒有辦法連續循環語句,有沒有辦法限制它循環的次數? 如果有更好的方法來做我想做的事情,那是什么?

我會將這些數據存儲在字典中,然后您可以遍歷它:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM