在我的代码中,我正在打印菜单
print(num_chars * char)
for option in options:
print("{:d}. {:s}".format(option, options[option]))
print(num_chars * char)
该代码print(num_chars * char)
打印一个分隔符/定界符,以“美化”输出。我从几个编码教程中学到,我不能多次编写相同的代码。
定义函数真的可取吗?
def get_char_repeated(char='*', num_chars=30):
"""
Return the character repeated an arbitrary number of times
"""
return num_chars * char
并在我的原始代码中调用两次?
如果我需要从字典中打印美观的菜单,还有其他选择吗?
谢谢你。
我从几个编码教程中学到,我不能多次编写相同的代码。
称为“不要重复自己”(DRY)的原则是一个很好的粗略指导。对于每个编写过多函数(将代码拆分成较小单元)的程序员,有20个人编写的函数太少。
但是,不要太过分。DRY背后的原因是使以后阅读和更改代码更容易。print(num_chars * char)
已经非常基础,并且非常易于理解和更改,因此将其分解为功能并没有真正的回报。
如果重复的代码增加到3行,则可以(可能应该)将其分解。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句