Home > OS >  Im trying to use try and except to accept only strings but it doesnt run, What am i doing wrong
Im trying to use try and except to accept only strings but it doesnt run, What am i doing wrong

Time:06-20

Trying to use try and except to accept strings only and display an error message if an int is typed in.

This is my code:

name = input('Enter Your Name: ')
try:
    s_name = str.lower(name)
except:
    print('Please your Alphabets Only')
    quit()

CodePudding user response:

str.lower() doesn't throw error when you pass a string of numbers. So, your try-except is not working.

>>> str.lower('ASD123')
>>> 'asd123'
>>> str.lower('123')
>>> '123'

To get your desired output, you can use isalpha().

name = input('Enter Your Name: ')
if name.isalpha():
    print(name) # or do whatever you want to do with name
else:
    print('Please your Alphabets Only')

CodePudding user response:

Is there a specific reason to use exceptions for that?

In case there isn't, you can just use isalpha.

In case there is, you can implement a utility that uses isalpha and throw an exception if the input is not valid:

def validate_input(str):
  if not str.is_alpha():
    raise ValueError('Input not valid') 

name = input('Enter Your Name: ')
try:
    validate_input(name)
except ValueError as e:
    print(e)
    quit()
  • Related