【问题标题】:How to prevent user from inputting spaces/nothing in Python?如何防止用户在 Python 中输入空格/空?
【发布时间】:2019-01-16 18:21:34
【问题描述】:

我有一个问题,用户可以输入空格或什么都不输入,但仍然可以通过程序,我该如何防止这种情况发生?我仍然是python的初学者。

def orderFunction(): # The function which allows the customer to choose delivery or pickup
    global deliveryPickup
    deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
    if deliveryPickup == "d": 
        global customerName
        while True:
            try:
                customerName = (input("Please input your name"))
                if customerName == (""):
                    print("Please input a valid name")
                else:
                    break
        global customerAddress
        while True:
            try:
                customerAddress = (input("Please input your name"))
                if customerAddress == (""):
                    print("Please input a valid Address")
                else:
                    break
        global customerPhnum
        while True: 
            try: 
                customerPhnum = int(input("Please input your phone number"))
            except ValueError:
                print("Please input a valid phone number")
            else:
                break
            print("There will also be a $3 delivery surcharge")
    elif deliveryPickup == "p": 
        customerName = (input("Please input your name"))
        if customerName == (""):
            print("Please input a valid name")
            orderFunction()

    else:
        print("Please ensure that you have chosen d for Delivery or p for Pickup")
        orderFunction()

orderFunction()   

这是我的尝试,但目前我遇到了各种不缩进和缩进错误,我认为我的 while 循环可能是错误的。

基本上,如果我输入一个空格或按 Enter 键输入其中一个客户输入(例如 customerName),它就会被存储。这需要防止,我试图通过使用 while 循环来修复它,但显然没有用。

希望有人能解决这个问题

非常感谢。

【问题讨论】:

  • 尝试签出string templates。它们对于获取客户信息等输入非常有用。

标签: python if-statement while-loop try-except


【解决方案1】:

尝试使用regular expression 检查是否插入了“A-Z”之间的任何字符,如果没有,则报错

