1

I am attempting to limit the character length of my input and then verify whether it is one of the three white characters. Struggling with the final part:

while True:
    try:
        letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
        assert len(letter) !=1
    except AssertionError:
        print("Please type only ONE character")
    else:
        whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
        if whitespace not in letter:
            print("Your character in lower case is: "+str(letter).lower())
        else:
            print("You typed a white space character!")

2 Answers 2

1

Welcome to Stackoverflow!

It looks like the error is on the if whitespace not in letter: line. This should actually be the other way around: if item not in list:. You have if list not in item:.

Also, it might help you if I reformat your code a little.

while True:
    letter = input('Please enter a character: ')

    if len(letter) != 1:
        print('Please type only ONE character')
        continue

    if letter in ['\n', ' ', '\t']:
        print("You typed a white space character!")
        continue

    lowercase_letter = letter.lower()
    print(f'Your character in lower case is: {lowercase_letter}')

If you haven't already seen pylint, I'd recommend you take a look at it. It helps you format your code to PEP8 standard. It is also quite good at pointing out some simple errors in your code.

Raising Exceptions are for reporting errors to calling functions - i.e. you can't perform the job the function is supposed to be doing because the input or system state is not as required by the function.

Catching Exceptions is for handling specific errors you know how to handle in a higher level function. So for example, if your trying to read a file and it doesn't exist. In your program that mean the user hasn't set a specific flag in the config file... so you can catch that exception and let the user know how to fix the issue.

Raising an Exception and catching it in the same function (at least in this case) is just a very complicated way of writing an if statement.

When writing an if-else statement, it's a good idea to try and make the if branch positive. Which means avoid if not ...: else: if you can.

In your code, letter is already a string object - so there is no need to create a new string object with str(letter). In python everything is an object, even literals.

The continue statement jumps to the next iteration of the loop. Nothing after the continue is executed in the current iteration of the loop. You could also look at break statement that finishes executing the loop. As an exercise, you could look at adding an extra check to your code to see if the user typed 'quit', and then break. What do you think will happen?

if letter.lower() == 'quit':
    break

This would have to be added before the check for single letters otherwise you would never get to this check.

Finally, rather than using string concatenation in your print statement (using str + str). You can use f-strings, format strings as in the example f'Hi my name is {name} and I am from {home}', where name and home are string variables.

Hope this helped!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for all the help! Online lectures have been a bane so this breakdown helps a lot.
Pleasure! I'm glad I could help you. Keep at it, it can be frustrating... but you will get better quickly, and it's well worth it. You could also try codewars.com or something like that. They give you simple coding challenges to solve all kinds of exercises from really easy to really complicated. After your done with one, it shows you how other people did it. Often there is an easier way, and you can learn a lot. Great if you have a few minutes spare for a bit of learning 😉
1

I'd advise you not to use exceptions because they're very unstable. Instead, I'd use if/else conditions, like this one:

    letter = input('Please enter a character: ')
    if len(letter) == 1:
        if letter in '\n\t ':
            print('You typed a white space character!')
        else:
            print('Your character in lowercase is {}'.format(letter.lower()))
    else:
        print('Please type only ONE character')```

2 Comments

Thank you! Appreciate the help :)
@BAMIR Not at all ;)

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.