0

Write a function named ask_file_name that repeatedly prompts the user for a file name until the user types the name of a file that exists on the system. Once you get a good file name, return that filename as a String.

this is what I have done till now:

import os.path
def ask_file_name():
    file = input("Type a file name: ")
    x = os.path.exists(file)
    if x :
        return file
    else:
        ask_file_name()

but it is giving the following error: expected string, but no value was returned

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 3
    After you add the missing return, you should consider rewriting this code to use an iterative solution (a while loop) rather than a recursive solution (calling ask_file_name() from within ask_file_name()). – jarmod Aug 15 '21 at 13:19
  • 1
    Refer this post for other ways to repeat input until valid https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – OneCricketeer Aug 15 '21 at 13:21

2 Answers2

1

You'll need to use a while loop.

def ask_file_name():
    file = input("Type a file name: ")
    while not os.path.exists(file):
        file = input("Type a file name: ")
    else:
        return file

Please note recursion is an option, however max recursion depth can be an obstacle.

MSH
  • 1,743
  • 2
  • 14
  • 22
0
import os
def ask_file_name():
    file = input("Type a file name: ")
    x = os.path.exists(file)
    if x :
        return file
    else:
        return ask_file_name()
Wrench
  • 490
  • 4
  • 13