我需要在程序中输入一些错误处理。我的程序从用户那里获取一行文本,但是这个文本应该只包含字母和空格。我试图输入一些错误处理,但我想改进它。当用户输入字母或空格以外的内容时,我会打印错误消息,但仍然会执行下面的代码。当用户输入不是字母或空格的内容时,我希望打印错误消息并终止程序。
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)
答案 0 :(得分:1)
break
仅退出for循环。不是程序或功能。您可以使用return
退出该功能,或者,如果您完全停止该脚本,则可以使用其中一个选项shown here。
答案 1 :(得分:0)
一种相当简单的方法如下:
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.