if/else 在 while 循环中适当的缩进 [英] If/else proper indentation inside while loop

查看:55
本文介绍了if/else 在 while 循环中适当的缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约几周后我开始学习 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 条件为假时运行.

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

当你缩进那行代码时,你将 else 附加到 if: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