python basic1

推荐<Python_精要参考(第二版).pdf>

一、两种python执行方法
方法1:直接在解释器中 >>> print ‘helloWorld'
方法2:将这句代码写到一个文件中,例如hello.py。运行这个文件有三种方式:
    1)在终端中:python hello.py
    2)先编译成.pyc文件
      import py_compile
      py_compile.compile("hello.py")
      再在终端中:python hello.pyc
    3)在终端中:
      python -O -m py_compile hello.py
      python hello.pyo

 二.变量,运算与表达式
1.创建脚本文件
#在文件开头写"#!/usr/bin/python",这是指定该脚本使用的解释器所在的目录。
#因为Linux中python的默认安装目录是"/usr/bin/python"

#!/usr/bin/python 
#filename: hello.py 
def some_func(): #代码段的开始用是冒号(:)隔开
    i=3      #代码段中:代码自身的缩进(一般缩进4个空格)
    print "number is %d" % i
print“hello, world”

2.运算符

 

### compute #######
# raw_input() get input from keyboard to string type
# So we should transfer to int type
# Some new support computing type:
# and or not in is < <= != == | ^ & << + - / % ~ **
print 'Please input a number:'
number = int(raw_input()) 
number += 1
print number**2 # ** 表示次方
print number and 1
print number or 1
print not number
5/2 # 结果是2
5.0/2 # 注意结果是 2.5 

3. 字符串的使用
单引号与双引号在python中等效使用
a. 三引号(’’’或”””)可用来指示跨行的字符串,在其中,单、双引号均可使用。
b. Python中字符串“what’s this”表示方式
   方式1:’what \’s this’. 这里用到了转义符’\’
   方式2:”what’s this”
c. 用r或R指定自然字符串
   r”Happy\n”, 因为用’r’指定为自然字符串,因此’\n’不会被解释器理解为回车换行符,而是’\’和’n’这两个字符,因此打印时会打印出”Happy\n”这7个字符。
d. 用u或U指定使用unicode编码. 如:u”Happy”
e. 连写的两个字符串会被解释器理解为一个连续的字符串
  “what’s”” your name”会被理解为”what’s your name”

三、数据类型
1.数字
通常的int, long,float,long等等都被支持。而且会看你的具体数字来定义变量的类型。如下:

### type of value #######
# int, long, float
# do not need to define the type of value, python will
# do this according to your value
num = 1   # stored as int type
num = 1111111111111   # stored as long int type
num = 1.0   # stored as float type
num = 12L # L stands for long type
num = 1 + 12j # j stands for complex type
num = '1' # string type

2.字符串
单引号,双引号和三引号都可以用来定义字符串。三引号可以定义特别格式的字符串。字符串作为一种序列类型

### type of string #######
num = "1" # string type
num = "Let's go" # string type
num = "He's \"old\"" # string type
mail = "Xiaoyi: \n hello \n I am you!"
mail = """Xiaoyi:
	hello
	I am you!
	""" # special string format
string = 'xiaoyi' # get value by index
copy = string[0] + string[1] + string[2:6] # 切片: [2:6] means [2 5] or[2 6)
copy = string[:4] # start from 1
copy = string[2:] # to end
copy = string[::1] # step is 1, from start to end
copy = string[::2] # step is 2
copy = string[-1] # means 'i', the last one
copy = string[-4:-2:-1] # means 'yoa', -1 step controls direction
memAddr = id(num) # id(num) get the memory address of num
type(num) # get the type of num

3、元组
元组tuple用()来定义。相当于一个可以存储不同类型数据的一个数组。可以用索引来访问,但需要注意的一点是,里面的元素不能被修改。

### sequence type #######
## can access the elements by index or slice
## include: string, tuple(or array? structure? cell?), list
# basis operation of sequence type
firstName = 'Zou'
lastName = 'Xiaoyi'
len(string) # the length
name = firstName + lastName # concatenate 2 string
firstName * 3 # repeat firstName 3 times
'Z' in firstName # check contain or not, return true
string = '123'
max(string)
min(string)
cmp(firstName, lastName) # return 1, -1 or 0

## tuple(or array? structure? cell?)
## define this type using ()
user = ("xiaoyi", 25, "male")
name = user[0]
age = user[1]
gender = user[2]
t1 = () # empty tuple
t2 = (2, ) # when tuple has only one element, we should add a extra comma
user[1] = 26 # error!! the elements can not be changed
name, age, gender = user # can get three element respectively
a, b, c = (1, 2, 3)

