开始学习python了,争取每天玩一点,写下点心得。
1. 版本选择
官网下载了python 3.3的win安装程序并安装,写了如下简单的测试程序,想看看idle debugger的功能。
CH_TYPE = "ch"
EN_TYPE = "en"
g_name_type = "ch" # ch / en
g_first_name = "hang"
def PrintFullName():
global g_name_type
global g_first_name
last_name = "Zhang"
if g_name_type == CH_TYPE:
print "full name: %s.%s" % (last_name, g_first_name)
if __name__ == "__main__":
PrintFullName()
未曾想,在
print "full name: %s.%s" % (last_name, g_first_name)
一行报语法错误,search后,发现原来python 2和3有很大差异,从python3.0开始,print由2中的一个statement变为3中的print()函数,查看3.3的手册,也学会了print函数的使用。那究竟是使用最新的python3还是使用python2呢?
python的网站上有如下一篇文章:
http://wiki.python.org/moin/Python2orPython3
就目前来看,为了获得更多第三方python库的支持,学习python2会更有利于我。所以我重新安装了python2.7.5
2. idle debugger
在idle中勾选debugger后,会弹出debug control窗口。
窗口中会显示stack中当前函数的globals和locals,以及运行到哪一行代码。
左上角的五个控制按钮的功能:Go,程序运行完毕;Step,程序运行单行,并进入函数;Over,程序运行单行,但不进入函数内部;Out,程序运行直到当前函数返回;Quit,程序退出。
同时,可以在程序中单击右键设定breakpoint。
3. pdb
python还可以使用pdb这个module来进行调试,在python的手册中可以索引到pdb模块的教程。
import pdb
CH_TYPE = "ch"
EN_TYPE = "en"
g_name_type = "ch" # ch / en
g_first_name = "hang"
def PrintFullName():
pdb.set_trace()
global g_name_type
global g_first_name
last_name = "Zhang"
if g_name_type == CH_TYPE:
print "full name: %s.%s" % (last_name, g_first_name)
if __name__ == "__main__":
PrintFullName()
代码中引入pdb,并且在开始debug处调用pdb.set_trace()函数。
这里对几个命令进行了学习:
h(elp) [command]查看某个命令的帮助
condition bpnumber [condition] 条件表达式为真,则断点生效;表达式为空,则所有条件被移除
commands [bpnumber]到达断点时候,执行相应命令,以end为结尾
An example:
(Pdb) commands 1
(com) print some_variable
(com) end
(Pdb)
To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.
With no bpnumber argument, commands refers to the last breakpoint set.
Continue execution until the line with the line number greater than the current one is reached or when returning from current frame.
New in version 2.6.
Set the next line that will be executed. Only available in the bottom-most frame. This lets you jump back and execute code again, or jump forward to skip code that you don’t want to run.
It should be noted that not all jumps are allowed — for instance it is not possible to jump into the middle of afor loop or out of afinally clause.
Evaluate the expression in the current context and print its value.
Note
print can also be used, but is not a debugger command — this executes the Pythonprint statement.