简体   繁体   English

While循环即使是错误也停止了吗?

[英]While loop stopping even if it's False?

I thought the logic of my while loop made sense, but it abruptly stops after the first loop. 我以为while循环的逻辑是合理的,但是在第一个循环后突然停止了。

choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
    valid = False
while valid == False:
    print("Invalid choice, please enter again")
    choice=int(input("Enter choice:"))
    return choice        
if choice ==1:
    valid=True
    display_modules_average_scores()
    menu()
elif choice ==2:
    valid=True
    display_modules_top_scorer()
    menu()
elif choice==0:
    exist=True
    print("===============================================")
    print("Thank you for using Students' Result System")
    print("===============================================")

If I enter 5, it does: 如果输入5,它会:

print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))

But if I enter 5 again, it stops the program. 但是,如果我再次输入5,它将停止程序。 What am I doing wrong? 我究竟做错了什么?

if I enter 5 again, it stops the program 如果我再次输入5,它将停止程序

Because you have a return statement that immediate ends the function you're running within. 因为您有一个return语句,该语句立即终止您正在其中运行的函数。

You seem to be trying to create an infinite loop. 您似乎正在尝试创建无限循环。 You can start with testing exit and invalid conditions with this. 您可以以此测试退出和无效条件。 Note:choice will never equal an empty string 注意:选择永远不会等于空字符串

while True:
    choice=int(input("Enter choice (0 to exit):"))
    if choice == 1:
        pass # do something 
    elif choice == 2:
        pass # do something else 
    elif choice == 0:
        break
    else:
        print("Invalid choice, please enter again")
print("Thanks") 

To exit the loop, you can use break , which executes code after the loop. 要退出循环,可以使用break ,它在循环之后执行代码。 Use return to end the function, as mentioned. 如前所述,使用return结束功能。 There is a difference 它们是有区别的

If you're running this loop inside of the menu() function, you do not need to actually call the menu function again. 如果您正在menu()函数内部运行此循环,则无需再次实际调用menu函数。 That's the point of the while loop 这就是while循环的意义

By defining the function we can perform this task easily with no code duplication. 通过定义功能,我们可以轻松执行此任务,而无需代码重复。 The Below code calls the function inputchoice() and then the inputchoice() will check the value entered by the user and if there the value is not valid then the inputchoice will call itself and the process continues untill the user enter correct input. 下面的代码调用函数inputchoice(),然后inputchoice()将检查用户输入的值,如果该值无效,则inputchoice将自行调用,然后过程继续进行,直到用户输入正确的输入为止。

def inputchoice():
   choice=int(input("Enter choice: "))
   if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
       print("Invalid choice!")
       choice = inputchoice()
   return choice

def menu():
 choice = inputchoice()   
 print(choice)
 if choice ==1:
      valid=True
      print("Do something if Valid = True")
 elif choice ==2:
      valid=True
      print("Do something if Valid = True")
 elif choice==0:
      valid=True
      print("Do something if Valid = True")

menu()  #implementing menu function

I prefer making a dictionary with your functions, keeps the code clean in my eyes. 我更喜欢用您的函数编写字典,以使代码保持干净。

Consider this code here: 在这里考虑以下代码:

def choice1():
    return 'choice1'

def choice2():
    return 'choice2'

def defaultchoice():
    return 'default'

choicedict = {
    '1': choice1,
    '2': choice2
}

while True:
    choice = input("Enter choice (0 to exit):") # maintain as str to avoid error!
    if choice == '0':
        break
    value = choicedict.get(choice, defaultchoice)()
    print(value)

Single Function Code 单一功能码

def menu():
 choice=int(input("Enter choice:"))


 if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
    print("Invalid choice, please enter again")
    menu()
 elif choice ==1:
    print("Oh, its working")
    menu()
 elif choice ==2:
    print("Oh, its working")
    menu()
 elif choice==0:
    print("===============================================")
    print("Thank you for using Students' Result System")
    print("===============================================")

menu()

Hi i would use a while loop like this. 嗨,我会使用这样的while循环。 It would seem from this assignment that we are from the same institution. 从这项任务看来,我们来自同一机构。 This is what i use for my code, I hope this helps. 这就是我使用的代码,希望对您有所帮助。

while True:
    user_input = input("Enter choice: ")
    if (user_input == "0"):
        print("=====================================================")
        print("Thank You for using Students' Result System")
        print("=====================================================")
        break
    elif(user_input == "1"):
        display_modules_average_scores()      

    elif(user_input == "2"):
        display_modules_top_scorer()
    else:
        print("Invalid choice, please enter again")

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

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