if/else在while循环内正确缩进 [英] If/else proper indentation inside while loop
问题描述
大约几周后,我开始学习使用Python编程 而且我遇到了麻烦. 以下代码是一个微型程序,该程序检查列表中是否存在偶数,如果找到第一个偶数,则会跳出循环:
I started learning programming with Python about a few weeks now and I am having some trouble. The following code is a tiny program that checks whether there's an even number in a list, if it finds the first even number, it breaks out of the loop:
numbers = [1, 3, 5]
position = 0
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
position += 1
else: # break not called
print('No even number found')
显示错误:
File "test.py", line 11
else: # break not called
^
SyntaxError: invalid syntax
这是一个缩进问题,如果我删除"else"之前的选项卡,然后将其与"while"对齐,则程序运行得很好:
That's an indentation issue, if I remove the tab before "else" and so align it with 'while' the program runs really well:
while position < len(numbers):
number = numbers[position]
if number % 2 == 0:
print('Found even number', number)
break
position += 1
else:
print('No even number found')
# Prints: No even number found
我的问题是,为什么在循环内,"else"需要与"while"对齐,而不是与"if"对齐?
My question is, why does 'else' needs to be aligned with 'while' instead of being aligned with 'if' inside the loop?
这就是我想认识的家伙! 提前感谢!
That's all I want to know guys! Thanx in advance!
推荐答案
删除缩进时,您使用的是while:else块.将else附加到while上,这意味着如果while条件为false,它将运行.
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
当缩进该行代码时,如果创建if:else块,则将else附加到该行.在这种情况下,如果if为假,则执行else.
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
python中的代码块遵循相同的缩进.因为"else"是"while"块的一部分,所以它必须处于相同的选项卡位置才能工作,然后查看您的代码,我想说while:else块就是您想要的. :)
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. :)
这篇关于if/else在while循环内正确缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!