If/else proper indentation inside while loop [closed]

情到浓时终转凉″ 提交于 2019-12-02 15:06:22

When you remove the indent you are using a while:else block. The else is being attached to while which means it will run if your while condition is false.

while True:
    ##some looping code
else:
    ##code to run when while is false

When you indent that line of code you attach the else to if making an if:else block. In this case else is executed when if is false.

if True:
    ##code to run if true
else
    ##code to run if false

Blocks of code in python follow the same indentation. Because "else" is part of the "while" block, it has to be at the same tab position for it to work, and looking at your code, I'd say the while:else block is what you intended. :)

Try like this:

numbers = [1, 3, 5]
position = 0

while position < len(numbers):
    number = numbers[position]
    if number % 2 == 0:
        print('Found even number', number)
        break
    else:  # break not called
        print('No even number found')
    position += 1

Here is the problem. There are two types of else statements in this case. If you align the else statement with while, the else statement is executed when the condition of the while loop becomes false.

In your code, the else statement gets executed when position < len(numbers) is not true.

Also, the syntax problem is occurring just because you have a line of code between the if and else statements, which is position += 1

If you want to use an else statement for your if statement (not for the while statement as I suggested at the beginning), you should move this line of code in between of if and else.

Try this:

while position < len(numbers):
    number = numbers[position]
    if number % 2 == 0:
        print('Found even number', number)
        break
    else:
        print('No even number found')
    position += 1

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!