结束一个程序

use*_*042 0 python python-3.x

如果事情属实,我如何结束我的计划?

这是我的代码

  count=0

  num=input("What would you like to do [1,2,3,4]? ")
  while (num>'0' and num<'5'):
      while num=='1':
        Do something
      while num=='2':
        Do something
      While num=='3':
        Do something
      while num=='4' and count!=1:

         print("The End")
         count= count+1
Run Code Online (Sandbox Code Playgroud)

我希望程序在num为'4'时结束

Ash*_*ary 6

首先使用整数而不是字符串:

>>> '100' > '5'
False
Run Code Online (Sandbox Code Playgroud)

而使用if而不是while,如果任何条件为True,那么你可以使用该break语句来摆脱循环.

count = 0
num = int(input("What would you like to do [1,2,3,4]? "))
while 0 < num < 5:
    if num == 1:
       Do something
       ...
    if num == 4 and count != 1:
       print("The End")
       count += 1
       break          #breaks out of the `while` loop
Run Code Online (Sandbox Code Playgroud)

还要注意你应该if-elif-else在这里使用条件而不是仅仅使用条件if,因为这里if将检查所有条件,但是if-elif-else条件会短路(跳转到if-elif-else块的末尾)条件是True.