如何从用户输入中收集信息并将其应用于其他地方

时间:2016-08-25 08:57:36

标签: python

您好我是编程的新手,我正在尝试编写一个代码,该代码将从输入中收集信息并确定它是否是有效的字母。

这是我目前的代码

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.

这就是我希望我的程序工作的方式

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:2)

使用str.isalpha() 如果字符串中的所有字符都是字母,则仅为true。

示例:

>>> 'test'.isalpha()
True
>>> 'test44'.isalpha()
False
>>> 'test test'.isalpha()
False

在您的代码中:

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

答案 1 :(得分:2)

您可以使用while循环来收集输入,如果输入为空(用户点击输入而不输入字符)或者输入不在字母表中,则可以使用循环。< / p>

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

答案 2 :(得分:1)

你可以尝试一下: -

words = []
while 1:
    word = input('Character: ')
    if word != '':
        try:
            if word.isalpha():
                pass
            if word not in words:
                words.append(word)
        except Exception:
            print word, " is not in the alphabet"
            break
    else:
        res = (''.join(words) +' is a valid alphabetical string.') if (words != []) else "The input was blank."
        print res
        break