python 基础之第二天
1 [root@master script]# vim while_counter.py 2 #!/usr/bin/python 3 # coding: utf-8 4 5 sum = 0 6 counter = 0 7 8 while counter < 101: 9 sum += counter 10 counter += 1 11 print sum
1 [root@master script]# cat game.py 2 #!/usr/bin/python 3 # coding: utf-8 4 import random 5 ch_list = ["剪刀","石头","布"] 6 prompt = """ 7 (0) 剪刀 8 (1) 石头 9 (2) 布 10 请选择(0/1/2): 11 """ 12 win_list = [["石头","剪刀"],["布","石头"],['剪刀',"布"]] 13 computer = random.choice(ch_list) 14 ind = int(raw_input(prompt)) 15 player = ch_list[ind] 16 17 print 'Your_choice:%s,computer_choice:%s' % (player,computer) 18 19 if [player,computer] in win_list: 20 print '\033[31;1mplayer win !!!!\033[0m' 21 elif player == computer: 22 print '\033[32;1m平局\033[0m' 23 24 else: 25 print '\033[33;1mcomputer win!!!\033[0m'
###############range用法################
1 >>> range(10) 2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 3 >>> range(1,10,2) 4 [1, 3, 5, 7, 9] 5 >>> range(2,10,2) 6 [2, 4, 6, 8] 7 >>> range(10,1,-1) 8 [10, 9, 8, 7, 6, 5, 4, 3, 2]
##################len用法###############
1 [fush@xm35 ~ 11:11:47]$ vim alist.py 2 #!/usr/bin/python 3 # coding: utf-8 4 5 alist = ['bob','jerry','hali','cherry'] 6 7 for i in range(len(alist)): 8 print '%s: %s' %(i,alist[i]) 9 10 [fush@xm35 ~ 11:12:11]$ python alist.py 11 0: bob 12 1: jerry 13 2: hali 14 3: cherry
###############斐波那契数列##############
#!/usr/bin/python # coding: utf-8 alist = [0,1] for i in range(8): sum = alist[-1] + alist[-2] alist.append(sum) for n in alist: print n, [root@master script]# python fbnq.py 0 1 1 2 3 5 8 13 21 34 ####改进######### [root@master script]# vim fbnq.py #!/usr/bin/python # coding: utf-8 alist = [0,1] num = int(raw_input('Please a number: ')) for i in range(num): sum = alist[-1] + alist[-2] alist.append(sum) for n in alist: print n, [root@master script]# python fbnq.py Please a number: 11 0 1 1 2 3 5 8 13 21 34 55 89 144 [root@master script]# python fbnq.py Please a number: 9 0 1 1 2 3 5 8 13 21 34 55
###############os.system 返回码###############
os.system()操作的结果是一个等价于echo $? 的一个值,成功为0,不成功非0值
1 [root@master script]# vim system.py 2 #!/usr/bin/python 3 # coding:utf-8 4 5 import os 6 7 result = os.system('cat /etc/passwd &> /dev/null') 8 print result 9 10 [root@master script]# python system.py 11 0
ping 主机连通性例子:
1 [root@master script]# vim ping.py 2 #!/usr/bin/python 3 # coding:utf-8 4 5 import os 6 7 for i in range(1,255): 8 ip = '192.168.244.%s' % i 9 result = os.system('ping -c2 %s &> /dev/null' % ip) 10 if result: 11 print '%s: down' % ip 12 else: 13 print '%s: up' % ip 14 15 检测: 16 [root@master script]# python ping.py 17 192.168.244.1: down 18 192.168.244.2: up 19 192.168.244.3: down 20 192.168.244.4: down 21 192.168.244.5: down
多线程:
##################解析列表##############
1 >>> ['hello' for i in range(3)] 2 ['hello', 'hello', 'hello'] 3 >>> [10 for i in range(3)] 4 [10, 10, 10] 5 >>> [i for i in range(10)] 6 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 7 >>> [i**2 for i in range(10)] 8 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 9 >>> [i**2 for i in range(10) if i%2] 10 [1, 9, 25, 49, 81]
#############文件对象##############
1.文件读取
例子:
1 >>> f = open('/etc/hosts') 2 >>> data = f.read() 3 >>> print data, 4 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 5 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 6 192.168.244.200 master 7 192.168.244.201 slave1 8 192.168.244.202 slave2 9 >>> f.close()
2.文件写入
1 >>> f= open('hi.txt','w') 2 >>> f.write('hello\n') 3 >>> f.close() 4 >>> f= open('hi.txt','a') 5 >>> f.write('fush\n') 6 >>> f.flush()
注释:‘w’表示以只写方式,不能读取,再次写入内容会覆盖前面的内容,‘a’ 追加内容
>>> f.writelines(['1st line.\n','2th line.\n'])
[root@master script]# cat /root/hi.txt
111
1st line.
2th line.
###########cp例子###########
1 [root@master script]# vim cp.py 2 #!/usr/bin/python 3 # coding:utf-8 4 5 f = open('/etc/passwd') 6 k = open('/root/passwd','a') 7 while True: 8 data = f.read(4096) 9 if not data: 10 break 11 k.write(data) 12 13 f.close() 14 k.close() 15 16 检测: 17 [root@master script]# python cp.py 18 [root@master script]# cat /root/passwd 19 root:x:0:0:root:/root:/bin/bash 20 bin:x:1:1:bin:/bin:/sbin/nologin 21 daemon:x:2:2:daemon:/sbin:/sbin/nologin 22 adm:x:3:4:adm:/var/adm:/sbin/nologin 23 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 24 sync:x:5:0:sync:/sbin:/bin/sync 25 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown 26 halt:x:7:0:halt:/sbin:/sbin/halt 27 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 28 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin 29 operator:x:11:0:operator:/root:/sbin/nologin 30 games:x:12:100:games:/usr/games:/sbin/nologin 31 gopher:x:13:30:gopher:/var/gopher:/sbin/nologin 32 ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin 33 nobody:x:99:99:Nobody:/:/sbin/nologin 34 vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin 35 saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin 36 postfix:x:89:89::/var/spool/postfix:/sbin/nologin 37 sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
1 改进版:函数方式 2 3 [root@master script]# vim cp.py 4 #!/usr/bin/python 5 # coding:utf-8 6 7 def cp(sfname,dfname): 8 f = open(sfname) 9 k = open(dfname,'w') 10 while True: 11 data = f.read(4096) 12 if not data: 13 break 14 k.write(data) 15 16 f.close() 17 k.close() 18 sname = raw_input('source_name: ') 19 dname = raw_input('destination_name: ') 20 cp(sname,dname) 21 22 检测: 23 [root@master script]# python cp.py 24 source_name: /etc/passwd 25 destination_name: /usr/local/src/passwd 26 [root@master script]# cat /usr/local/src/passwd 27 root:x:0:0:root:/root:/bin/bash 28 bin:x:1:1:bin:/bin:/sbin/nologin 29 daemon:x:2:2:daemon:/sbin:/sbin/nologin 30 adm:x:3:4:adm:/var/adm:/sbin/nologin 31 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 32 sync:x:5:0:sync:/sbin:/bin/sync 33 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown 34 halt:x:7:0:halt:/sbin:/sbin/halt 35 mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 36 uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin 37 operator:x:11:0:operator:/root:/sbin/nologin 38 games:x:12:100:games:/usr/games:/sbin/nologin 39 gopher:x:13:30:gopher:/var/gopher:/sbin/nologin 40 ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin 41 nobody:x:99:99:Nobody:/:/sbin/nologin 42 vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin 43 saslauth:x:499:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin 44 postfix:x:89:89::/var/spool/postfix:/sbin/nologin 45 sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
1 增强版: 2 [root@master script]# vim cp.py 3 #!/usr/bin/python 4 # coding:utf-8 5 6 import sys 7 def cp(sfname,dfname): 8 f = open(sfname) 9 k = open(dfname,'w') 10 while True: 11 data = f.read(4096) 12 if not data: 13 break 14 k.write(data) 15 16 f.close() 17 k.close() 18 cp(sys.argv[1],sys.argv[2]) 19 20 检测: 21 [root@master script]# python cp.py /etc/hosts /home/zhuji 22 [root@master script]# cat !$ 23 cat /home/zhuji 24 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 25 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 26 192.168.244.200 master 27 192.168.244.201 slave1 28 192.168.244.202 slave2
##############函数初识##################
[root@master ~]# vim func01.py #!/usr/bin/python # coding:utf-8 def pstar(): print '*' * 20 print '#' * 20 a= pstar() print a [root@master ~]# python func01.py ******************** #################### None
备注:当函数没有返回值,返回None
形参例子:
1 [root@master ~]# vim func01.py 2 #!/usr/bin/python 3 # coding:utf-8 4 5 def pstar(num): 6 return '*' * num 7 8 n = int(raw_input('number: ')) 9 print pstar(n) 10 11 12 [root@master ~]# python func01.py 13 number: 15 14 ***************
默认参数例子:
[root@master ~]# vim func01.py
#!/usr/bin/python
# coding:utf-8
def pstar(num=20):
return '*' * num
n = int(raw_input('number: '))
print pstar()
print pstar(n)
[root@master ~]# python func01.py
number: 15
********************
***************
备注:调用函数不带参数时,用默认参数20;有带参数时,不用默认,会覆盖默认的参数
##############函数的位置参数#############
1 [root@master script]# vim position.py 2 #!/usr/bin/python 3 # coding:utf-8 4 5 import sys 6 7 print sys.argv 8 9 检测: 10 [root@master script]# ./position.py 11 ['./position.py'] 12 [root@master script]# ./position.py hello 13 ['./position.py', 'hello'] 14 [root@master script]# ./position.py hello fush 15 ['./position.py', 'hello', 'fush']
备注:sys.argv 是一个list
###############模块相关################
1 >>> import string 2 >>> string.upper('abc') 3 'ABC' 4 >>> string.__file__ 5 '/usr/lib64/python2.6/string.pyc' ###string模块文件位置 6 7 查看模块文件: 8 [root@master script]# vim /usr/lib64/python2.6/string.py 9 """A collection of string operations (most are no longer used). 10 11 Warning: most of the code you see here isn't normally used nowadays. 12 Beginning with Python 1.6, many of these functions are implemented as 13 """A collection of string operations (most are no longer used).
1 导入模块: 2 >>> from random import choice ##只导入random的choice 3 >>> choice('adfe') 4 'a' 5 >>> choice('adfe') 6 'a' 7 >>> choice('adfe') 8 'd' 9 >>> choice('adfe') 10 'd' 11 >>> choice('adfe') 12 'e' 13 >>> choice('adfe') 14 'f' 15 >>> random.choice('fush') ###前面没有导入random,会报错 16 Traceback (most recent call last): 17 File "<stdin>", line 1, in <module> 18 NameError: name 'random' is not defined 19 >>> import random as rdm ##把random模块起了个别名rdm 20 >>> rdm.choice('fush') 21 's' 22 >>> rdm.choice('fush') 23 's' 24 >>> rdm.choice('fush') 25 'f'