[英]Get stuck in a 'while True' loop python
I just learned about break
and return
in Python. 我刚刚了解了Python的break
和return
。
In a toy code that I wrote to get familiar with the two statements, I got stuck in a loop, but I don't know why. 在为熟悉这两个语句而编写的玩具代码中,我陷入了一个循环,但我不知道为什么。 Here is my code: 这是我的代码:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
I'm new to programming, any suggestions will be appreciated. 我是编程新手,任何建议将不胜感激。
With the for-else
construct you only enter the else
block if the for
loop does not break
, which your for
loop always does because i
inevitably becomes 3
with your range
generator. 随着for-else
构建你只能进入else
块如果for
循环不break
,这您for
循环总是这样,因为i
必然变3
你的range
产生。 Your infinite while
loop is therefore never able to reach the return
statement, which is only in the said else
block. 因此,您的while
循环无限可能永远无法到达return
语句,该语句仅在said else
块中。
nvm I'm super wrong here nvm我在这里超级错了
First of all, when you define a function in Python, any code that belongs in the function should be in the same indentation block. 首先,在Python中定义函数时,该函数中包含的所有代码都应位于同一缩进块中。 With this in mind, your code would look like this: 考虑到这一点,您的代码将如下所示:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
The next problem I see is that your else
statement isn't correctly formatted with an if
statement. 我看到的下一个问题是您的else
语句未使用if
语句正确格式化。 If you mean for it to go on the 2nd if
statement, your code would look like this: 如果您要让它在第二个if
语句上执行,则您的代码应如下所示:
def break_return():
while True:
for i in range(5):
if i < 2:
print(i)
if i == 3:
break
else:
print('i = ', i)
return 343
break_return()
This is only formatting. 这只是格式化。 But in this example, the code would only run once because it immediately returns and exits the function. 但是在此示例中,该代码仅运行一次,因为它会立即返回并退出该函数。
I think this may be a better example of using both break
and return
: 我认为这可能是同时使用break
和return
的更好示例:
def break_return(value):
for i in range(5):
print(i)
if i == 3:
break #This exits the for loop
if i == 4:
print("This won't print!")
#Won't print because the loop "breaks" before i ever becomes 4
return value * 2 #Returns the input value x 2
print(break_return(30)) #Display the return value of break_return()
This demonstrates how break
exits a for
loop and how return
can return a value from the function. 这演示了break
如何退出for
循环以及return
如何从函数中返回值。
The output of the code above is: 上面的代码输出为:
0 #Value of i
1 #Value of i
2 #Value of i
3 #Value of i
60 #The value returned by the function
Glad to hear you're learning Python! 很高兴听到您正在学习Python! It's a lot of fun, and super useful. 这很有趣,而且超级有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.