【问题标题】:How do i validate a user input in python? [duplicate]如何在 python 中验证用户输入? [复制]
【发布时间】:2020-01-10 23:48:51
【问题描述】:

如何在 python 中验证用户输入?我正在写这段代码,用户必须输入他们的名字,并且必须是两个用空格分隔的名字,并且名字应该只包含字母

def Name():
    n = 0
    name = input('name please\n>>')
    c = name.split(' ')
    while len(c) != 2:
        print('we need two names')
        name = input('name please\n>>')
        c = name.split(' ')

    while True:
        for i in name:
            if i not in r:
                n+=1
        if n > 0:
            print('Letters only')
        else:
            break

Name()

【问题讨论】:

  • 您当前的代码有什么问题?
  • 我希望程序返回一个只有字母的两个名称,但我发现很难验证输入。当我使用 while 循环和 for 循环时,它会运行两次并停止
  • 这能回答你的问题吗? Asking the user for input until they give a valid response 将此与下面答案中的验证方法结合使用。
  • ' def Name(): name = input('name please\n>>') c = name.split(' ') if len(c) != 2: print('我们需要两个名称')C中项目的名称():如果不是item.isalpha():打印('仅字母')名称()返回名称名称()'

标签: python


【解决方案1】:

使用while循环

def Name():
  while True:
    name = input('name please:')
    c = name.split(' ')
    if len(c) != 2:
      print("We need two names (first/last with space between)")
      continue

    if not (c[0].isalpha() and c[1].isalpha()):
      print('Only letters a-z or A-Z') 
      continue

    return name

name = Name()
print(name)

【讨论】:

    【解决方案2】:

    使用.isalpha(),我建议递归地执行此操作。

    def Name():
        name = input('name please\n>>')
        c = name.split(' ')
        if len(c) != 2:
            print('we need two names')
            Name()
    
        for item in c:
            if not item.isalpha():
                print('Letters only')
                Name()
    
        return name
    
    Name()
    

    【讨论】:

    • 非常感谢。除了在函数中调用函数之外,还有其他方法吗?喜欢使用while循环吗?
    • 递归地这样做是一个糟糕的主意,为什么你没有评论有问题的基于全局的设计?
    • AMC,当我再看一遍时,我发现递归可能会变得混乱,而 while 循环会更好。我不知道您的意思是基于全局的设计,但是如果您发现代码有问题,您应该在帖子上发表评论,以便发帖人和其他读者意识到所说的问题,而不是要求其他人这样做。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 2017-08-22
    • 2011-06-26
    相关资源
    最近更新 更多