Home > Mobile >  In Python, How can I create a while loop using input 'filename'
In Python, How can I create a while loop using input 'filename'

Time:08-10

I am wanting to create a loop for my book reader so that when the user inputs a number other than 1-10, an error message comes up, and when they press 0 the program quits. However, an error message appears saying FileNotFoundError: No such file or directory: '11.txt'(etc)

import time
option = str(input('Which Book would you like to read? (1-10): '))
while option !=0:
    number_of_words = 0
    f=open(option   '.txt', encoding='utf-8')
    file_contents=f.read()
    lines = file_contents.split()
    number_of_words  = len(lines)
    print('Word Count:',number_of_words)
    time.sleep(2)
    f=open(option   '.txt', encoding='utf-8')
    for line in f:
        print(line)
        time.sleep(0)
    else:
        print("404 file not found")
    print()
    option=str(input('Which Book would you like to read?(1-10):'))
print("Goodbye")

CodePudding user response:

Try this:

import time
while True:
    try: # Wrap the input in a try except and try to convert it directly to an integer.
        option=int(input('Which Book would you like to read? (1-10): '))
    except:
        print("Please only enter a number.")
        continue
    if option == 0:
        print("Goodbye")
        break
    if option > 10:
        print("Invalid book entered, try again, must be between 1 and 10.")
        continue
    with open(str(option)   '.txt', encoding='utf-8') as f: # Use a context manager to open files, it will make sure your files are closed after opening
        file_contents=f.read()
        number_of_words = len(file_contents.split())
        print('Word Count:',number_of_words)
        time.sleep(2)
        for line in file_contents:
            print(line)

Results:

Which Book would you like to read? (1-10): few
Please only enter a number.
Which Book would you like to read? (1-10): 121
Invalid book entered, try again, must be between 1 and 10.
Which Book would you like to read? (1-10): 0
Goodbye
  • Related