【问题标题】:How to break out of a while loop and make code after it not run (python) [duplicate]如何打破while循环并在它不运行后生成代码(python)[重复]
【发布时间】:2021-10-01 08:41:24
【问题描述】:

我想要做的是如果 num == 4 那么它之后的打印语句将不会运行,它将退出 while 循环

num = 3

def ifnum():
  ifnum.loop = True
  if num == 4:
    ifnum.loop = False
    print("num is 4")

ifnum()

while ifnum.loop == True:
  num = int(input())
  ifnum()
  print("If num is 4 then i dont want this code to run")
  print("same with this print statement")

【问题讨论】:

  • break 将退出循环。
  • 有没有办法将break 放入函数中?
  • 没有。 break 只能在循环内使用
  • 不,您希望该函数返回一个布尔值,然后您尝试使用 if 语句。
  • sujay,我知道,哈哈,但是有没有可以在函数中使用的替代方法

标签: python python-3.x loops while-loop break


【解决方案1】:

你可以返回结果并赋值。

num = 3

def ifnum():
  ifnum.loop = True
  if num == 4:
    ifnum.loop = False
    print("num is 4")
  return(ifnum.loop)

ifnum()

while ifnum.loop == True:
  num = int(input())
  ifnum.loop = ifnum()
  print("If num is 4 then i dont want this code to run")
  print("same with this print statement")

【讨论】:

  • 为此使用函数属性似乎有点极端 - 为什么不只是返回 True/False 并且 while 循环可以每次都简单地测试返回值……此外,将 num 传递给函数一个参数,而不是使用一个全局...简单得多
猜你喜欢
  • 1970-01-01
  • 2020-03-28
  • 2013-03-20
  • 2021-07-02
  • 2021-06-23
  • 1970-01-01
  • 2014-01-30
  • 2016-08-06
相关资源
最近更新 更多