【问题标题】:Equivalent to GOTO in conditions, Python相当于条件中的 GOTO,Python
【发布时间】:2011-05-25 05:20:39
【问题描述】:

既然 Python 中没有 goto 操作符,那可以用什么技术代替呢?

条件 如果为真,转到线程1,如果为假,转到线程2 在线程中,我们做了一些小的事情,然后我们转到线程 2,所有其他操作都发生在这里。

【问题讨论】:

  • 你不能跨线程跳转
  • 您的问题需要重温一遍,您能再提供一点吗?
  • 如果只根据条件运行其中的一个,为什么要将两段代码放入线程中?线程用于并行执行,这显然不会在您的场景中发生。如果我理解正确,无论如何都会执行“thread2”,因此应该根据您的条件执行“thread1”中的整个代码,然后执行“thread2”代码。
  • 另外,我见过的最伟大的科技愚人节笑话之一是为 Python 创建一个 functioning goto 模块。
  • 从下面的 cmets 看来,“goto thread”似乎是指执行一段特定的代码。 “goto”和“thread”都是具有精确语义的技术术语,与您的意思无关。因此,您的问题具有误导性和混淆性。我建议(a)你花一点时间来学习正确的术语,并且(b)你花一点精力来编辑问题,使它有意义。但是,我怀疑在 (a) 之后,您会发现您知道问题的答案。

标签: python conditional-statements goto


【解决方案1】:

据我所知,它不存在(谢天谢地),但你应该检查一下link

“goto”模块是愚人节的玩笑,于 4 月 1 日发布 2004. 是的,它有效,但它仍然是一个笑话。请不要在实际代码中使用!

【讨论】:

  • 不要把他引向 Python 编程的黑暗面 :-) 幸运的是,它写在页面上,这只是一个愚人节的玩笑。
【解决方案2】:
def thread_1():
  # Do thread_1 type stuff here.

def thread_2():
  # Do thread_2 type stuff here.

if condition:
    thread_1()

# If condition was false, just run thread_2(). 
# If it was true then thread_1() will return to this point.
thread_2()

编辑:我假设“线程”是指一段代码(也称为子例程或函数)。如果您将线程讨论为并行执行,那么您将需要在问题中提供更多详细信息。

【讨论】:

  • 是的,我的意思是一段代码。是否可以将所有这些函数放在“for”迭代中?
  • @Maks:是的,当然。您几乎可以将任何内容放入 for 循环中。
【解决方案3】:

Python 旨在支持良好的编码实践,而 GOTO 不是其中之一。如果使用不当,可能会导致程序逻辑不可读。

我建议以 Python 方式 学习编写程序代码,不要固守(有时是坏的)其他编程语言的习惯。查看 Python 文档、真正成熟的 Python 程序并学习。

【讨论】:

    【解决方案4】:

    既然 Python 中没有 goto 操作符,那可以用什么技术代替呢?

    从逻辑和语义上构建您的代码。

    if condition:
        perform_some_action()
    
    perform_other_actions()
    

    【讨论】:

      【解决方案5】:
      def thread1():
          #write your thread 1 code here
      
          print("entered no is 1")
      
      def thread2():
          #write your thread 2 code here
          print("Number is greater or less then one.")
      
      def main():
         a=input()
         if a==1:
         thread1()
         elif a<=1 or a>=1:
         thread2()
          #you can use recursion here in case if you want to use agin and again
          #if you want to print serveral time you can use looping.
          for i in range(4):
              main()
          #if you want to run goto forever and ever and ever then remove loop in 
          #this code.
      
      #this code will enable you the equivalent of goto statement.
      

      这是我每次在 Python 3.x 中使用的。

      【讨论】:

        猜你喜欢
        • 2013-09-22
        • 1970-01-01
        • 2012-03-02
        • 2019-08-06
        • 1970-01-01
        • 1970-01-01
        • 2016-05-08
        • 2011-06-05
        • 2012-08-25
        相关资源
        最近更新 更多