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

2024-06-06 15:35: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'] 

我想要的是这样显示一条消息,而不将配对添加到列表中。在

^{pr2}$

到目前为止,我对这个部分的代码如下。。。在

当用户在字母部分输入一个数字,一个错误消息将被打印出来。在

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

Tags: theto代码用户youaddsymbolwhat
3条回答

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

while True:
    something = raw_input(prompt)

    if condition: break

类似这样的设置将继续询问prompt,直到condition满足为止。你可以做condition任何你想测试的东西,所以对你来说,它就是len(something) != 1

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

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

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

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

相关问题 更多 >