作为一名刚开始学习语言的小小菜鸟,今天真正的体会到了敲代码一定要细心,来不得半点马虎。
下午,对着书上的一段代码,一句一句的往计算机中输入,准备测试下运行结果(现阶段的我,也就是对着书上的代码敲一敲,体验下运行结果,仅此而已,自己写还是办不到的)。代码如下:
- # 以正确的宽度在居中的“盒子”内打印一个句子
- # 注意,整数除法运算符(//)只能用在python 2.2以及后续版本,在之前的版本中,只使用普通除法(/)
- se = raw_input("Sentence: ")
- screen_width = 80
- text_width = len(sentence)
- box_width = text_width + 6
- left_margin = (screen_width - box_width) // 2
- print ' ' * left_margin + '+' + '-' * (box_width-4) + '+'
- print ' ' * left_margin + '| ' + ' ' * text_width + ' |'
- print ' ' * left_margin + '| ' + sentence + ' |'
- print ' ' * left_margin + '| ' + ' ' * text_width + ' |'
- print ' ' * left_margin + '+' + '-' * (box_width-4) + '+'
结果,让人恼火的是,一段代码敲完了,运行之后总是输出错误提示:Traceback (most recent call last):
File "E:/python/test.py", line 7, in <module>
text_width = len(sentence)
NameError: name 'sentence' is not defined
提示第七行的sentence没有定义,纳闷了,之前命名定义过sentence了啊,检查了几遍也没发现到底错在哪了,对着书上的代码又核实了一遍也没发现错误所在,最后不经意的发现,原来第一行定义变量的时候,变量名称sentence输错了,输入成了上一段代码的sequence了,一个小失误导致后面全局错误,看来敲代码真的是半点马虎不得。
正确的代码:
- # 以正确的宽度在居中的“盒子”内打印一个句子
- # 注意,整数除法运算符(//)只能用在python 2.2以及后续版本,在之前的版本中,只使用普通除法(/)
- sentence = raw_input("Sentence: ")
- screen_width = 80
- text_width = len(sentence)
- box_width = text_width + 6
- left_margin = (screen_width - box_width) // 2
- print ' ' * left_margin + '+' + '-' * (box_width-4) + '+'
- print ' ' * left_margin + '| ' + ' ' * text_width + ' |'
- print ' ' * left_margin + '| ' + sentence + ' |'
- print ' ' * left_margin + '| ' + ' ' * text_width + ' |'
- print ' ' * left_margin + '+' + '-' * (box_width-4) + '+'
运行结果:
- Sentence: yeah,i have get it
- +--------------------+
- | |
- | yeah,i have get it |
- | |
- +--------------------+