【问题标题】:how to make an *if* statement loop?如何制作 *if* 语句循环?
【发布时间】:2020-07-20 03:38:07
【问题描述】:

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

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

【问题讨论】:

  • 尝试任何你想到的,如果它不起作用,那就问一个更专注的问题
  • 旁注.. if 语句不是循环,不能循环 if 语句,它是一个语句。循环就像forwhile 等 :) 你所拥有的是检查变量相等性,它检查每个语句中存储在特定变量中的值,例如 species
  • 你可以用elif代替很多if
  • 使用字典

标签: python python-2.7 loops if-statement


【解决方案1】:

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

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)

【讨论】:

  • 非常感谢您的帮助!它正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多