【讨论】:

    【解决方案2】:

    您可以创建一个与此类似的函数,它只允许有效输入,而不是立即使用输入。

    您可以使用此valid_input 函数代替input

    def valid_input(text):
        not_valid = True
        res = ''
        while not_valid:
            res = input(text)
            if res.split():  # if text is empty or only spaces, this creates an empty list evaluated at False
                not_valid = False
        return res
    

    这里的检查非常简单:不允许任何由空或空格组成的文本,我们将继续要求相同的输入,直到给出有效信息。

    我简化了这段代码,只是为了让您有一个大致的了解。但是您可以根据自己的喜好更改验证测试,也可以输出警告,说明为什么不允许输入,以便该人知道该怎么做。您可以使用正则表达式进行更高级的验证,也许您需要最小文本长度等...

    【讨论】:

      【解决方案3】:

      您有缩进错误,因为您有一个 try 语句而没有相应的 except。 您需要两者才能使其正常工作(就像您在电话号码部分中所做的那样)。

      这里是 try/except 的链接:docs

      另外,您可以检查字符串是否为空,详见this 答案。

      所以例如你想写:

              try:
                  customerName = input("Please input your name")
                  if not customerName:
                      print("Please input a valid name")
                  else:
                      break
              except ValueError:
                      print("Please input a valid name")
      

      虽然上面看起来有点多余,所以如果客户名称为空,您可能希望引发异常,在 except 块中捕获异常,打印警告并返回错误(或其他内容)。

              try:
                  customerName = input("Please input your name")
                  if not customerName:
                      raise ValueError
              except ValueError:
                  print("Please input a valid name")
              else:
                  break
      

      【讨论】:

        【解决方案4】:

        您正在寻找的是 str.strip 方法,该方法可以删除字符串中的尾随空格。 另外我认为 try 在这里并不是特别适合您的需求。

        customerName = input("Please input your name")
        while not customerName.strip():
            customerName = input("Please input a valid name")
        

        对于电话号码,我不会转换为整数,因为如果电话号码以零开头,它们将不会被存储。

        【讨论】:

          【解决方案5】:

          while 循环是一个不错的解决方案,您只需在 if 语句中添加更多检查。

          首先,您不需要在前两个循环中使用 try 语句。不要使用 try 语句,除非您预期会出现错误,您需要使用 except 语句来处理,就像您在底部的 while 循环中所做的那样。

          然后你只需要在你的前两个循环中添加更多条件,我不知道你想要阻止什么,但你可以尝试检查输入的长度,也可以看看这个答案以获得一个有趣的方法: https://stackoverflow.com/a/2405300/8201979

          【讨论】:

            【解决方案6】:

            尝试为拣货和交付选项添加另一个 while true,以防止接受其他输入

            【讨论】:

              【解决方案7】:

              您不需要任何这些 try/excepts(无论如何都已损坏)。

              很难弄清楚您要做什么,如果传递了一个空字符串,您是要引发异常,还是要从用户那里请求另一个输入?目前,您似乎都实现了一半。

              如果是后者,这样的事情会起作用。

              def func(fieldname):
                  while True:
                      val = input("Please input your {}".format(fieldname))
                      if val.strip() != "":
                          break
                      else:
                          print("Please input a valid {}".format(fieldname))
                  return val
              
              delivery_pickup = input("Please input delivery or pickup: d for delivery p for pickup")
              
              if delivery_pickup == "d":
                  customer_name = func("name")
                  address = func("address")
                  phone_number = func("phone number")
              

              【讨论】:

              • 将你的条件直接放在while中而不是手动中断会更干净。注意:if val.strip() != "" 等价于 if val.strip(),因为空字符串在条件中的行为类似于 False
              【解决方案8】:

              .strip() 删除字符串前后的所有制表符或空格。 表示所有空格 == 空字符串。所有选项卡 == 空字符串。因此,您只需检查该字符串的长度 != 0 还是该字符串不为空。只需使用无限循环来继续强制正确输入。

              另外作为提示,您不必将自己限制在一个功能中。 这是下面的工作代码。

              def getNonBlankInput(message, error_message):
              
                  x = input(message)
                  while len(x.strip()) == 0:
                      x = input(error_message)
              
                  return x
              
              def getValidIntegerInput(message, error_message):
              
                  msg = message
                  while(True):
                      try: 
                          x = int(input(msg))
                          break
                      except ValueError:
                          msg = error_message
              
                  return x
              
              
              def orderFunction(): # The function which allows the customer to choose delivery or pickup
                  global deliveryPickup
                  global customerName
                  global customerAddress
                  global customerPhnum
              
                  deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
              
                  if deliveryPickup == "d": 
                      customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
                      customerAddress = getNonBlankInput("Please input your address: ", "Please input a valid address: ")
                      customerPhnum = getValidIntegerInput("Please input your phone number: ", "Please input a valid phone number: ")
                      print("There will also be a $3 delivery surcharge")
                  elif deliveryPickup == "p": 
                      customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
                  else:
                      print("Please ensure that you have chosen d for Delivery or p for Pickup")
                      orderFunction()
              
              orderFunction() 
              

              【讨论】:

              • 你有办法确保电话号码不是负整数吗?
              • customerPhnum > 0 可以,尽管我不认为整数是电话号码特别好的表示。
              • 另外,在 Python 中,空字符串在条件下的行为类似于 False。因此while len(x.strip()) == 0可以替换为while not x.strip()
              • 好的,我有点明白了,但是我应该把 customerPhnum > 0 放在哪里?
              • 0 为假,> 0 在 python 中也为真。亚历克西斯是对的。在现实世界中,电话号码是字符串,因为人们有时会在电话号码旁边加上 + 或任何其他符号。
              猜你喜欢
              • 1970-01-01
              • 2016-07-13
              • 2014-03-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多