如果 - 否则缩进

时间:2015-11-14 14:14:50

标签: python if-statement for-loop indentation

我正在玩python3.5。我正在研究一个简单的代码,找到小于给定整数的素数。我错误地解决了代码,我不知道为什么。这是代码:

Chess.hs:21:30:
    Found hole ‘_’ with type: PieceType
    Relevant bindings include
      displaySquare' :: Maybe Piece -> Char (bound at Chess.hs:24:13)
      n :: Square (bound at Chess.hs:19:15)
      displaySquare :: Square -> Char (bound at Chess.hs:19:1)
    In the second argument of ‘Piece’, namely ‘_’
    In the first argument of ‘Just’, namely ‘(Piece White _)’
    In the second argument of ‘(==)’, namely ‘Just (Piece White _)’
Failed, modules loaded: none.

我似乎不明白为什么如果我像上面那样编写代码会给出正确的答案,如果我用另外一个缩进编写else语句,输出就不同了。例如:

输入数值:10

3

5

5

5

7

7

7

7

7

9

有:

n=int(input('Enter a numeric value: '))

for num in range(2, n+1):
    if num>1:
        for i in range(2, num):
            if (num%i)==0:
                break
        else:   
            print(num)

我觉得有必要提一下我刚开始学习python所以请慢慢来吧:D

1 个答案:

答案 0 :(得分:0)

elsefor相关联。缩进它使它与if进一步联系起来。

  • 如果else没有<{li},if运行后if
  • 如果else没有for
  • for运行后break

您需要后一种行为,因为如果您找到了该数字的因子,则break