4.列表
列表list用[]来定义。它和元组的功能一样,不同的一点是,里面的元素可以修改。List是一个类,支持很多该类定义的方法,这些方法可以用来对list进行操作。

## list type (the elements can be modified)
## define this type using []
userList = ["xiaoyi", 25, "male"]
name = userList[0]
age = userList[1]
gender = userList[2]
userList[3] = 88888 # 报错越界,列表只有3个元素
userList.append(8888) #添加一个对象到末尾
"male" in userList # search
userList[2] = 'female' # can modify the element (the memory address not change)
userList.remove(8888) # remove element
userList.remove(userList[2]) # remove element
del(userList[1]) # use system operation api
## help(list.append)
################################
######## object and class ######
## object = property + method
## python treats anything as class, here the list type is a class,
## when we define a list "userList", so we got a object, and we use
## its method to operate the elements
a. 各种内建方法
>>>list_a = [1, 2]    #/* 定义list_a含有1,2两个对象 */ 
>>>list_a.append(2)   #/* 添加一个对象到末尾 */ 
>>>list_a             #/* 查看list_a中内容 */ 
[1, 2, 2]             #/* shell中显示 */ 
>>>list_a.count(2)    #/* 返回list_a中对象是2的个数 */ 
2                     #/* shell中显示有2个值为2的对象 */ 
>>>list_b = [3, 4]    #/* 定义list_b含有3,4两个对象 */ 
>>>list_a.extend(list_b)   #/* 在list_a末尾添加添加list_b */ 
>>>list_a             #/* 查看list_a中内容 */
[1, 2, 2, 3, 4]       #/* shell中显示 */ 
>>>list_a.index(3)    #/* 返回第1个匹配的指定值在list中的位置,list中第1个对象的位置是0,第2个对象位置是1,以此类推 */ 
3                     #/* shell中显示 */ 
>>>list_a.insert(2,’ok’)  #/* 在位置是2的对象前添加对象’ok’ */ 
>>>list_a                    #/* 查看list_a中内容 */ 
[1, 2, ‘ok’, 2, 3, 4] 
>>>list_a.pop()       #/* 删除并返回list中最后一个对象 */ 
>>>list_a.remove(2)   #/* 删除第1次出现的匹配指定值的对象 */ 
>>>list_a             #/* 查看list_a中内容 */ 
[1, ‘ok’, 2, 3, 4] 
>>>list_a.reverse()   #/* 将list_a中的所有对象的位置反转 */ 
>>>list_a             #/* 查看list_a中内容 */ 
[4, 3, 2, ‘ok’, 1] 
list_a.sort(cmp=None, key=None, reverse=False):对list_a排序

b. 列表使用:下标方式,结合切片操作符’:’
>>>list_a[2] = ‘ok’     #/*给列表中一项赋值*/ 
>>>list_b = list_a[2:]    #/*将list_a[2]起到最后一个元素,都值赋给list_b*/ 
>>>list_b = list_a[:3]    #/*将list_a中第1个至list_a[2]赋给list_b,不包括list_a[3]*/ 
>>>list_b = list_a[1:4]   #/*将list_a[1]至list_a[3]赋给list_b,不包括list_a[4]*/ 
>>>list_b = list_a[1:-1]  #/*将list_[1]至list_a中最后一项赋给list_b。-1表示最后一项,-2表示倒数第2项,以此类推*/

c. 在list中查找数据
for value in list_a: #/* 动作代码块:使用value 的动作 */ 
                     #临时变量value遍历list_a,循环取值,每取到一次值,执行一次动作代码块

d. 用for语句定义列表
>>>my_list = [2*i for i in range(0, 5) if i>2]  #/*形式为 [表达式,变量范围,条件] */
(1) 表达式:2*i,i是变量
(2) 变量范围:for i in range(0,5)
(3) 条件:if i>2
再举一例: 
>>>list_a = [2, 3, 4, 5, 6] 
>>>list_b = [3*i for i in list_a if i%2==0] 
>>>print list_b /*终端显示[6, 12, 18]*/

5.字典
字典dictionary用{}来定义。它的优点是定义像key-value这种键值对的结构,就像struct结构体的功能一样。它也支持字典类支持的方法进行创建和操作。

