python - 更多错误信息 + 更长的程序还是更少的错误信息 + 更短的程序?
问题描述
def question():
original = input("Enter a word: ")
if " " in original:
print("\n**Please only enter one word.**")
question()
elif len(original) <= 0:
print("\n**It seems as though you did not enter a word.**")
question()
elif not original.isalpha():
print("\n**Please only use letters.**")
question()
else:
print(original)
question()
VS。
def question():
original = input("Enter a word: ")
if len(original) > 0 and original.isalpha() and " " not in original:
print(original)
else:
print("**Make sure you enter a word, only use letters, and only enter single word.**")
question()
question()
这两个程序基本上是一回事。但是顶级程序更长,并且在用户输入无效响应时提供了更多关于出错的信息。底部程序要短得多,但没有为无效响应提供尽可能多的信息。在现实世界的编码中,就像在专业编程中一样,哪一个程序会比另一个程序更受欢迎?
解决方案
除了少数例外(例如登录),更多的信息通常会更好(但这是高度主观的并且取决于具体情况)。话虽如此,我们可以稍微改进您的第一个详细选项,例如:
# Allow multiple, simultaneous errors
def question():
while True:
original = input("Enter a word: ")
errors = []
if " " in original:
errors.append("\n**Please only enter one word.**")
if len(original) <= 0:
errors.append("\n**It seems as though you did not enter a word.**")
if not original.isalpha():
errors.append("\n**Please only use letters.**")
# if <another test>:
# errors.append(<test message>)
if not errors: break
# If we get here, there were some errors -- print them and repeat
print("".join(errors))
# We've broken from the while loop, the input is good
print(original)
或者
# Don't allow multiple errors
def question():
while True:
original = input("Enter a word: ")
err = None
if " " in original:
err = "\n**Please only enter one word.**"
elif len(original) <= 0:
err = "\n**It seems as though you did not enter a word.**"
elif not original.isalpha():
err = "\n**Please only use letters.**"
# elif <another test>:
# err = <test message>
if err is None: break
# If we get here, there was an error -- print it and repeat
print(err)
# We've broken from the while loop, the input is good
print(original)
推荐阅读
- php - 如何使用事件侦听器向用户显示警报消息
- r - 如何在 r 中使用列表元素作为绘图标题?
- c++ - c++中二维数组的两条对角线之和的绝对差
- python - AttributeError:模块 'torch' 没有 PyTorch 的属性 'rfft'
- typescript - Array.fill() 然后更改二维数组中的值会为 JS 中的列提供相同的输出
- cmd - 是否有 CMD 命令将文件移动到下一个更高的文件夹级别?
- android - 有没有办法从原生安卓应用创建 Facebook 事件?
- xamarin.forms - Xamarin Forms LibVlc MediaPlayerElement 在第二页 android 应用程序崩溃
- swiftui - SwiftUI - 如何消除文本内容和文本背景之间的差距?
- android - 在android studio中添加admob sdk时重复类