0

如果事情属实,我该如何结束我的程序?

这是我的代码

  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

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

4

4 回答 4

6

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

>>> '100' > '5'
False

并使用if而不是while,如果任何条件为真,那么您可以使用该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

另请注意,您应该if-elif-else在此处使用条件而不是仅使用if's,因为此处if将检查所有条件,但是一旦出现if-elif-else条件之一,条件就会短路(跳转到 if-elif-else 块的末尾)条件是True

于 2013-09-18T07:44:03.780 回答
1

利用

if num=='4' and count!=1:

不是

while num=='4' and count!=1:
于 2013-09-18T07:38:54.277 回答
0

添加break语句并使用数字

while (num > 0 and num < 5):
    while num == 1:
        #Do something
    while num == 2:
        #Do something
    while num == 3:
        #Do something
    if num == 4 and count != 1:
        print ("The End"); count += 1
        break
于 2013-09-18T07:46:34.933 回答
0

使用if代替while looplike,

while (num>0 and num<5):
  if num==1:
    Do something
  if num==2:
    Do something
  if num==3:
    Do something
  if num==4 and count!=1:
     print("The End")
     count= count+1
     break
于 2013-09-18T07:40:04.147 回答