0

This is a function of a larger Python program. How can I get it to loop continuously until "4" is entered? Any help is greatly appreciated.

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
martineau
  • 119,623
  • 25
  • 170
  • 301

5 Answers5

1

Just wrap all in a while True, also think about using elif as your choice will be one of all so don't to check the next one's if one successes, and you can simplify the while/choice using an array.

Also I'd suggest you refactor to avoid duplicate code (if you can) for the part that check mode, read file, save content, print content ;

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)

Or add an else at the end and remove the inner loop

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: ")
azro
  • 53,056
  • 7
  • 34
  • 70
0

Have you tried using continue and break statement, I mean instead of saying condition in the while loop, you could say

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

You should probably add continue under all statements except the last on

0

You could improve this code, but as far as the question goes, simply wrap your initial loop into another loop.

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)
Joe
  • 879
  • 2
  • 6
  • 15
0

This problem can be resolved with basic indention in python 3 but you can also modify this like:

# continues loop until specific key is pressed
    
choice=int(input("\nEnter a number (1) - (4). (4) terminates the program."))
    
while 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))

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

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

    else :
        print("Exiting program.")
        sys.exit
Ryan M
  • 18,333
  • 31
  • 67
  • 74
Umar Ahmed
  • 79
  • 6
0

You question has already been throughly answered by others.

However, I wanted to take a minute to show you a few opportunities for improving your coding style. I rewrote your program, and made some notes on how these changes can make your life easier as a developer.

  1. Set constants to allow yourself to manipulate data on a single line instead of multiple places. - I did this by using an options variable for printing out the options to the user and for determining what to do with each option.
  2. Make your loops as small as possible to increase readability. - In this example, I moved all of the logic that processes a choice out to a function. Now any reader can tell that all I'm really doing in this loop is (1) prompting the user, then (2) processing the choice.
  3. Stick variables into strings - If there is only a small variation in a string that gets repeated, make the variation into a variable & drop it into the string. This will speed up your coding and make your code more readable. That's where choice comes in this example.
  4. Use fstrings - This isn't a must, but it's a continuation of the previous point. Plus, it's a good way to optimize your code and make string parsing/concatenation more readable.

I hope this is helpful for you as you're learning Python! Happy coding!

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))
Eddie Knight
  • 102
  • 6