简体   繁体   English

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

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

I got a program when input a number they show some command and when i put in number 4 i want it print goodbye and end the program.我得到一个程序,当输入一个数字时,它们会显示一些命令,当我输入数字 4 时,我希望它打印再见并结束程序。 I know there is a way is use break but my teacher dont want to use it .我知道有一种方法是使用 break 但我的老师不想使用它。 Is there any other way to end it when enter number 4 ?输入数字 4 时还有其他方法可以结束它吗? Thank in advance : PS : i just new leaner to Python.提前致谢: 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. Use a variable in the while condition: 1.在while条件中使用变量:

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

2. Raise an exception: 2. 引发异常:

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

3. Put it inside a function and return: 3. 把它放在一个函数中并返回:

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

4. Exit the program: 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"
    ...

A simple way could be:一个简单的方法可能是:

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

To exit:退出:

import sys
sys.exit(0)

If you need to break nested loops, you can put your code inside a function and then use "return None" instead of "break"如果需要中断嵌套循环,可以将代码放在函数中,然后使用“return None”而不是“break”

Well, I am also new to the platform of python but I have the answer to your question.好吧,我也是 python 平台的新手,但我有你的问题的答案。 You can use:您可以使用:

import sys          
sys.exit(0)    

Well, I hope that this might help you.嗯,我希望这可以帮助你。

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

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