作为一名刚开始学习语言的小小菜鸟,今天真正的体会到了敲代码一定要细心,来不得半点马虎。

    下午,对着书上的一段代码,一句一句的往计算机中输入,准备测试下运行结果(现阶段的我,也就是对着书上的代码敲一敲,体验下运行结果,仅此而已,自己写还是办不到的)。代码如下:

 

 
  
  1. # 以正确的宽度在居中的“盒子”内打印一个句子 
  2. # 注意,整数除法运算符(//)只能用在python 2.2以及后续版本,在之前的版本中,只使用普通除法(/) 
  3.  
  4. se = raw_input("Sentence: "
  5.  
  6. screen_width = 80 
  7. text_width = len(sentence) 
  8. box_width = text_width + 6 
  9. left_margin = (screen_width - box_width) // 2 
  10.  
  11. print 
  12. print ' ' * left_margin + '+'  + '-' * (box_width-4) +  '+' 
  13. print ' ' * left_margin + '| ' + ' ' * text_width    + ' |' 
  14. print ' ' * left_margin + '| ' +       sentence      + ' |' 
  15. print ' ' * left_margin + '| ' + ' ' * text_width    + ' |' 
  16. print ' ' * left_margin + '+'  + '-' * (box_width-4) + '+' 
  17. print 

结果,让人恼火的是,一段代码敲完了,运行之后总是输出错误提示: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了,一个小失误导致后面全局错误,看来敲代码真的是半点马虎不得。

正确的代码:

 

 
  
  1. # 以正确的宽度在居中的“盒子”内打印一个句子 
  2. # 注意,整数除法运算符(//)只能用在python 2.2以及后续版本,在之前的版本中,只使用普通除法(/) 
  3.  
  4. sentence = raw_input("Sentence: "
  5.  
  6. screen_width = 80 
  7. text_width = len(sentence) 
  8. box_width = text_width + 6 
  9. left_margin = (screen_width - box_width) // 2 
  10.  
  11. print 
  12. print ' ' * left_margin + '+'  + '-' * (box_width-4) +  '+' 
  13. print ' ' * left_margin + '| ' + ' ' * text_width    + ' |' 
  14. print ' ' * left_margin + '| ' +       sentence      + ' |' 
  15. print ' ' * left_margin + '| ' + ' ' * text_width    + ' |' 
  16. print ' ' * left_margin + '+'  + '-' * (box_width-4) + '+' 
  17. print 

运行结果:

 

 
  
  1. Sentence: yeah,i have get it 
  2.  
  3.                             +--------------------+ 
  4.                             |                    | 
  5.                             | yeah,i have get it | 
  6.                             |                    | 
  7.                             +--------------------+