cars cars - 3 months ago 18
Python Question

Validating Alphabet From Input

Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.

This is my code so far

words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')

suppose I choose three letters then the output of my code then pressed enter on the fourth,
the code will be:

Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.

I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.

Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.


This is how I want my program to work

enter image description here

enter image description here

Answer

You can use a while loop to collect input, then break out of the loop if either the input is empty (the user hit enter without inputting a character) or if the input is not in the alphabet.

letters = []
while True:
    letter = input('Character:')
    if letter == '':
        if not letters:
            print('The input was blank.')
        else:
            print('{} is a valid alphabetical string.'.format(''.join(letters)))
        break
    elif letter.isalpha():
        letters.append(letter)
    else:
        print('{} is not in the alphabet.'.format(letter))
        break
Comments