[英]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.