【问题标题】:I need to input some error handling into my program我需要在我的程序中输入一些错误处理
【发布时间】:2015-08-19 00:14:20
【问题描述】:

我需要在我的程序中输入一些错误处理。我的程序从用户那里获取一行文本,但该文本应该只包含字母和空格。我试图输入一些错误处理,但我想改进它。当用户输入字母或空格以外的内容时,我会打印一条错误消息,但下面的代码仍会执行。当用户输入不是字母或空格的内容时,我希望打印错误消息并终止程序。

print ""

# To God be the Glory

text = raw_input("Please enter a line of text: ")
text_lower = text.lower()

我希望在此处输入我的错误处理,这样如果用户输入的内容不是字母或空格,程序将打印错误消息并且不会要求用户输入密钥。

print ""
key = int(input("Please enter a key: "))


def ascii_func (text) :

这是我尝试的错误处理方法

    for charc in text_lower:
        if charc not in ["a","b","c","d","e","f","g","h","i","j","k","l","m","n",\
    "o","p","q","r","s","t","u","v","w","x","y","z"," "]:
        print "Error input is not correct"
        break

    result = ''

    print ""

    for charc in text:


        if charc != " " :
            charc = ord(charc)
            charc = (charc - 97) + key
            charc = (charc % 26)
            charc = charc + 97
            charc = chr(charc)

        result += charc

    print result

ascii_func(text)           

【问题讨论】:

    标签: python


    【解决方案1】:

    break 只退出 f​​or 循环。不是程序或功能。您可以使用return 退出该函数,或者,如果您希望完全停止脚本,您可以使用shown here 选项之一。

    【讨论】:

      【解决方案2】:

      一个相当简单的方法如下。

      fail = False
      for charc in text_lower:
          if charc not in acceptable list:
              fail = True
              print "bad input"
              break
      
      if not fail:
          #rest of your code goes here
      

      还有很多更好的方法。例如,您应该阅读try... except

      出于您的目的,可能更清洁的方法是

      import sys
      for charc in text_lower:
          if charc not in acceptable list:
              sys.exit("bad input")
      #rest of your code.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 2015-05-08
        • 2020-09-24
        • 2010-10-14
        • 1970-01-01
        相关资源
        最近更新 更多