【问题标题】:Python if/elif issue with random.randintPython if/elif 问题与 random.randint
【发布时间】:2011-11-13 02:58:20
【问题描述】:

这是一个更大问题的一部分,但我在使用这个 if/elif 函数时遇到了一些问题。

def fish():
    import random   

    score = 0

    i = random.randint(0,39)

    if i == [0,19]:
        print("You caught nothing!")
    elif i == [20,39]:
        print("You caught a Minnow! +10 points.")
        score += 10
    print(i)
    print(score)
fish()

当我运行它时,我得到的只是随机数,0 代表分数。我不确定我在这里做错了什么。

【问题讨论】:

  • 你的问题与random.randint无关,与if/elif逻辑无关;它与比较值有关。想清楚你对i == [0, 19] 的期望是什么,以及为什么它应该是这个意思。

标签: python python-3.x


【解决方案1】:

是的,嗯……这不是它的工作原理。您正在将整数与列表进行比较。

    if 0 <= i < 20:
        print("You caught nothing!")
    elif 20 <= i < 40:
        print("You caught a Minnow! +10 points.")
        score += 10

【讨论】:

    【解决方案2】:

    您正在将整数与列表进行比较。

    要做你想做的事,这里有一种方法:

    if i in range(0, 20):
        print("You caught nothing!")
    elif i in range(20, 40):
        print("You caught a Minnow! +10 points.")
        score += 10
    

    【讨论】:

      【解决方案3】:

      你想做的是:

      if i in range(20):
          print("You caught nothing!")
      elif i in range(20,40):
          print("You caught a Minnow! +10 points.")
          score += 10
      

      或者更好:

      if i < 20:
          print("You caught nothing!")
      else:
          print("You caught a Minnow! +10 points.")
          score += 10
      

      【讨论】:

        【解决方案4】:

        i 是一个int,您将intints 的列表进行比较,您应该:

        if i in range(19)
        ...
        elif i in range(20,39):
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-05-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-03
          相关资源
          最近更新 更多