duanmie9682 2019-07-30 18:53 采纳率: 100%
浏览 50

如何进行For-Else循环(使用其他语言的Else-Else)?

A while back I have read/seen that you can do a For-Else loop in Go, but now I cannot find the correct syntax anymore. I find it a very useful construct, and would like to have it in my toolbelt.

For a python example of what I mean see http://www.yourownlinux.com/2016/12/python-while-else-loop-break-continue-statement.html .

while myVar <= 10 :
     myVar == myNum :
             print 'Breaking out of the loop'
             break
     print 'This number = ' + str(myVar)
     myVar += 1
 else:
     print 'Break statement is executed, printing "else" block'
  • 写回答

1条回答 默认 最新

  • du13932014807 2019-07-30 21:08
    关注

    Python 3.7.4 documentation

    8.2. The while statement

    The while statement is used for repeated execution as long as an expression is true:

    while_stmt ::=  "while" expression ":" suite
                    ["else" ":" suite]
    

    This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

    A break statement executed in the first suite terminates the loop without executing the else clause’s suite.


    Your code:

    while myVar <= 10 :
         myVar == myNum :
                 print 'Breaking out of the loop'
                 break
         print 'This number = ' + str(myVar)
         myVar += 1
     else:
         print 'Break statement is executed, printing "else" block'
    

    Your example, in Go,

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        var myNum int = 7
        var myVar int = 0
        for {
            if myVar <= 10 {
                if myVar == myNum {
                    fmt.Println("Breaking out of the loop")
                    break
                }
                fmt.Println("This number = " + strconv.Itoa(myVar))
                myVar++
            } else {
                fmt.Println(`"while" "else" block`)
                break
            }
        }
    }
    

    Playground: https://play.golang.org/p/MkwhWfL4cr6

    Output:

    This number = 0
    This number = 1
    This number = 2
    This number = 3
    This number = 4
    This number = 5
    This number = 6
    Breaking out of the loop
    
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计