################################
######## dictionary type ######
## define this type using {}
item = ['name', 'age', 'gender']
value = ['xiaoyi', '25', 'male']
zip(item, value) # zip() will produce a new list: 
# [('name', 'xiaoyi'), ('age', '25'), ('gender', 'male')]
# but we can not define their corresponding relationship
# and we can define this relationship use dictionary type
# This can be defined as a key-value manner
# dic = {key1: value1, key2: value2, ...}, key and value can be any type
dic = {'name': 'xiaoyi', 'age': 25, 'gender': 'male'}
dic = {1: 'zou', 'age':25, 'gender': 'male'}
# and we access it like this: dic[key1], the key as a index
print dic['name']
print dic[1]
# another methods create dictionary
fdict = dict(['x', 1], ['y', 2]) # factory mode
ddict = {}.fromkeys(('x', 'y'), -1) # built-in mode, default value is the same which is none
# access by for circle
for key in dic:
	print key
	print dic[key]

# add key or elements to dictionary, because dictionary is out of sequence,
# so we can directly and a key-value pair like this:
dic['tel'] = 88888 	
# update or delete the elements
del dic[1] # delete this key
dic.pop('tel') # show and delete this key
dic.clear() # clear the dictionary
del dic # delete the dictionary
dic.get(1) # get the value of key
dic.get(1, 'error') # return a user-define message if the dictionary do not contain the key
dic.keys()
dic.values()
dic.has_key(key)
# dictionary has many operations, please use help to check out

 6.python数据结构--集合(sets)
我所理解的,集合的概念就是数学上所称的集合的概念。关于集合的操作,新老版本略有不同。在python2.5版中,sets是作为一个系统模块存在的,并非是内建的数据结构,使用它要导入模块,然后基于list来创建,如:

>>>import sets 
>>>list_a = [1, 2, 3] 
>>>set_a = sets.Set(list_a)#/*基于list_a创建集合set_a注意sets.Set中红色S是大写*/ 
【新版本不必导入模块,可以直接这样定义一个集合:set_a = {1, 2}】 
>>>set_a.add(4)            #/*向set_a中添加元素4*/ 
>>>set_a.discard(2)        #/*删除集合set_a中的元素2*/ 
>>>set_b = set_a.copy()    #/*将set_a内容复制给set_b。*/ 
【“set_b = set_a”表示“引用”关系,并非是复制】 
>>>set_a.remove(2)         #/*从集合set_a中删除2*/ 
>>>set_a.pop()             #/*从集合set_a中随机删除一个值,并返回该值。从空集合中pop会引发KeyError*/ 
>>>set_a.clear()           #/*删除集合中所有的值,留下一个空集合*/ 
>>>set_a.update([5,9,2])   #/*将5,9,2(可以是任意多个值)加入集合,根据数字中集合的概念,相同的值不会重复加入。新版本参数格式或许不同*/ 
>>>set_c = set_a | set_b   #/*set_c为set_a及set_b的并集*/ 
>>>set_c = set_a & set_b   #/*set_c为set_a及set_b的交集*/ 
>>>set_c = set_a - set_b   #/*set_c为set_a去掉与set_b公共的部分*/ 
>>>set_c = set_b - set_a   #/*set_c为set_b去掉与set_a公共的部分*/ 
>>>if 3 in set_a:          #/*判断set_a中是否有元素3*/ 
>>>set_a.issubset(set_b)   #/*判断set_a是否为set_b的子集,返回True 或False*/ 
>>>set_a.issuperset(set_b) #/*判断set_a是否为set_b的超集,返回True 或False*/ 
【if 语句中,空集合为False,任何非空集合为真值】

四、流程控制

1.if-else
If-else用来判断一些条件,以执行满足某种条件的代码。

######## procedure control #####  
## if else  
if expression: # bool type and do not forget the colon  
    statement(s) # use four space key   
  
if expression:   
statement(s) # error!!!! should use four space key   
      
if 1<2:  
    print 'ok, ' # use four space key  
    print 'yeah' # use the same number of space key  
      
if True: # true should be big letter True  
    print 'true'  
  
def fun():  
    return 1  
  
if fun():  
    print 'ok'  
else:  
    print 'no'  
      
con = int(raw_input('please input a number:'))  
if con < 2:  
    print 'small'  
elif con > 3:  
    print 'big'  
else:  
    print 'middle'  
      
if 1 < 2:  
    if 2 < 3:  
        print 'yeah'  
    else:  
        print 'no'    
    print 'out'  
else:  
    print 'bad'  
  
if 1<2 and 2<3 or 2 < 4 not 0: # and, or, not  
    print 'yeah'  

2.for
for的作用是循环执行某段代码。还可以用来遍历我们上面所提到的序列类型的变量。

######## procedure control #####  
## for  
for iterating_val in sequence:  
    statements(s)  
