Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使该程序无限循环,直到输入特定的整数4?_Python_Loops_While Loop - Fatal编程技术网

Python 如何使该程序无限循环,直到输入特定的整数4?

Python 如何使该程序无限循环,直到输入特定的整数4?,python,loops,while-loop,Python,Loops,While Loop,这是一个大型Python程序的函数。如何使其连续循环直到输入“4”?非常感谢您的帮助 print("\nEnter a number (1) - (4). (4) terminates the program.") choice = int(input("Enter your choice: ")) while((choice != 1) and (choice != 2) and (choice != 3) and (choice != 4)): choice = int(i

这是一个大型Python程序的函数。如何使其连续循环直到输入“4”?非常感谢您的帮助

print("\nEnter a number (1) - (4). (4) terminates the program.")
choice = int(input("Enter your choice: "))

while((choice != 1) and (choice != 2) and (choice != 3) and (choice != 4)):
        choice = int(input("\nInvalid option. Enter a number from the menu: "))

if(choice == 1):
        f = open("dna1.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal:   {0}" .format(contents))

if(choice == 2):
        f = open("dna2.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal: {0}" .format(contents))

if(choice == 3):
        f = open("dna3.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal: {0}" .format(contents))

if(choice == 4):
        print("Exiting program.")
        sys.exit

您是否尝试过使用continue和break语句,我的意思是在while循环中不说条件,您可以说

while(True):
      if(condition met):
           break
      elif(condition):
           continue

您可能应该在除最后一条之外的所有语句下添加continue(继续)

只需将所有语句包装在一个
中,而True
,还可以考虑使用
elif
,因为您的选择将是所有语句中的一个,所以不要检查下一个语句是否成功,您可以使用数组简化
while/choice

此外,我建议您重构以避免检查模式、读取文件、保存内容、打印内容的部分的重复代码(如果可以)

while True:
    while choice not in [1, 2, 3, 4]:
        choice = int(input("\nInvalid option. Enter a number from the menu: "))

    if choice == 1:
        ...
    elif choice == 2:
        ...
    elif choice == 3:
        ...
    elif choice == 4:
        print("Exiting program.")
        sys.exit(1)
或者在末尾添加一个
else
,然后移除内环

while True:
    choice = int(input(" Enter a number from the menu: "))
    if choice == 1:
        ...
    elif choice == 2:
        ...
    elif choice == 3:
        ...
    elif choice == 4:
        print("Exiting program.")
        sys.exit(1)
    else:
        print("\nInvalid option. Enter a number from the menu: ")

您可以改进这段代码,但问题是,只需将初始循环包装到另一个循环中即可

print("\nEnter a number (1) - (4). (4) terminates the program.")
choice = int(input("Enter your choice: "))


while True:

    while ((choice != 1) and (choice != 2) and (choice != 3) and (choice != 4)):
        choice = int(input("\nInvalid option. Enter a number from the menu: "))

    if (choice == 1):
        f = open("dna1.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal:   {0}".format(contents))

    if (choice == 2):
        f = open("dna2.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal: {0}".format(contents))

    if (choice == 3):
        f = open("dna3.txt", "r")
        if f.mode == "r":
            contents = f.read()
            print("\nOriginal: {0}".format(contents))

    if (choice == 4):
        print("Exiting program.")
        sys.exit(0)

这个问题可以通过python 3中的基本缩进来解决,但您也可以这样修改:

#继续循环,直到按下特定键
choice=int(输入(“\n输入一个数字(1)-(4)。(4)终止程序。”)

而选择你的问题已经被其他人彻底回答了

然而,我想花一分钟向您展示一些改进编码风格的机会。我重新编写了你的程序,并就这些更改如何使你作为一名开发人员的生活更轻松做了一些笔记

  • 设置常量,使您可以在一行而不是多个位置上操作数据。-我使用
    options
    变量将选项打印给用户,并确定如何处理每个选项
  • 使循环尽可能小以增加可读性。在本例中,我将处理选择的所有逻辑移到了函数中。现在任何读者都可以看出,我在这个循环中真正做的是(1)提示用户,然后(2)处理选择
  • 将变量粘贴到字符串中-如果字符串中只有一个小的变量被重复,则将该变量粘贴到变量中并放入字符串中。这将加快您的编码速度,使您的代码更具可读性。这就是本例中的
    choice
  • -这不是必须的,但它是前一点的延续。另外,这是优化代码并使字符串解析/连接更具可读性的好方法
  • 我希望这对您学习Python有帮助!快乐编码

    options = list(range(1, 5))
    finished = False
    
    def process_choice(choice):
        if choice not in options:
            print("Invalid option.\n")
            return False
    
        if(choice == 4):
            print("Exiting program.")
            return True
    
        with open(f"dna{choice}.txt", "r") as file:
            contents = file.read()
            print(f"\nOriginal: {contents}")
        return True
    
    
    print(f"\nEnter a number {options}. (4) terminates the program.\n")
    
    while not finished:
        choice = input("Enter a number from the menu: ")
        finished = process_choice(int(choice))
    

    sys.exit
    是一个函数;像
    sys.exit(0)
    那样调用它表示成功完成,或者像
    sys.exit(1)
    那样调用它表示由于错误而未能完成。将其包装在一个循环中。内部
    while
    循环可以被
    if
    语句中的
    else
    子句替换。@chepner是的,这是其他可能的解决方案之一;)