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]))
3
  • What are you trying to achieve? Commented Jul 5, 2020 at 20:35
  • Does this answer your question? Asking the user for input until they give a valid response See the top answer under Implementing Your Own Validation Rules Commented Jul 5, 2020 at 20:36
  • Yeah, you can do it. Create a function that has the code in it, and just call it when you need. Commented Jul 8, 2020 at 16:43

3 Answers 3

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, ")
Sign up to request clarification or add additional context in comments.

3 Comments

Oh this is much smarter
The else statement isn't necessary.
@AnnZen Quite true, but I generally lean towards including it to make the separation of the branches clearer.
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, ")

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.