如何让用户一次只输入一个字符

时间:2014-09-28 18:58:59

标签: python

好的,我需要做的是让我的代码只允许用户输入一个字母,然后一次输入一个符号。以下示例以更好的视图显示了我想要的内容。

目前我的代码允许用户一次输入多个我不想要的字符。

What letter would you like to add?  hello

What symbol would you like to pair with  hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello'] 

我想要的是要显示的消息,并且配对不会添加到列表中。

What letter would you like to add?  hello

What symbol would you like to pair with  hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].

到目前为止,我对此部分的代码如下......

当用户在字母部分输入一个数字时,这也是很好的,这是一个要打印的错误信息。

def add_pairing(clues):
    addClue = False
    letter=input("What letter would you like to add?  ").upper()
    symbol=input("\nWhat symbol would you like to pair with  ")
    userInput= letter + symbol
    if userInput in clues:
        print("The letter either doesn't exist or has already been entered ")
    elif len(userInput) ==1:
        print("You can only enter one character")
    else:
        newClue = letter + symbol
        addClue = True
    if addClue == True:
        clues.append(newClue)
        print("The pairing has been added")
        print (clues)
    return clues

4 个答案:

答案 0 :(得分:0)

确保用户输入的最简单方法是使用循环:

while True:
    something = raw_input(prompt)

    if condition: break

这样设置的内容会继续询问prompt,直到condition满足为止。你可以condition任意想要测试的内容,所以对你而言,len(something) != 1

答案 1 :(得分:0)

如果您让用户输入字母和符号对,您的方法可简化为以下内容:

def add_pairing(clues):
    pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
    clues = pairing.upper().split()
    print('Your pairings are: {}'.format(clues))
    return clues

答案 2 :(得分:0)

我喜欢在类似情况下提出并捕捉异常。有可能让人感到震惊的是C-ish'背景(sloooow),但它在我看来是完全pythonic,非常易读和灵活。

此外,您应该添加对您期望的字符之外的字符的检查:

import string

def read_paring():
    letters = string.ascii_uppercase
    symbols = '*@#$%^&*' # whatever you want to allow

    letter = input("What letter would you like to add?  ").upper()
    if (len(letter) != 1) or (letter not in letters):
        raise ValueError("Only a single letter is allowed")

    msg = "What symbol would you like to pair with '{}'? ".format(letter)
    symbol = input(msg).upper()
    if (len(symbol) != 1) or (symbol not in symbols):
        raise ValueError("Only one of '{}' is allowed".format(symbols))

    return (letter, symbol)

def add_pairing(clues):
    while True:
        try:
            letter, symbol = read_paring()
            new_clue = letter + symbol
            if new_clue in clues:
                raise ValueError("This pairing already exists")
            break # everything is ok 
        except ValueError as err:
            print(err.message)
            print("Try again:")
            continue

    # do whatever you want with letter and symbol
    clues.append(new_clue)
    print(new_clue)
    return clues

答案 3 :(得分:0)

不完全确定要返回的内容,但这会检查所有条目:

def add_pairing(clues):
    addClue = False
    while True:
        inp = input("Enter a letter followed by a symbol, separated by a space?  ").upper().split()
        if len(inp) != 2: # make sure we only have two entries
            print ("Incorrect amount of  characters")
            continue
        if not inp[0].isalpha() or len(inp[0]) > 1:  # must be a letter and have a length of 1
            print ("Invalid letter input")
            continue
        if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
            print ("Invalid character input")
            continue
        userInput = inp[0] + inp[1] # all good add letter to symbol
        if userInput in clues:
            print("The letter either doesn't exist or has already been entered ")
        else:
            newClue = userInput
            addClue = True
        if addClue:
            clues.append(newClue)
            print("The pairing has been added")
            print (clues)               
            return clues