# sequence type can be string, tuple or list  
  
for i in "abcd":  
    print i  
  
for i in [1, 2, 3, 4]:  
    print i  
  
# range(start, end, step), if not set step, default is 1,   
# if not set start, default is 0, should be noted that it is [start, end), not [start, end]  
range(5) # [0, 1, 2, 3, 4]  
range(1, 5) # [1, 2, 3, 4]  
range(1, 10, 2) # [1, 3, 5, 7, 9]  
for i in range(1, 100, 1):   
    print i  
  
# ergodic for basis sequence  
fruits = ['apple', 'banana', 'mango']  
for fruit in range(len(fruits)):   
    print 'current fruit: ', fruits[fruit]  
  
# ergodic for dictionary  
dic = {1: 111, 2: 222, 5: 555}  
for x in dic:  
    print x, ': ', dic[x]  
      
dic.items() # return [(1, 111), (2, 222), (5, 555)]  
for key,value in dic.items(): # because we can: a,b=[1,2]  
    print key, ': ', value  
else:  
    print 'ending'  
  
################################  
import time  
# we also can use: break, continue to control process  
for x in range(1, 11):  
    print x  
    time.sleep(1) # sleep 1s  
    if x == 3:  
        pass # do nothing  
    if x == 2:  
        continue  
    if x == 6:  
        break  
    if x == 7:    
        exit() # exit the whole program  
    print '#'*50  

3.while
while的用途也是循环。它首先检查在它后边的循环条件,若条件表达式为真,它就执行冒号后面的语句块,然后再次测试循环条件,直至为假。冒号后面的缩近语句块为循环体。

######## procedure control #####  
## while  
while expression:  
    statement(s)  
  
while True:  
    print 'hello'  
    x = raw_input('please input something, q for quit:')  
    if x == 'q':  
        break  
else:  
    print 'ending'  

4.switch
其实Python并没有提供switch结构,但我们可以通过字典和函数轻松的进行构造。例如:

## switch ####  
## this structure do not support by python  
## but we can implement it by using dictionary and function  
## cal.py ##  
#!/usr/local/python  
  
from __future__ import division  
# if used this, 5/2=2.5, 6/2=3.0  
  
def add(x, y):  
    return x + y  
def sub(x, y):  
    return x - y  
def mul(x, y):  
    return x * y  
def div(x, y):  
    return x / y  
  
operator = {"+": add, "-": sub, "*": mul, "/": div}  
operator["+"](1, 2) # the same as add(1, 2)  
operator["%"](1, 2) # error, not have key "%", but the below will not  
operator.get("+")(1, 2) # the same as add(1, 2)  
  
def cal(x, o, y):  
    print operator.get(o)(x, y)  
cal(2, "+", 3)  
# this method will effect than if-else

五、函数
1.自定义函数
在Python中,使用def语句来创建函数:

######## function #####   
def functionName(parameters): # no parameters is ok  
    bodyOfFunction  
  
def add(a, b):  
    return a+b # if we do not use a return, any defined function will return default None   
      
a = 100  
b = 200  
sum = add(a, b)  
  
##### function.py #####  
#!/usr/bin/python  
#coding:utf8  # support chinese  
def add(a = 1, b = 2): # default parameters  
    return a+b  # can return any type of data  
# the followings are all ok  
add()  
add(2)  
add(y = 1)  
add(3, 4)  
  
###### the global and local value #####  
## global value: defined outside any function, and can be used  
##              in anywhere, even in functions, this should be noted  
## local value: defined inside a function, and can only be used  
##              in its own function  
## the local value will cover the global if they have the same name  
val = 100 # global value  
def fun():  
    print val # here will access the val = 100  
print val # here will access the val = 100, too  
  
def fun():  
    a = 100 # local value  
    print a  
print a # here can not access the a = 100  
  
def fun():  
    global a = 100 # declare as a global value  
    print a  
  
print a # here can not access the a = 100, because fun() not be called yet  
fun()  
print a # here can access the a = 100  
  
############################  
## other types of parameters  
def fun(x):  
    print x  
# the follows are all ok  
fun(10) # int  
fun('hello') # string  
fun(('x', 2, 3))  # tuple  
fun([1, 2, 3])    # list  
fun({1: 1, 2: 2}) # dictionary  
  
## tuple  
def fun(x, y):  
    print "%s : %s" % (x,y) # %s stands for string  
fun('Zou', 'xiaoyi')  
tu = ('Zou', 'xiaoyi')  
fun(*tu)    # can transfer tuple parameter like this  
  
## dictionary  
def fun(name = "name", age = 0):  
    print "name: %s" % name  
    print "age: " % age  
dic = {name: "xiaoyi", age: 25} # the keys of dictionary should be same as fun()  
fun(**dic) # can transfer dictionary parameter like this  
fun(age = 25, name = 'xiaoyi') # the result is the same  
## the advantage of dictionary is can specify value name  
  
#############################  
## redundancy parameters ####  
## the tuple  
def fun(x, *args): # the extra parameters will stored in args as tuple type   
    print x  
    print args  
# the follows are ok  
fun(10)  
fun(10, 12, 24) # x = 10, args = (12, 24)  
  
## the dictionary  
def fun(x, **args): # the extra parameters will stored in args as dictionary type   
    print x  
    print args  
# the follows are ok  
fun(10)  
fun(x = 10, y = 12, z = 15) # x = 10, args = {'y': 12, 'z': 15}  
  
# mix of tuple and dictionary  
def fun(x, *args, **kwargs):  
    print x  
    print args  
    print kwargs  
fun(1, 2, 3, 4, y = 10, z = 12) # x = 1, args = (2, 3, 4), kwargs = {'y': 10, 'z': 12}  

2.Lambda函数
Lambda函数用来定义一个单行的函数,其便利在于:

## lambda function ####  
## define a fast single line function  
fun = lambda x,y : x*y # fun is a object of function class  
fun(2, 3)  
# like  
def fun(x, y):  
    return x*y  
  
## recursion  
# 5=5*4*3*2*1, n!  
def recursion(n):  
    if n > 0:  
        return n * recursion(n-1) ## wrong  
  
def mul(x, y):  
    return x * y  
numList = range(1, 5)  
reduce(mul, numList) # 5! = 120  
reduce(lambda x,y : x*y, numList) # 5! = 120, the advantage of lambda function avoid defining a function  
  
### list expression  
numList = [1, 2, 6, 7]  
filter(lambda x : x % 2 == 0, numList)  
print [x for x in numList if x % 2 == 0] # the same as above  
map(lambda x : x * 2 + 10, numList)  
print [x * 2 + 10 for x in numList] # the same as above 

3.Python内置函数
Python内置了很多函数,他们都是一个个的.py文件,在python的安装目录可以找到。弄清它有那些函数,对我们的高效编程非常有用。这样就可以避免重复的劳动了。下面也只是列出一些常用的:

## built-in function of python ####  
## if do not how to use, please use help()  
abs, max, min, len, divmod, pow, round, callable,  
isinstance, cmp, range, xrange, type, id, int()  
list(), tuple(), hex(), oct(), chr(), ord(), long()  
  
callable # test a function whether can be called or not, if can, return true  
# or test a function is exit or not  
  
isinstance # test type  
numList = [1, 2]  
if type(numList) == type([]):  
    print "It is a list"  
if isinstance(numList, list): # the same as above, return true  
    print "It is a list"  
      
for i in range(1, 10001) # will create a 10000 list, and cost memory  
for i in xrange(1, 10001)# do not create such a list, no memory is cost  
  
## some basic functions about string  
str = 'hello world'  
str.capitalize() # 'Hello World', first letter transfer to big  
str.replace("hello", "good") # 'good world'  
ip = "192.168.1.123"  
ip.split('.') # return ['192', '168', '1', '123']  
help(str.split)  
  
import string  
str = 'hello world'  
string.replace(str, "hello", "good") # 'good world'  
  
## some basic functions about sequence  
len, max, min  
# filter(function or none, sequence)  
def fun(x):  
    if x > 5:  
        return True  
numList = [1, 2, 6, 7]  
filter(fun, numList) # get [6, 7], if fun return True, retain the element, otherwise delete it  
filter(lambda x : x % 2 == 0, numList)  
# zip()  
name = ["me", "you"]  
age = [25, 26]  
tel = ["123", "234"]  
zip(name, age, tel) # return a list: [('me', 25, '123'), ('you', 26, '234')]  
# map()  
map(None, name, age, tel) # also return a list: [('me', 25, '123'), ('you', 26, '234')]  
test = ["hello1", "hello2", "hello3"]  
zip(name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2')]  
map(None, name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2'), (None, None, None, 'hello3')]  
a = [1, 3, 5]  
b = [2, 4, 6]  
def mul(x, y):  
    return x*y  
map(mul, a, b) # return [2, 12, 30]  
# reduce()  
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # return ((((1+2)+3)+4)+5) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值