循环也不会停止循环循环

发布于 2025-02-07 14:41:01 字数 336 浏览 1 评论 0原文

在我的代码中,我必须向用户询问一些输入。满足条件时,程序应停止运行!

ALIVE = True

def you_died():
    global ALIVE
    ALIVE = False

def some_input():
    choice = input()
    if choice == "yes":
        you_died()

while ALIVE is True:
    some_input()
    print("some string")

为什么我的代码仍在打印“一些字符串”,即使变量活着是错误的?

如何从功能内部打破循环?

In my code I have to ask users some input. When a condition is met the program should stop running!

ALIVE = True

def you_died():
    global ALIVE
    ALIVE = False

def some_input():
    choice = input()
    if choice == "yes":
        you_died()

while ALIVE is True:
    some_input()
    print("some string")

Why is my code still printing "some string" even though the variable ALIVE is False?

How to break the loop from inside the function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

述情 2025-02-14 14:41:01

尽管每次迭代一次评估条件,因此更改条件中使用的变量不会导致其立即破裂。另外,您不能break从函数内部进行。但是,您可以在调用功能后测试全局并在执行其他循环中执行其他任何步骤之前打破函数:

ALIVE = True

def you_died():
    global ALIVE
    ALIVE = False

def some_input():
    choice = input()
    if choice == "yes":
        you_died()

while ALIVE is True:
    some_input()
    if not ALIVE: break
    print("some string")

While conditions are evaluated once per iteration so changing the variable that is used in the condition won't cause it to immediately break. Also, you can't break from within a function. BUT you CAN test your global after calling your function and break if it isn't true before performing any other steps in your while loop:

ALIVE = True

def you_died():
    global ALIVE
    ALIVE = False

def some_input():
    choice = input()
    if choice == "yes":
        you_died()

while ALIVE is True:
    some_input()
    if not ALIVE: break
    print("some string")
后eg是否自 2025-02-14 14:41:01

只有break,异常可以在执行的中间停止循环。否则,即使条件不再正确,当前的迭代也将完成:

  1. 检查条件。这是true,因此开始第一迭代。
  2. 调用some_input修改Alive,因此条件不再正确。但是,现在还不是时候检查情况了!
  3. 运行循环的其他语句,例如print(stupt)
  4. ...
  5. 一旦循环中没有更多代码(第一次迭代完成),请再次检查条件。
  6. 它是false,因此停止循环。

基本上,循环以与书面形式相同的方式执行:

  1. 检查条件。如果true,<代码> goto 2 。否则跳过整个循环(goto 4)。
  2. 开始执行循环主体(循环内的代码)。
    1. 如果偶然发现了break语句,请跳出当前循环:goto 4
    2. 如果有例外,请打断我们正在做的所有事情,并传播例外,直到在某个地方处理。如果没有处理,请完全停止执行。
  3. 循环主体执行后,goto 1
  4. 循环后执行代码...

Only break and exceptions can stop loops in the middle of execution. Otherwise, the current iteration will complete even if the condition is no longer true:

  1. Check condition. It's True, so begin 1st iteration.
  2. Call some_input which modifies ALIVE, so the condition isn't true anymore. However, it's not time to check the condition yet!
  3. Run other statements of the loop, like print(stuff)
  4. ...
  5. Once there's no more code in the loop (the 1st iteration is done), check the condition again.
  6. It's False, so stop the loop.

