Reputation: 1
Is there a better way to do this?
I want the code to detect numbers and special characters and print:
"numbers not allowed" / "special characters not allowed"
while True:
try:
x = input('Enter an alphabet:')
except ValueError:
print('sorry i do not understand that')
continue
if x in ('1', '2','3','4','5','6','7','8','9','0'):
print('Numbers not allowed')
continue
else:
break
if x in ('a', 'e', 'i', 'o', 'u'):
print ('{} is a vowel'.format(x))
elif x in ('A', 'E', 'I', 'O', 'U'):
print ('{} is a vowel in CAPS'.fotmat(x))
else:
print('{} is a consonant'.format(x))
Upvotes: 0
Views: 5995
Reputation: 418
You could do it a couple of ways but the pythonic method seems to me to be like so:
if any(char in string.punctuation for char in x) or any(char.isdigit() for char in x):
print("nope")
Upvotes: 0
Reputation: 383
May be this code does the job.
while True:
x = ord(input('Enter an alphabet:')[0])
if x in range(ord('0'), ord('9')):
print('Numbers not allowed')
continue
if x not in range(ord('A'), ord('z')):
print('Symbols not allowed')
continue
if chr(x) in 'aeiou':
print('{} is a vowel'.format(chr(x)))
elif chr(x) in 'AEIOU':
print('{} is a vowel in CAPS'.format(chr(x)))
else:
print('{} is a consonant'.format(chr(x)))
continue
We select numbers, deselect whatever character except letters and then does the job.
Upvotes: 0
Reputation: 43524
One way is to use the string
library.
Here is some psuedocode, which assumes that the input is one character at a time:
import string
x = input('Enter an alphabet:')
if x in string.digits:
print('Numbers not allowed')
elif x not in string.ascii_letters:
print('Not a letter')
string.ascii_letters
is a string that contains all the uppercase and lowercase letters:
print(string.ascii_letters)
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
Likewise, string.digits
is a string that contains all of the digits:
print(string.digits)
#'0123456789'
Upvotes: 1