1 基本使用方法

启动Python/Ipython Shell有几种方式:

  • 命令行窗口键入python并回车
  • 切换到你喜欢的目录,键入ipython notebook并回车
  • 终端中键入Ipython并回车,或者在IDE中打开一个IPython

每次键入命令需要摁下Enter键(REPL中)或者Run Cell按钮(IPython)

你会得到一个显示结果反馈。


In [2]:
8 * 5 + 2


Out[2]:
42

世间真理42,以及


In [3]:
2 ** 100


Out[3]:
1267650600228229401496703205376L

超大整数,或者试试


In [3]:
"The answer to life,the universe,and everything is ?"


Out[3]:
'The answer to life,the universe,and everything is ?'

字符串。

用print打印任意我们想要的内容:

(一个对象在REPL中直接回车和被print分别输出的是他的__repr__和__str__方法对应的字符串)


In [4]:
print "Scala|Python|C"
print 42
print repr(42),str(42)


Scala|Python|C
42
42 42

但是如果需要用户在电脑上输入一些字符怎么办?反复输入和打印字符串也并不方便。

Keep your code DRY (Don't Repeat Yourself)


In [2]:
lang = "Scala|Python|C"
print lang


Scala|Python|C

如果需要标识注释,请以# 符号开始一段语句(这与大部分脚本语言和unix-shell语言一样)。从# 开始直到一行结束的内容都是注释。


In [4]:
#Skip these comments.
print "These lines can be run."
print '''
Whatever.
'''


These lines can be run.
Out[4]:
'\nWhatever.\n'

2 Python变量入门

2.0 Python变量的一些概念

  • 赋值时创建变量本身,绑定名字

  • 动态类型

  • 强类型

  • 可变类型与不可变类型

2.1 Python变量介绍

通常用等号(=)用来给变量赋值。等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值或者一个复合的表达式。

试试在python shell里键入以下内容,每打一行摁下Enter键:


In [3]:
a = 42
b = 42*3
print type(a)
print id(b)
print a*b
b = "Hello,world!"
print type(b)
print id(b)
print b * 2
print b + b
help(id)
#print dir(a),'\n'*2,dir(b)
print isinstance(a,int)


<type 'int'>
4298149336
5292
<type 'str'>
4352948184
Hello,world!Hello,world!
Hello,world!Hello,world!
Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer
    
    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

True

2.2 Python变量赋值与操作

多变量赋值(不推荐):


In [4]:
x = y = z = 42
print x,y,z


42 42 42

当然你也可以为多个对象指定多个变量,例如:


In [9]:
x,y,z = "So long","and thanks for all","the fish"
print x,y,z


So long and thanks for all the fish

赋值的语法糖(Syntax Sugar):


In [6]:
x,y = "So long",42
x,y = y,x
print x
print y


42
So long

Python同样拥有增量赋值方法:


In [4]:
a = 42
a += 1
print a
a -= 1
a *= 2
print a


43
84

类似的能够赋值的操作符还有很多,包括:

  • *= 自乘
  • /= 自除
  • %= 自取模
  • **= 自乘方
  • <<= 自左移位
  • >>= 自右移位
  • &= 自按位与
  • ^= 自按位异或

等等。

注意:Python不支持x++ 或者 --x 这类操作。

2.3 Python数值类型

  • int: 42 126 -680 -0x92
  • bool: True False
  • float: 3.1415926 -90.00 6.022e23
  • complex: 6.23+1.5j -1.23-875j 0+1j

  • type: 判断类型

  • isinstance: 判断属于特定类型(推荐)

In [12]:
a,b,c,d = 42,True,3.1415926,6.23+1.5j
print type(a),type(b),type(c),type(d)
print isinstance(a,int),isinstance(b,(float,int)),\
    isinstance(c,float),isinstance(d,(int,bool))

# 可以分别取得复数的实部和虚部
print d.real
print d.imag


<type 'int'> <type 'bool'> <type 'float'> <type 'complex'>
True True True False
6.23
1.5

工业级的计算器:

基础操作符:

+ - * / // % **

比较操作符:

< <= > >= == !=


In [13]:
d = 6.23+1.5j
e = 0+1j
print d+e,d-e,d*e

print 7*3,7**2  # x**y 返回x的y次幂

print 8%3,float(10)/3,10.0/3,10//3

print 1==2, 1 != 2    #==表示判断是否相等   != 表示不相等
print 7%2           #返回除法的余数

print 1<42<100


(6.23+2.5j) (6.23+0.5j) (-1.5+6.23j)
21 49
2 3.33333333333 3.33333333333 3
False True
1
True

是时候展现真正的除法了:


In [1]:
print 7/4
from __future__ import division
print 7/4


1
1.75

普通floor除法:


In [6]:
print 7//4


1

布尔值:


In [16]:
print not True
print not False
print 40 < 42 <= 100
print not 40 > 30
print 40 > 30 and 40 < 42 <= 100   
print 40 < 30  or 40 < 42 <=100


False
True
True
False
True
True

2.4 Python字符串类型

字符串的长度len与切片:


In [2]:
c = "Hello world"
print len(c)
print c[0],c[1:3]
print c[-1],c[:]
print c[::2],c[::-1]


11
H el
d Hello world
Hlowrd dlrow olleH

复杂切片操作:[start:end:step]


In [18]:
c = "Hello world"
print c[::-1]   #翻转字符串
print c[:]      #原样复制字符串
print c[::2]    #隔一个取一个
print c[:8]     #前八个字母
print c[:8:2]   #前八个字母,每两个取一个


dlrow olleH
Hello world
Hlowrd
Hello wo
Hlow

复制:


In [11]:
c = "Hello world"
d = c[:]        #复制字符串,赋值给d
del c           #删除原字符串
print d         #d 字符串依然可用
e = d[0:4]
print e         #新构造一个截取d字符串部分所组成的串
f = e
print id(f)
print id(e)
del e
print id(f),f        #仍然可用


Hello world
Hell
4369762608
4369762608
4369762608 Hell

加号(+)用于字符串连接运算,星号(*)用来重复字符串。


In [12]:
teststr,stringback="Clojure is","cool"
print '-'*20
print teststr+stringback
print teststr*3
print '-'*20


--------------------
Clojure iscool
Clojure isClojure isClojure is
--------------------

美化打印:


In [21]:
pystr,pystring="Clojure is","cool"
print '-'*20
print pystr,pystring
print '-'*20
print pystr+'\t'+pystring
print '-'*20


--------------------
Clojure is cool
--------------------
Clojure is	cool
--------------------

In [10]:
pystr = "Clojure"
pystring = "cool"
yastr = "LISP"
yastring = "wonderful "
print('Python\'s Format I : {0} is {1}'.format(pystr,pystring))
print 'Python\'s Format II: {language} is {description}'.\
format(language='Scala',description='awesome') #使用\接续换行
print 'C Style Print: %s is %s'%(yastr,yastring)


Python's Format I : Clojure is cool
Python's Format II: Scala is awesome
C Style Print: LISP is wonderful 

字符串复杂效果举例:


In [11]:
for i in range(0,5)+range(2,8)+range(3,12)+[2,2]:
    print' '*(40-2*i-i//2)+'*'*(4*i+1+i)


                                        *
                                      ******
                                   ***********
                                 ****************
                              *********************
                                   ***********
                                 ****************
                              *********************
                            **************************
                         *******************************
                       ************************************
                                 ****************
                              *********************
                            **************************
                         *******************************
                       ************************************
                    *****************************************
                  **********************************************
               ***************************************************
             ********************************************************
                                   ***********
                                   ***********

尾部换行\:


In [24]:
"A:What's your favorite language?\
B:C++."


Out[24]:
"A:What's your favorite language?B:C++."

\t:水平制表符:


In [25]:
print "A:What’s your favorite language?\nB:C++"
print "A:What’s your favorite language?\tB:C++"


A:What’s your favorite language?
B:C++
A:What’s your favorite language?	B:C++

注意其他的转义字符(反斜线+字符):


In [14]:
print 'What\'s your favorite language?'
print "What's your favorite language?"
print "What\"s your favorite language?\\"


What's your favorite language?
What's your favorite language?
What"s your favorite language?\

其他操作 —— Join,Split,Strip, Upper, Lower


In [3]:
s = "a\tb\tc\td"
print s
l = s.split('\t')
print l
snew = ','.join(l)
print snew
line = '\t Blabla \t \n'
print line.strip()
print line.lstrip()
print line.rstrip()
salpha = 'Abcdefg'
print salpha.upper()
print salpha.lower()

#isupper islower isdigit isalpha


a	b	c	d
['a', 'b', 'c', 'd']
a,b,c,d
Blabla
Blabla 	 

	 Blabla
ABCDEFG
abcdefg

更多操作:

  • 查阅dir('s')
  • 查阅codecs
  • 查阅re(regexp,正则表达式)

2.5 初识Python可变类型(Mutables)

  • 字符串(string):不可变
  • 字节数组(bytearray):可变

In [13]:
s = "string"
print type(s)


<type 'str'>

In [14]:
s[3] = "o"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-70c1b7211999> in <module>()
----> 1 s[3] = "o"

TypeError: 'str' object does not support item assignment

In [6]:
s = "String"
sba = bytearray(s)
sba[3] = "o"
print sba


Strong

In [ ]:


In [ ]: