python 基础之第三天

时间:2023-02-15 18:47:07

例子1:8位数的随机密码

 1 #!/usr/bin/python
2 # coding:utf-8
3
4 import string
5 import random
6
7 pwd = ''
8 for i in range(8):
9 char = random.choice(string.printable)
10 pwd += char
11
12 print pwd

验证:

1 [root@master script]# python ranpass.py 
2 9W3HXhrI

改进版:

 1 #!/usr/bin/python
2 # coding:utf-8
3
4 import string
5 import random
6 import sys
7
8
9 def get_pass(num):
10 pwd = ''
11 for i in range(num):
12 char = random.choice(string.printable)
13 pwd += char
14 return pwd
15 if __name__ == '__main__':
16 print get_pass(int(sys.argv[1]))

备注:

In [3]: string.printable
Out[3]: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

 a和b 的值互换:

 1 In [18]: a = 10
2
3 In [19]: b = 20
4
5 In [20]: a,b = b,a
6
7 In [21]: a
8 Out[21]: 20
9
10 In [22]: b
11 Out[22]: 10

程序例子:

创建一个文件,判断文件是否存在,不存在则创建,存在则直接写入数据

关键词:import os ; os.path.isfile('/etc/passwd')  用于判断文件是否存在

os.path.isdir('/etc/') 用于判断目录是否存在

#!/usr/bin/python
#
coding:utf-8


import os
contents
= []
while True:
fname
= raw_input('filename: ')
if not os.path.exists(fname):
break
print '%s already exists,Try again' % fname


while True:
data
= raw_input('<Enter to quit>: ')
if not data:
break
contents.append(data
+ '\n')

f
= open(fname,'w')
f.writelines(contents)
f.close()

通过函数的改进版:

 1 #!/usr/bin/python
2 # coding:utf-8
3
4
5 import os
6 def file_name():
7 while True:
8 fname = raw_input('filename: ')
9 if not os.path.exists(fname):
10 break
11 print '%s already exists,Try again' % fname
12 return fname
13 def content():
14 contents = []
15 while True:
16 data = raw_input('<Enter to quit>: ')
17 if not data:
18 break
19 contents.append(data + '\n')
20 return contents
21 def wfile(fname,contents):
22 f = open(fname,'w')
23 f.writelines(contents)
24 f.close()
25
26 if __name__ == '__main__':
27 wfile(file_name(),content())

##############如何查看python的关键字有哪些#################

In [32]: import keyword
In [
33]: keyword.kwlist
Out[
33]:
[
'and',
'as',
'assert',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'exec',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'not',
'or',
'pass',
'print',
'raise',
'return',
'try',
'while',
'with',
'yield']

In [34]: keyword.iskeyword('def')
Out[34]: True