繁体   English   中英

有没有办法在不使用break的情况下结束程序?

[英]Is there anyway to end the program without using break?

我得到一个程序,当输入一个数字时,它们会显示一些命令,当我输入数字 4 时,我希望它打印再见并结束程序。 我知道有一种方法是使用 break 但我的老师不想使用它。 输入数字 4 时还有其他方法可以结束它吗? 提前致谢: PS:我刚开始学习 Python。

while True  :
     num= int(input("enter : "))

    if num == 1:
       print("encrypt text")
    elif num == 2 :
        print("decrypt text")
    elif num == 3 :
        print("Brute force decrypt")
    elif num ==4 :
        print("goodbye")
    else :
            print('false')

1.在while条件中使用变量:

num = 0
while num != 4:
    num = int(input("enter : "))    
    ... your other code

2. 引发异常:

try:
    while True:
        num = int(input("enter : "))    
        ... your other code
        elif num == 4:
            raise StopIteration 
        ...
except StopIteration as e:
     print('goodbye')

3. 把它放在一个函数中并返回:

def main():
    while True:
        num = int(input("enter : "))    
        ... your other code
        elif num == 4:
            return
        ...
main()
print('goodbye')

4.退出程序:

while True:
    num = int(input("enter : "))
    ... your other code
    elif num ==4 :
        print("goodbye")
    
        # Do any of the following
        exit()
        quit()
        raise SystemExit
        sys.exit() # requires "import sys"
    ...

一个简单的方法可能是:

number = 0
while number != 4:
    ...

退出:

import sys
sys.exit(0)

如果需要中断嵌套循环,可以将代码放在函数中,然后使用“return None”而不是“break”

好吧,我也是 python 平台的新手,但我有你的问题的答案。 您可以使用:

import sys          
sys.exit(0)    

嗯,我希望这可以帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM