开始使用python

安装python请查看 python 的安装与初步

首先用svn获取最新的本文档代码,或者下载 google-python-exercises.zip <../static/google-python-exercises.zip> 用于学习过程中的练习。

在linux上开始使用python

我们先来运行一个hello world看看cd到目录google-python-exercises里面:

~/google-python-exercises$ python hello.py
Hello World
~/google-python-exercises$ python hello.py Alex
Hello Alex

交互模式:

~/google-python-exercises]$ python
Python 2.7.3 (default, Apr 24 2012, 00:06:13)
[GCC 4.7.0 20120414 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+1
2
>>> 2**79
604462909807314587353088L
>>> 可以用ctrl-d退出python

再看看我推荐的ipython:

~/google-python-exercises$ ipython
Python 2.7.3 (default, Apr 24 2012, 00:06:13)
Type "copyright", "credits" or "license" for more information.

IPython 0.12.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: 1+1
Out[1]: 2

In [2]: 2**79
Out[2]: 604462909807314587353088L

In [3]:
Do you really want to exit ([y]/n)? y

在Windows上开始python

安装好python之后,打开一个“命令提示符”: 程序->附件->命令提示符。或者xp:开始->运行->cmd+回车, win7: 在开始目录的输入框里输入cmd+回车即可。

然后cd到google-python-exercises目录里面运行python:

C:\google-python-exercises$ python hello.py
Hello World
C:\google-python-exercises$ python hello.py Alex
Hello Alex

如果有上面结果就说明你的python安装好了。如果你安装python过程中出现问题,到math.yeshiwei.com里面讨论吧。

同样可以运行python命令进入交互模式, ctrl+Z退出交互模式。

编辑python文件

pyhont程序就是一个文本文件,你可以直接编辑它。上面”python hello.py”就是运行了一个python程序hello.py。

编写python程序最好有一个比较好的编辑器,帮助你自动缩进:

  • Windows – 不要用记事本写字板,用Notepad++就不错。
  • Linux – 各种编辑器都可以。vim, emacs...我用的是emacs。

编辑器设置

我们希望在你编辑python文件的时候,按tab键插入的是几个空格而不是一个制表符。google-python-exercises里面的文件都是以两个空格作为默认缩进的,在其他程序里面4个空格也很常见。编辑器有自动缩进功能能会非常方便,那样当你写完一行以后按回车,在新的一行里就自动和上一行有一样的缩进了。这里还推荐unix换行符。如果你运行hello.py的时候报错“Unkown option: -”的话, 说明文件的换行符可能出了问题。总之,可以如下设置你的编辑器:

  • Windows Notepad++ – Tabs: Settings > Preferences > Edit Components > Tab settings, and Settings > Preferences > MISC for auto-indent. Line endings: Format > Convert, set to Unix.
  • JEdit (any OS) – Line endings: Little ‘U’ ‘W’ ‘M’ on status bar, set it to ‘U’ (i.e. Unix line-endings)
  • Windows Notepad or Wordpad – do not use
  • Mac TextWrangler – Tabs: Preference button at the top of the window, check Auto Expand Tabs. Can set the default in Defaults > Auto-Expand Tabs and Auto-indent. Line endings: little control at the bottom of each window, set it to Unix
  • Mac TextEdit – do not use
  • Unix pico – Tabs: Esc-q toggles tab mode, Esc-i to turns on auto-indent mode
  • Unix emacs – Tabs: manually set tabs-inserts-spaces mode: M-x set-variable(return) indent-tabs-mode(return) nil