1

I can't get this short piece of code to work. What I am trying to do is ask user to enter a 4 letter word, if they don't then ask them to try again, if they do then to say thanks. I added the while True, try & except part as it looked like the best way to keep looping around but I didn't really get it.

while True:
    try:
        word=input("Please enter a four letter word: ")
        word_length=len(word)
    except word_length != 4:
        print("That's not a four letter word. Try again: ")
        continue
    else: 
        break

if word_length ==4:
    print("Thanks")
5
  • You could start by identifying what language you are trying to use. Commented Feb 10, 2020 at 20:10
  • Sorry using python 3 Commented Feb 10, 2020 at 20:11
  • not sure why my code hasn't displayed correctly in my question sorry Commented Feb 10, 2020 at 20:11
  • What is your exact question or problem? Commented Feb 10, 2020 at 20:14
  • That's not how you use except. You use except to catch an exception thrown by something. Commented Feb 10, 2020 at 20:16

2 Answers 2

1

except is for catching exceptions (other languages use try and catch instead).

In this case, you just need to use a simple if to check if the value is what you want:

while True:
    try:
        word = input("Please enter a four letter word: ")
        word_length = len(word)
    except TypeError:
        print('error getting word length')
    else:
        if word_length != 4:
            print("That's not a four letter word. Try again: ")
        else:
            break

if word_length == 4:
    print("Thanks")
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help - the bit that's missing is the loop back around, so it says try again but doesn't allow user to input for a 2nd time when I test this?
@EleanorLaurence Yes, looks like I needed to move the word_length check into the else of the try block.
1

Use if-else instead of try-except:

while True:
    word=input("Please enter a four letter word: ")

    if len(word) == 4:
        print("Thanks")
        break
    else:
        print("That's not a four letter word. Try again: ")

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.