Basically, a loop is executed in the same manner that it's written:

  1. Check condition. If True, goto 2. Otherwise skip the entire loop (goto 4).
  2. Start executing the loop body (code that's within the loop).
    1. If stumbled upon a break statement, jump out of the current loop: goto 4.
    2. If there's an exception, interrupt everything we're doing and propagate the exception until it's handled somewhere. If it's not handled, stop execution entirely.
  3. Once the loop body is executed, goto 1.
  4. Execute code after the loop...
枯寂 2025-02-14 14:41:01

您在调用 some_input()之后打印,在循环重新启动之前和Alive时,都没有机会可以让循环进行 Alive 决定不在调用some_input()和执行print之间不重复。

一个简单的修复程序是在循环启动之前调用一次some_input(),以便Alive在第一个some_input()。 >调用,然后在循环末尾(而不是开始)调用some_input(),以便在再次打印之前重新评估active

some_input()
while ALIVE:  # no need to say "is True"
    print("some string")
    some_input()

一种更好的方法组织此代码将是让您的函数告诉您是否死亡(通过其返回值,而不是global),而break立即循环(如果是)。这使您可以在true 时使用简单的,依靠break在适当的时间停止循环:

def you_died():
    """Asks for input, returns True if you died."""
    return input() == "yes"

while True:
    if you_died():
        break
    print("some string")

You print "some string" after calling some_input(), before the loop restarts and ALIVE is checked, so there's no opportunity for the loop to decide not to repeat in between calling some_input() and doing the print.

A simple fix would be to call some_input() once before your loop starts, so that ALIVE is initialized with the result of the first some_input() call, and then call some_input() at the end of the loop (not the beginning) so that ALIVE is re-evaluated before you print again:

some_input()
while ALIVE:  # no need to say "is True"
    print("some string")
    some_input()

A better way to organize this code would be to have your function tell you if you died (via its return value, not a global), and break the loop immediately if so. This allows you to use a simple while True, relying on the break to stop the loop at the appropriate time:

def you_died():
    """Asks for input, returns True if you died."""
    return input() == "yes"

while True:
    if you_died():
        break
    print("some string")
只怪假的太真实 2025-02-14 14:41:01

Alive变量更改为false,只会停止执行新迭代的语句。

如果要print(“一些字符串”)语句才能仅在
用户回答了“是”以外的其他内容,对当前实现的更改很小,您可以将print移至some_input喜欢:


ALIVE = True

def you_died():
   global ALIVE
   ALIVE = False

def some_input():
   choice = input()
   if choice == "yes":
       you_died()
   else:
       print("some string")


while ALIVE is True:
   some_input()
   

但是,我强烈建议您不要使用这种方法。原因如下:

  1. 全局变量:使用全局变量会导致隐藏的副作用。对于较大的程序,很容易丢失可能使用并更改您的Alive变量的所有代码片段。从长远来看,全球变量的过度使用将导致复杂性的增加。由于您已经定义了该函数,因此you_died专门处理停止while/loop语句的过程,您可能需要通过定义Alive 输入参数,将其更改为false并返回其新值。

  2. “是” vs是“是”:您是否希望您的程序在用户回答“是”或“是”,“是的”,甚至是“是!”吗?如果是这样,也许更改如果选择==“是”:...之类更强大的方法。


考虑到两个上述要点,这是有关如何重新编写代码的建议:


def some_input(case_insensitive: bool = True) -> bool:
    """Ask User for input, and return `True` if they answer something other than "yes".

    Parameters
    ----------
    case_insensitive: bool, default = True
        Whether to consider User's input case-sensitive or not, when checking
        looking for replies equal to "yes". For example, if `case_insensitive` is set to
        `True`, then the function considers "yes", "Yes", and "YES" as the same
        answer.
    
    Returns
    -------
    bool
        `True`, if User inputs anything that doesn't contain the word "yes".
    """
    choice = input()
    if case_insensitive:
        choice = choice.lower()
    return "yes" not in choice


# Only enters the while statement, if the user
# answers something other than "yes" (e.g., "no") 
while some_input():
    print("some string")

Changing the ALIVE variable to False, will only stop the while statement of executing a new iteration.

If you want the print("some string") statement to only execute when the
user answers something other than "yes", with minimal changes to your current implementation, you can move the print to some_input like so:


ALIVE = True

def you_died():
   global ALIVE
   ALIVE = False

def some_input():
   choice = input()
   if choice == "yes":
       you_died()
   else:
       print("some string")


while ALIVE is True:
   some_input()
   

However, I strongly advise you not to use this approach. Here's why:

  1. Global variables: The use of global variables leads to hidden side effects. For larger programs, it's easy to lose track of all the pieces of code that might be using and altering your ALIVE variable. In the long run, overuse of global variable will lead to an increase in complexity. Since you've defined the function, you_died to specifically handle the process of stopping your while/loop statement, you might want to maximize the pros of functions by defining an alive input parameter to it, changing it to False and returning its new value.

  2. "Yes" vs "yes": would you like your program to stop the while statement, when the user answers "yes", or "YES", "Yes", and even "Yes!"? If so, perhaps changing if choice == "yes":... to something like if "yes" in choice.lower():... might be a more robust approach.

Taking into account both aforementioned points, here's a suggestion on how you might want to re-write your code:


def some_input(case_insensitive: bool = True) -> bool:
    """Ask User for input, and return `True` if they answer something other than "yes".

    Parameters
    ----------
    case_insensitive: bool, default = True
        Whether to consider User's input case-sensitive or not, when checking
        looking for replies equal to "yes". For example, if `case_insensitive` is set to
        `True`, then the function considers "yes", "Yes", and "YES" as the same
        answer.
    
    Returns
    -------
    bool
        `True`, if User inputs anything that doesn't contain the word "yes".
    """
    choice = input()
    if case_insensitive:
        choice = choice.lower()
    return "yes" not in choice


# Only enters the while statement, if the user
# answers something other than "yes" (e.g., "no") 
while some_input():
    print("some string")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文