0

I would like to use Try/ecept to check if a string is really a string. I made the following code:

nome = input('Name: ')
try:
    if not nome.isalpha() or nome == '':
        raise ValueError('Invalid!')
    else:
        print(f'Name {nome} valid.') 
except ValueError as e:
    print(f'Error: {e}')

But, I would like to do it without using the raise command, just try/except.

Can anyone help me? I thank you.

2
  • 2
    try/except requires something to raise the exception. There's no built-in function that raises an exception for non-alpha strings, so you have to raise it explicitly. Commented Apr 18, 2022 at 20:57
  • You would need to provide your own assertion method that raises internally. e.g. def assert_isalpha_non_empty Commented Apr 18, 2022 at 21:01

1 Answer 1

1

The only way to trigger an exception without raising it yourself is to attempt something invalid, such as this:

nome = input('Name: ')
try:
    f = float(nome)
except ValueError as e:
    print('Is alpha')
else:
    print('Not alpha')

Here I try to convert the input to a float, and if there are any alpha characters in the value, it will raise the ValueError exception.

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

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.