用户输入 - 验证和确认 -

时间:2017-05-10 00:49:37

标签: python if-statement while-loop user-input

我正在尝试执行之前已经多次询问过的事情(特别是Asking the user for input until they give a valid response),但我要么尝试做一些过于复杂的事情,要么不考虑我的循环方式正确。

在下面的代码中,我尝试做一些事情:

  • 向用户询问整数列表,可以是一个或多个(在本例中为loan_ids
  • 如果整数失败,请大声拒绝输入
  • 如果是整数,则附加到正在运行的列表
  • 将所有结果转换为元组,以便在SQL查询中使用

在第二个功能中,我试图合并第一个功能,然后让用户在切断之前确认loan_ids

  • 如果用户输入y,则结束循环
  • 如果用户输入n,请返回第一个功能并再次询问
  • 如果输入任何其他内容,请让用户重新提交答案

我试图不违反不要重复自己的原则,但对于我的生活,我无法弄清楚循环的位置。我对python和编程结构也比较陌生,所以对设计的惯用评论也是开放的

def get_unique_loans_from_user():
    """Get list of  loan_ids from user

    This function is mean to capture raw loan_ids a user wishes to look up. 

    Returns tuple of unique loan_ids

    """

    loan_ids = []
    while True:    
        loan_id = raw_input('> Loan Id: ')
        # If nothing entered, exit
        if len(loan_id)==0:
            break
        # Make sure an integer was entered      
        else:
            try:
                int(loan_id)
            except ValueError:
                print loan_id + " is not a real integer, so likely not a valid loan id"
                continue
        # if an integer was entered, append to running list as an integer and continue
        # We only need to return the unique list of loan ids
            else:
                loan_ids.append(int(loan_id))

    # Convert unique list of loans to tuple to use in SQL     
    loans = tuple(np.unique(loan_ids))   

    # Return the tuple of loans
    return loans

第二部分 - 它当前编写的方式会在用户输入y以外的任何内容时强制执行相同的结果 - 我尝试根据使用是否无效而导致不同的行为输入与实际确认loan_ids不正确。我最后还使用了一个额外的中断声明,我相当肯定这不是最佳实践

def confirm_loan_ids():
    """ Confirm the list of loan ids is what the user wanted"""

    while True:

        # Get loan ids from user through raw input
        ids = get_unique_loans_from_user()

        # Print out the ids to the user
        print "Printing loan ids. There are {0} ids".format(len(ids))
        print ids

        # Confirm with user these are the correct ids
        answer = raw_input('> Are these the loan ids you expected? [y/n] ')


    # If user confirms correct, and continue
        if answer == 'y':
            print "\nExcellent - moving on\n"
            print "Here are your loan ids:"
            print ids
            break
    # If the answer is n, repeat the question
        elif answer == 'n':
            print "\n-------------> Let\'s try again\n"
            continue
    # If answer is not no or yes, ask again    
        elif (len(answer) == 0) or (answer not in ('y','n')):
            print "Please enter only y or n"
            continue
        else:
            print "This is only a test"
        # The If loop only breaks when the answer is 'y'
        break

    return ids

1 个答案:

答案 0 :(得分:0)

试试这个。它减少了使用continue的一些要求,而是让循环自然地再次迭代。这减少了代码中的视觉噪音。

对于第二个函数,您可以再次简化逻辑以消除使用continue的需要,而只是在输入良好时断开。

代码需要再次循环以获得yes / no确认,因此为了避免必须打破嵌套循环的问题,yes / no循环在另一个函数中。在收到有效输入之前,此功能不会返回。

希望这能为您提供一些更清晰的逻辑吗?

如果你想要而不是numpy.unique,你可以恢复你的set功能,但我一般不会使用numpy而只是为了这个目的导入它似乎有点过分我使用{ {1}}而是。我不知道您的具体要求,因此不知道setset是否更合适。

numpy.unique