python - 我需要在我的程序中输入一些错误处理

标签 python

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

print ""

# To God be the Glory

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

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

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)           

最佳答案

break 仅退出 for 循环。不是程序或函数。您可以使用 return 退出该函数,或者,如果您希望完全停止脚本,则可以使用选项之一 shown here .

关于python - 我需要在我的程序中输入一些错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084545/

相关文章:

python - 如何在 Python 中用 subprocess.call 替换 os.system ("mkdir "_testName)?

python - Fabric 的 `hide("everything")` 实际上隐藏了什么?

python - 是否可以在 python 中将动态(带有静态文件)Web 应用程序作为没有其他依赖项的单个包提供服务?

python - 如何计算前瞻受限的组内的 cummin?

python - 从 IronPython 使用 NumPy 和 SciPy 的 final方法

python - Pandas 通过多个字符串分隔符将列拆分为多列

python - 类型错误 : __init__() missing 1 required positional argument: 'on_delete' (Django 2)

python - 在函数之外的 golang 中设置常量,就像在 Python 中一样

python - 无法在正确的 python 版本上安装 python 包?

python - Python 的逗号运算符在赋值过程中是如何工作的?