0

Ws you can see below, the code above and under the start of loop looks pretty much same. Is it possible to avoid this repetition?

Code:

term = ","
file_name = input("What is the file name? ")
f_extns = file_name.split(".")  #splitting file extension from file name
while term in file_name:
     print("Please type file name again with . not, ")
     file_name = input("What is the file name? ")
     f_extns = file_name.split(".")
else:
    print("The file extension is: " + repr(f_extns[-1]))
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
  • What are you trying to achieve? – bigbounty Jul 05 '20 at 20:35
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) See the [top answer](https://stackoverflow.com/a/23294659/4518341) under **Implementing Your Own Validation Rules** – wjandrea Jul 05 '20 at 20:36
  • Yeah, you can do it. Create a function that has the code in it, and just call it when you need. – alfadog67 Jul 08 '20 at 16:43

3 Answers3

2

You could use an infinite loop and only break when the exit condition is met.

while True:
    file_name = input("What is the file name? ")
    f_extns = file_name.split(".")

    if term not in file_name:
        break
    else:
        print("Please type file name again with . not, ")
Brian61354270
  • 8,690
  • 4
  • 21
  • 43
0

Like this:

term = ","
while True:
    file_name = input("What is the file name? ")
    if term not in file_name: # If the user didn't input any commas
        print("The file extension is: ", file_name.rsplit('.')[0])
        break
    print("Please type file name again with . not, ")
Red
  • 26,798
  • 7
  • 36
  • 58
0

You can simplify your code by doing this

term = ","
file_name = input("What is the file name? ")
while term in file_name:
     print("Please type file name again with . not, ")
     file_name = input("What is the file name? ")
f_extns = file_name.split(".")
print("The file extension is: " + repr(f_extns[-1]))

This takes the input and as long as there is a comma in the input it will ask the user to repeat the filename. As soon as they enter a correct file name it will exit the loop and split by period.

Shrey
  • 146
  • 2
  • 11