1.查看Python的版本信息
root@zhou-desktop:/home/zhou# python -V //V要大写
Python 2.5.1
2.hello world程序
两种方式,一种是启动解释器
root@zhou-desktop:/home/zhou# python
Python 2.5.1 (r251:54863, May 2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'hello world'
hello world
>>>
退出解释器的方法是Ctrl+D或者Ctrl+Z和Enter
另外一种是启用vim,编辑程序如下:
#!/usr/bin/python
# Filename: helloworld.py
print 'Hello world!'
保存程序,并在终端运行 python helloworld.py
root@zhou-desktop:/home/zhou# python helloworld.py
Hello world!
3. 选择一个程序编辑器
在windows下面建议使用IDLE;
在ubuntu下面建议使用Vim或Emacs.
4. 运行不同目录下的python程序
root@zhou-desktop:/home/zhou# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
root@zhou-desktop:/home/zhou#
root@zhou-desktop:/home/zhou# cp helloworld.py /usr/sbin
root@zhou-desktop:/home/zhou# cd /usr/sbin
root@zhou-desktop:/usr/sbin# python helloworld.py
Hello world!
root@zhou-desktop:/usr/sbin#
5.启用帮助
首先确保你安装了python-doc,如果安装了一般就没什么问题,直接用help()就可以了,否则:
$ env PYTHONDOCS=/usr/share/doc/python-docs-2.3.4/html/ python
Python 2.3.4 (#1, Oct 26 2004, 16:42:40)
[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> help('print')
按q键退出帮助文档
6. 关于常量
字符串常量可以用单引号‘’,双引号“”,或者三引号‘" ""来表示
其实单引号和双引号没什么区别,都可以对一般的字符串常量。而三引号里面则可以换行,如:
'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''
有些特殊的字符串常量如:what's your name?则需要用下述方法来表示:
'what\' your name'
字符串的自动级连
例如,'What\'s' 'your name?'会被自动转为"What's your name?"。
对于数,则需要注意指数型E需要大写,如
1.2E-5
7.关于变量的一个程序
#! /usr/bin/python
# Filename: var.py
i=5
print i
i=i+1
print i
s='''This is a multi-line string.
This is the second line.'''
print s
ss='What\' your name?'
print ss
输出为:
root@zhou-desktop:/home/zhou# python var.py
5
6
This is a multi-line string.
This is the second line.
What' your name?
8.明确的行连接
s = 'This is a string. \
This continues the string.'
print s
输出
This is a string. This continues the string.
而下面一个例子
print \
i
等同于
print i
9.一个错误的例子
# Filename: error.py
i=5
print 'Value is', i # This a space at the beginning of the line.
print 'I repeat, the value is',i
输出为:
root@zhou-desktop:/home/zhou# python error.py
File "error.py", line 3
print 'Value is', i # This a space at the beginning of the line.
^
IndentationError: unexpected indent
这就是关于缩进的问题
10. 关于运算
关于除法
>>> 3/5
0
>>> 3.0/5
0.59999999999999998
>>> 3/5.0
0.59999999999999998
>>> 3.0//5
0.0
关于取模
>>> 8%3
2
>>> 8.0%3
2.0
关于幂
>>> 3**3
27
>>> 3.0**3
27.0
关于乘法
>>> 2*3
6
>>> 2.0*3
6.0
还有很多,日后要多多注意用法