python 学习笔记 1
-- 源自Python基础教程-第二版, 人民邮电出版社
Ubuntu 11.10 自带了 python 2.7.2 and python3.2,若要IDLE或其他版本,则可以从Ubuntu Software Center download.
Under ubuntu, I can run python(link to python2.7) or python2.7 or python3.2
calculate 1 / 2
in 2.7 , it's 0, in 3.2, it's 0.5. So, remember to use 1.0 / 2.0 or 1 // 2
3.0 / 2.0 => 1.5 ; 3.0 // 2.0 => 1.0 ; 3 // 2 => 1 ( note: // means 整除)
% ==> 取余 , e.g.; 5 % 2 ==> 1
2 ** 3 ==> 8 ; means 2 * 2 * 2
int is 32bits, long is 64 bits
1000L, here “L” or “l” means long
8进制 010 = 10进制的8(仅在2.7中有效, 3.2 不能用)
16进制 0x12
变量赋值: x= 8
e.g. x = 8;print(x); //注意:print x在2.7下可以工作, 3.2 不工作
字符串: “hello world” or 'hello world'
字符串转义: 'Let\'s go!' or “print quote(\”)”
字符串拼接: “Hello “ 'World' or “hello “ + 'World'
原始字符串用r开头, 如r'Let\'s go' 就是 'Let\\\'s go'; r相当于c#的@
but if x='hello', y=' world'; x+y is valid, x y is not valid
unicode字符串 u'测试' , 在2.7可用, 3.2不能用,会出错。3.0+只有unicode字符串
get input from console : x=input('intput a number')
some built-in functions: pow(2,3) means 2**3 ==> 8;
abs(-1) ==> 1; round(5.2) ==> 5 ; round(5.8) ==> 6
use module : e.g., import math
int(math.floor(5.2)) ==> 5;
int(5.0) ==> 5
if want import only one function from a module, not all the modules, use
from math import sqrt
e.g.;
import sqrt from math
sqrt(100) ==> 10.0 // in this case, use sqrt directly, no need to add “math.” as prefix
支持复数, import cmath
有趣的__future__
run in command line: python hello.py
in ubuntu, run *.py as executable
first line like #!/usr/bin/env python
or #!/usr/bin/env python3.2
or #!/usr/binenv python2.7
Comment : use #
# this is comment
str() and repr() : how convert something to string
x=str(“ABC”) ;print(x) ==> ABC
y=repr(“ABC”);print(y) ==> 'ABC'
x=str(“Let's go”);print(x) ==> Let's go
y=repr(“Let's go”); print(y) ==> “Let's go”
temp=42; print(“The number is “ + repr(temp))
str, repr和反引号是将python值转为支付串的3种方法, str让字符串易读,而repr和反引号则把结果字符串转换为合法的python表达式
different between input() and raw_input() //only for 2.7
input() expects valid python expressions, like
10,20,2.5
“hello world” # must contain quote in the beginning and the end
varName # varName must exists
在3.2中,raw_input()不存在, input()的功能相当于2.7的input()
浙公网安备 33010602011771号