【问题标题】:Is there a better way to check if a series of inputs match a certain stop condition?有没有更好的方法来检查一系列输入是否匹配某个停止条件?
【发布时间】:2021-03-01 04:21:27
【问题描述】:

(Python 3.7)

我有一个与下面包含的类似的程序。我只是想弄清楚是否有更好的方法来检查任何用户输入是否与“结束”条件匹配,我确实需要单独保存每个输入。

while True:
    fname = input("Enter Customer first name: ")
    if fname == "end":
        break
    
    lname = input("Enter Customer last name: ")
    if lname == "end":
        break

    email = input("Enter Customer email: ")
    if email == "end":
        break

    num = input("Enter Customer id: ")
    if num == "end":
        break
    elif not num.isdigit():
        num = -1
    # not worried about error here
    num = int(num)

    print(fname, lname, email, num)
print("User has ended program")

我不担心现阶段的错误,只是想在这里集思广益,讨论最干净的实现。我会有很多输入,所以我希望我不必为每个单独的输入一遍又一遍地包含相同的 if 语句。

【问题讨论】:

  • 为什么要让用户输入部分记录?
  • @DavisHerring 在我的情况下,我只需要能够取消输入过程并返回到外部命令选择页面。上面的函数将用于在已经填充的数据库中进行搜索,因此记录的完整性对我来说并不重要。

标签: python python-3.x user-input exit stop-words


【解决方案1】:

这将是创建用户异常的好机会:

class UserExit(BaseException):
    pass

def get_input(prompt):
    response = input(prompt)
    if response=="end":
        raise UserExit("User Exit.")
    return response

try:
    while True:
        fname = get_input("Enter Customer first name: ")
        lname = get_input("Enter Customer last name: ")
        email = get_input("Enter Customer email: ")
        num = get_input("Enter Customer id:")
        if not num.isdigit():
            num = -1
        else:
            num = int(num)
        print (fname,lname,email,num)

except UserExit as e:
    print ("User ended program.")

【讨论】:

  • 太棒了。我想知道尝试例外情况是否适用于我的情况,但不知道引发自定义异常的具体细节,谢谢。
  • 哎呀,我还没有看到你的答案,我已经发布了一个非常相似的答案。我觉得有义务在收回我的时候支持你的……
  • @gboffi 非常荣幸!谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 2021-06-27
  • 2016-10-28
  • 1970-01-01
相关资源
最近更新 更多