学习永远都是“理论”与“实践”相结合效果最好。
这里有python入门的120个基础练习(1~40),希望对你有用。
01-Hello World
python的语法逻辑完全靠缩进,建议缩进4个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。 下面示例中,满足if条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。
1 print(\'hello world!\') 2 3 if 3 > 0: 4 print(\'OK\') 5 print(\'yes\') 6 7 x = 3; y = 4 # 不推荐,还是应该写成两行 8 print(x + y)
02-print
1 print(\'hello world!\') 2 print(\'hello\', \'world!\') # 逗号自动添加默认的分隔符:空格 3 print(\'hello\' + \'world!\') # 加号表示字符拼接 4 print(\'hello\', \'world\', sep=\'***\') # 单词间用***分隔 5 print(\'#\' * 50) # *号表示重复50遍 6 print(\'how are you?\', end=\'\') # 默认print会打印回车,end=\'\'表示不要回车
03-基本运算
运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符。最好使用括号,增加了代码的可读性。
1 print(5 / 2) # 2.5 2 print(5 // 2) # 丢弃余数,只保留商 3 print(5 % 2) # 求余数 4 print(5 ** 3) # 5的3次方 5 print(5 > 3) # 返回True 6 print(3 > 5) # 返回False 7 print(20 > 10 > 5) # python支持连续比较 8 print(20 > 10 and 10 > 5) # 与上面相同含义 9 print(not 20 > 10) # False
04-input
1 number = input("请输入数字: ") # input用于获取键盘输入 2 print(number) 3 print(type(number)) # input获得的数据是字符型 4 5 print(number + 10) # 报错,不能把字符和数字做运算 6 print(int(number) + 10) # int可将字符串10转换成数字10 7 print(number + str(10)) # str将10转换为字符串后实现字符串拼接
05-输入输出基础练习
1 username = input(\'username: \') 2 print(\'welcome\', username) # print各项间默认以空格作为分隔符 3 print(\'welcome \' + username) # 注意引号内最后的空格
06-字符串使用基础
python中,单双引号没有区别,表示一样的含义
1 sentence = \'tom\\'s pet is a cat\' # 单引号中间还有单引号,可以转义 2 sentence2 = "tom\'s pet is a cat" # 也可以用双引号包含单引号 3 sentence3 = "tom said:\"hello world!\"" 4 sentence4 = \'tom said:"hello world"\' 5 # 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串 6 words = """ 7 hello 8 world 9 abcd""" 10 print(words) 11 12 py_str = \'python\' 13 len(py_str) # 取长度 14 py_str[0] # 第一个字符 15 \'python\'[0] 16 py_str[-1] # 最后一个字符 17 # py_str[6] # 错误,下标超出范围 18 py_str[2:4] # 切片,起始下标包含,结束下标不包含 19 py_str[2:] # 从下标为2的字符取到结尾 20 py_str[:2] # 从开头取到下标是2之前的字符 21 py_str[:] # 取全部 22 py_str[::2] # 步长值为2,默认是1 23 py_str[1::2] # 取出yhn 24 py_str[::-1] # 步长为负,表示自右向左取 25 26 py_str + \' is good\' # 简单的拼接到一起 27 py_str * 3 # 把字符串重复3遍 28 29 \'t\' in py_str # True 30 \'th\' in py_str # True 31 \'to\' in py_str # False 32 \'to\' not in py_str # True
07-列表基础
列表也是序列对象,但它是容器类型,列表中可以包含各种数据
1 **alist = [10, 20, 30, \'bob\', \'alice\', [1,2,3]] 2 len(alist) 3 alist[-1] # 取出最后一项 4 alist[-1][-1] # 因为最后一项是列表,列表还可以继续取下标 5 [1,2,3][-1] # [1,2,3]是列表,[-1]表示列表最后一项 6 alist[-2][2] # 列表倒数第2项是字符串,再取出字符下标为2的字符 7 alist[3:5] # [\'bob\', \'alice\'] 8 10 in alist # True 9 \'o\' in alist # False 10 100 not in alist # True 11 alist[-1] = 100 # 修改最后一项的值 12 alist.append(200) # 向**列表中追加一项
08-元组基础
元组与列表基本上是一样的,只是元组不可变,列表可变。
1 atuple = (10, 20, 30, \'bob\', \'alice\', [1,2,3]) 2 len(atuple) 3 10 in atuple 4 atuple[2] 5 atuple[3:5] 6 # atuple[-1] = 100 # 错误,元组是不可变的
09-字典基础
1 # 字典是key-value(键-值)对形式的,没有顺序,通过键取出值 2 adict = {\'name\': \'bob\', \'age\': 23} 3 len(adict) 4 \'bob\' in adict # False 5 \'name\' in adict # True 6 adict[\'email\'] = \'bob@tedu.cn\' # 字典中没有key,则添加新项目 7 adict[\'age\'] = 25 # 字典中已有key,修改对应的value
10-基本判断
单个的数据也可作为判断条件。 任何值为0的数字、空对象都是False,任何非0数字、非空对象都是True。
1 if 3 > 0: 2 print(\'yes\') 3 print(\'ok\') 4 5 if 10 in [10, 20, 30]: 6 print(\'ok\') 7 8 if -0.0: 9 print(\'yes\') # 任何值为0的数字都是False 10 11 if [1, 2]: 12 print(\'yes\') # 非空对象都是True 13 14 if \' \': 15 print(\'yes\') # 空格字符也是字符,条件为True
11-条件表达式、三元运算符
1 a = 10 2 b = 20 3 4 if a < b: 5 smaller = a 6 else: 7 smaller = b 8 9 print(smaller) 10 11 s = a if a < b else b # 和上面的if-else语句等价 12 13 print(s)
12-判断练习:用户名和密码是否正确
1 import getpass # 导入模块 2 3 username = input(\'username: \') 4 # getpass模块中,有一个方法也叫getpass 5 password = getpass.getpass(\'password: \') 6 7 if username == \'bob\' and password == \'123456\': 8 print(\'Login successful\') 9 else: 10 print(\'Login incorrect\')
13-猜数:基础实现
1 import random 2 3 num = random.randint(1, 10) # 随机生成1-10之间的数字 4 answer = int(input(\'guess a number: \')) # 将用户输入的字符转成整数 5 if answer > num: 6 print(\'猜大了\') 7 elif answer < num: 8 print(\'猜小了\') 9 else: 10 print(\'猜对了\') 11 12 print(\'the number:\', num)
14-成绩分类1
1 score = int(input(\'分数: \')) 2 3 if score >= 90: 4 print(\'优秀\') 5 elif score >= 80: 6 print(\'好\') 7 elif score >= 70: 8 print(\'良\') 9 elif score >= 60: 10 print(\'及格\') 11 else: 12 print(\'你要努力了\')
15-成绩分类2
1 score = int(input(\'分数: \')) 2 3 if score >= 60 and score < 70: 4 print(\'及格\') 5 elif 70 <= score < 80: 6 print(\'良\') 7 elif 80 <= score < 90: 8 print(\'好\') 9 elif score >= 90: 10 print(\'优秀\') 11 else: 12 print(\'你要努力了\')
16-石头剪刀布
1 import random 2 3 all_choices = [\'石头\', \'剪刀\', \'布\'] 4 computer = random.choice(all_choices) 5 player = input(\'请出拳: \') 6 7 # print(\'Your choice:\', player, "Computer\'s choice:", computer) 8 print("Your choice: %s, Computer\'s choice: %s" % (player, computer)) 9 if player == \'石头\': 10 if computer == \'石头\': 11 print(\'平局\') 12 elif computer == \'剪刀\': 13 print(\'You WIN!!!\') 14 else: 15 print(\'You LOSE!!!\') 16 elif player == \'剪刀\': 17 if computer == \'石头\': 18 print(\'You LOSE!!!\') 19 elif computer == \'剪刀\': 20 print(\'平局\') 21 else: 22 print(\'You WIN!!!\') 23 else: 24 if computer == \'石头\': 25 print(\'You WIN!!!\') 26 elif computer == \'剪刀\': 27 print(\'You LOSE!!!\') 28 else: 29 print(\'平局\')
17-改进的石头剪刀布
1 import random 2 3 all_choices = [\'石头\', \'剪刀\', \'布\'] 4 win_list = [[\'石头\', \'剪刀\'], [\'剪刀\', \'布\'], [\'布\', \'石头\']] 5 prompt = """(0) 石头 6 (1) 剪刀 7 (2) 布 8 请选择(0/1/2): """ 9 computer = random.choice(all_choices) 10 ind = int(input(prompt)) 11 player = all_choices[ind] 12 13 print("Your choice: %s, Computer\'s choice: %s" % (player, computer)) 14 if player == computer: 15 print(\'\033[32;1m平局\033[0m\') 16 elif [player, computer] in win_list: 17 print(\'\033[31;1mYou WIN!!!\033[0m\') 18 else: 19 print(\'\033[31;1mYou LOSE!!!\033[0m\')
18-猜数,直到猜对
1 import random 2 3 num = random.randint(1, 10) 4 running = True 5 6 while running: 7 answer = int(input(\'guess the number: \')) 8 if answer > num: 9 print(\'猜大了\') 10 elif answer < num: 11 print(\'猜小了\') 12 else: 13 print(\'猜对了\') 14 running = False
19-猜数,5次机会
1 import random 2 3 num = random.randint(1, 10) 4 counter = 0 5 6 while counter < 5: 7 answer = int(input(\'guess the number: \')) 8 if answer > num: 9 print(\'猜大了\') 10 elif answer < num: 11 print(\'猜小了\') 12 else: 13 print(\'猜对了\') 14 break 15 counter += 1 16 else: # 循环被break就不执行了,没有被break才执行 17 print(\'the number is:\', num)
20-while循环,累加至100
因为循环次数是已知的,实际使用时,建议用for循环
1 sum100 = 0 2 counter = 1 3 4 while counter < 101: 5 sum100 += counter 6 counter += 1 7 8 print(sum100)
21-while-break
break是结束循环,break之后、循环体内代码不再执行。
1 while True: 2 yn = input(\'Continue(y/n): \') 3 if yn in [\'n\', \'N\']: 4 break 5 print(\'running...\')
22-while-continue
计算100以内偶数之和。
continue是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0 counter = 0 while counter < 100: counter += 1 # if counter % 2: if counter % 2 == 1: continue sum100 += counter print(sum100)
23-for循环遍历数据对象
1 astr = \'hello\' 2 alist = [10, 20, 30] 3 atuple = (\'bob\', \'tom\', \'alice\') 4 adict = {\'name\': \'john\', \'age\': 23} 5 6 for ch in astr: 7 print(ch) 8 9 for i in alist: 10 print(i) 11 12 for name in atuple: 13 print(name) 14 15 for key in adict: 16 print(\'%s: %s\' % (key, adict[key]))
24-range用法及数字累加
1 # range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2 # >>> list(range(10)) 3 # range(6, 11) # [6, 7, 8, 9, 10] 4 # range(1, 10, 2) # [1, 3, 5, 7, 9] 5 # range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 6 sum100 = 0 7 8 for i in range(1, 101): 9 sum100 += i 10 11 print(sum100)
25-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
1 fib = [0, 1] 2 3 for i in range(8): 4 fib.append(fib[-1] + fib[-2]) 5 6 print(fib)
26-九九乘法表
1 for i in range(1, 10): 2 for j in range(1, i + 1): 3 print(\'%s*%s=%s\' % (j, i, i * j), end=\' \') 4 print() 5 6 # i=1 ->j: [1] 7 # i=2 ->j: [1,2] 8 # i=3 ->j: [1,2,3] 9 #由用户指定相乘到多少 10 n = int(input(\'number: \')) 11 12 for i in range(1, n + 1): 13 for j in range(1, i + 1): 14 print(\'%s*%s=%s\' % (j, i, i * j), end=\' \') 15 print()
27-逐步实现列表解析
1 # 10+5的结果放到列表中 2 [10 + 5] 3 # 10+5这个表达式计算10次 4 [10 + 5 for i in range(10)] 5 # 10+i的i来自于循环 6 [10 + i for i in range(10)] 7 [10 + i for i in range(1, 11)] 8 # 通过if过滤,满足if条件的才参与10+i的运算 9 [10 + i for i in range(1, 11) if i % 2 == 1] 10 [10 + i for i in range(1, 11) if i % 2] 11 # 生成IP地址列表 12 [\'192.168.1.%s\' % i for i in range(1, 255)]
28-三局两胜的石头剪刀布
1 import random 2 3 all_choices = [\'石头\', \'剪刀\', \'布\'] 4 win_list = [[\'石头\', \'剪刀\'], [\'剪刀\', \'布\'], [\'布\', \'石头\']] 5 prompt = """(0) 石头 6 (1) 剪刀 7 (2) 布 8 请选择(0/1/2): """ 9 cwin = 0 10 pwin = 0 11 12 while cwin < 2 and pwin < 2: 13 computer = random.choice(all_choices) 14 ind = int(input(prompt)) 15 player = all_choices[ind] 16 17 print("Your choice: %s, Computer\'s choice: %s" % (player, computer)) 18 if player == computer: 19 print(\'\033[32;1m平局\033[0m\') 20 elif [player, computer] in win_list: 21 pwin += 1 22 print(\'\033[31;1mYou WIN!!!\033[0m\') 23 else: 24 cwin += 1 25 print(\'\033[31;1mYou LOSE!!!\033[0m\')
29-文件对象基础操作
1 # 文件操作的三个步骤:打开、读写、关闭 2 # cp /etc/passwd /tmp 3 f = open(\'/tmp/passwd\') # 默认以r的方式打开纯文本文件 4 data = f.read() # read()把所有内容读取出来 5 print(data) 6 data = f.read() # 随着读写的进行,文件指针向后移动。 7 # 因为第一个f.read()已经把文件指针移动到结尾了,所以再读就没有数据了 8 # 所以data是空字符串 9 f.close() 10 11 f = open(\'/tmp/passwd\') 12 data = f.read(4) # 读4字节 13 f.readline() # 读到换行符\n结束 14 f.readlines() # 把每一行数据读出来放到列表中 15 f.close() 16 17 ################################ 18 f = open(\'/tmp/passwd\') 19 for line in f: 20 print(line, end=\'\') 21 f.close() 22 23 ############################## 24 f = open(\'图片地址\', \'rb\') # 打开非文本文件要加参数b 25 f.read(4096) 26 f.close() 27 28 ################################## 29 f = open(\'/tmp/myfile\', \'w\') # \'w\'打开文件,如果文件不存在则创建 30 f.write(\'hello world!\n\') 31 f.flush() # 立即将缓存中的数据同步到磁盘 32 f.writelines([\'2nd line.\n\', \'new line.\n\']) 33 f.close() # 关闭文件的时候,数据保存到磁盘 34 35 ############################## 36 with open(\'/tmp/passwd\') as f: 37 print(f.readline()) 38 39 ######################### 40 f = open(\'/tmp/passwd\') 41 f.tell() # 查看文件指针的位置 42 f.readline() 43 f.tell() 44 f.seek(0, 0) # 第一个数字是偏移量,第2位是数字是相对位置。 45 # 相对位置0表示开头,1表示当前,2表示结尾 46 f.tell() 47 f.close()
30-拷贝文件
拷贝文件就是以r的方式打开源文件,以w的方式打开目标文件,将源文件数据读出后,写到目标文件。
以下是【不推荐】的方式,但是可以工作:
1 f1 = open(\'/bin/ls\', \'rb\') 2 f2 = open(\'/root/ls\', \'wb\') 3 4 data = f1.read() 5 f2.write(data) 6 7 f1.close() 8 f2.close()
31-拷贝文件
每次读取4K,读完为止:
1 src_fname = \'/bin/ls\' 2 dst_fname = \'/root/ls\' 3 4 src_fobj = open(src_fname, \'rb\') 5 dst_fobj = open(dst_fname, \'wb\') 6 7 while True: 8 data = src_fobj.read(4096) 9 if not data: 10 break 11 dst_fobj.write(data) 12 13 src_fobj.close() 14 dst_fobj.close()
32-位置参数
注意:位置参数中的数字是字符形式的
1 import sys 2 3 print(sys.argv) # sys.argv是sys模块里的argv列表 4 5 # python3 position_args.py 6 # python3 position_args.py 10 7 # python3 position_args.py 10 bob
33-函数应用-斐波那契数列
1 def gen_fib(l): 2 fib = [0, 1] 3 4 for i in range(l - len(fib)): 5 fib.append(fib[-1] + fib[-2]) 6 7 return fib # 返回列表,不返回变量fib 8 9 a = gen_fib(10) 10 print(a) 11 print(\'-\' * 50) 12 n = int(input("length: ")) 13 print(gen_fib(n)) # 不会把变量n传入,是把n代表的值赋值给形参
34-函数-拷贝文件
1 import sys 2 3 def copy(src_fname, dst_fname): 4 src_fobj = open(src_fname, \'rb\') 5 dst_fobj = open(dst_fname, \'wb\') 6 7 while True: 8 data = src_fobj.read(4096) 9 if not data: 10 break 11 dst_fobj.write(data) 12 13 src_fobj.close() 14 dst_fobj.close() 15 16 copy(sys.argv[1], sys.argv[2]) 17 # 执行方式 18 # cp_func.py /etc/hosts /tmp/zhuji.txt
35-函数-九九乘法表
1 def mtable(n): 2 for i in range(1, n + 1): 3 for j in range(1, i + 1): 4 print(\'%s*%s=%s\' % (j, i, i * j), end=\' \') 5 print() 6 7 mtable(6) 8 mtable(9)
36-模块基础
每一个以py作为扩展名的文件都是一个模块。
1 star.py: 2 3 4 hi = \'hello world!\' 5 6 def pstar(n=50): 7 print(\'*\' * n) 8 9 if __name__ == \'__main__\': 10 pstar() 11 pstar(30) 12 在call_star.py中调用star模块: 13 14 import star 15 16 print(star.hi) 17 star.pstar() 18 star.pstar(30)
37-生成密码/验证码
此文件名为:randpass.py
思路:
1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字
2、循环n次,每次随机取出一个字符
3、将各个字符拼接起来,保存到变量result中
1 from random import choice 2 import string 3 4 all_chs = string.ascii_letters + string.digits # 大小写字母加数字 5 6 def gen_pass(n=8): 7 result = \'\' 8 9 for i in range(n): 10 ch = choice(all_chs) 11 result += ch 12 13 return result 14 15 if __name__ == \'__main__\': 16 print(gen_pass()) 17 print(gen_pass(4)) 18 print(gen_pass(10))
38-序列对象方法
1 from random import randint 2 3 alist = list() # [] 4 list(\'hello\') # [\'h\', \'e\', \'l\', \'l\', \'o\'] 5 list((10, 20, 30)) # [10, 20, 30] 元组转列表 6 astr = str() # \'\' 7 str(10) # \'10\' 8 str([\'h\', \'e\', \'l\', \'l\', \'o\']) # 将列表转成字符串 9 atuple = tuple() # () 10 tuple(\'hello\') # (\'h\', \'e\', \'l\', \'l\', \'o\') 11 num_list = [randint(1, 100) for i in range(10)] 12 max(num_list) 13 min(num_list)
39-序列对象方法2
1 alist = [10, \'john\'] 2 # list(enumerate(alist)) # [(0, 10), (1, \'john\')] 3 # a, b = 0, 10 # a->0 ->10 4 5 for ind in range(len(alist)): 6 print(\'%s: %s\' % (ind, alist[ind])) 7 8 for item in enumerate(alist): 9 print(\'%s: %s\' % (item[0], item[1])) 10 11 for ind, val in enumerate(alist): 12 print(\'%s: %s\' % (ind, val)) 13 14 atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90) 15 sorted(atuple) 16 sorted(\'hello\') 17 for i in reversed(atuple): 18 print(i, end=\',\')
40-字符串方法
1 py_str = \'hello world!\' 2 py_str.capitalize() 3 py_str.title() 4 py_str.center(50) 5 py_str.center(50, \'#\') 6 py_str.ljust(50, \'*\') 7 py_str.rjust(50, \'*\') 8 py_str.count(\'l\') # 统计l出现的次数 9 py_str.count(\'lo\') 10 py_str.endswith(\'!\') # 以!结尾吗? 11 py_str.endswith(\'d!\') 12 py_str.startswith(\'a\') # 以a开头吗? 13 py_str.islower() # 字母都是小写的?其他字符不考虑 14 py_str.isupper() # 字母都是大写的?其他字符不考虑 15 \'Hao123\'.isdigit() # 所有字符都是数字吗? 16 \'Hao123\'.isalnum() # 所有字符都是字母数字? 17 \' hello\t \'.strip() # 去除两端空白字符,常用 18 \' hello\t \'.lstrip() 19 \' hello\t \'.rstrip() 20 \'how are you?\'.split() 21 \'hello.tar.gz\'.split(\'.\') 22 \'.\'.join([\'hello\', \'tar\', \'gz\']) 23 \'-\'.join([\'hello\', \'tar\', \'gz\'])
41-字符串格式化
1 "%s is %s years old" % (\'bob\', 23) # 常用 2 "%s is %d years old" % (\'bob\', 23) # 常用 3 "%s is %d years old" % (\'bob\', 23.5) # %d是整数 常用 4 "%s is %f years old" % (\'bob\', 23.5) 5 "%s is %5.2f years old" % (\'bob\', 23.5) # %5.2f是宽度为5,2位小数 6 "97 is %c" % 97 7 "11 is %#o" % 11 # %#o表示有前缀的8进制 8 "11 is %#x" % 11 9 "%10s%5s" % (\'name\', \'age\') # %10s表示总宽度为10,右对齐, 常用 10 "%10s%5s" % (\'bob\', 25) 11 "%10s%5s" % (\'alice\', 23) 12 "%-10s%-5s" % (\'name\', \'age\') # %-10s表示左对齐, 常用 13 "%-10s%-5s" % (\'bob\', 25) 14 "%10d" % 123 15 "%010d" % 123 16 17 "{} is {} years old".format(\'bob\', 25) 18 "{1} is {0} years old".format(25, \'bob\') 19 "{:<10}{:<8}".format(\'name\', \'age\')
42-shutil模块常用方法
1 import shutil 2 3 with open(\'/etc/passwd\', \'rb\') as sfobj: 4 with open(\'/tmp/mima.txt\', \'wb\') as dfobj: 5 shutil.copyfileobj(sfobj, dfobj) # 拷贝文件对象 6 7 shutil.copyfile(\'/etc/passwd\', \'/tmp/mima2.txt\') 8 shutil.copy(\'/etc/shadow\', \'/tmp/\') # cp /etc/shadow /tmp/ 9 shutil.copy2(\'/etc/shadow\', \'/tmp/\') # cp -p /etc/shadow /tmp/ 10 shutil.move(\'/tmp/mima.txt\', \'/var/tmp/\') # mv /tmp/mima.txt /var/tmp/ 11 shutil.copytree(\'/etc/security\', \'/tmp/anquan\') # cp -r /etc/security /tmp/anquan 12 shutil.rmtree(\'/tmp/anquan\') # rm -rf /tmp/anquan 13 # 将mima2.txt的权限设置成与/etc/shadow一样 14 shutil.copymode(\'/etc/shadow\', \'/tmp/mima2.txt\') 15 # 将mima2.txt的元数据设置成与/etc/shadow一样 16 # 元数据使用stat /etc/shadow查看 17 shutil.copystat(\'/etc/shadow\', \'/tmp/mima2.txt\') 18 shutil.chown(\'/tmp/mima2.txt\', user=\'zhangsan\', group=\'zhangsan\')
43-练习:生成文本文件
1 import os 2 3 def get_fname(): 4 while True: 5 fname = input(\'filename: \') 6 if not os.path.exists(fname): 7 break 8 print(\'%s already exists. Try again\' % fname) 9 10 return fname 11 12 def get_content(): 13 content = [] 14 print(\'输入数据,输入end结束\') 15 while True: 16 line = input(\'> \') 17 if line == \'end\': 18 break 19 content.append(line) 20 21 return content 22 23 def wfile(fname, content): 24 with open(fname, \'w\') as fobj: 25 fobj.writelines(content) 26 27 if __name__ == \'__main__\': 28 fname = get_fname() 29 content = get_content() 30 content = [\'%s\n\' % line for line in content] 31 wfile(fname, content)
44-列表方法
1 alist = [1, 2, 3, \'bob\', \'alice\'] 2 alist[0] = 10 3 alist[1:3] = [20, 30] 4 alist[2:2] = [22, 24, 26, 28] 5 alist.append(100) 6 alist.remove(24) # 删除第一个24 7 alist.index(\'bob\') # 返回下标 8 blist = alist.copy() # 相当于blist = alist[:] 9 alist.insert(1, 15) # 向下标为1的位置插入数字15 10 alist.pop() # 默认弹出最后一项 11 alist.pop(2) # 弹出下标为2的项目 12 alist.pop(alist.index(\'bob\')) 13 alist.sort() 14 alist.reverse() 15 alist.count(20) # 统计20在列表中出现的次数 16 alist.clear() # 清空 17 alist.append(\'new\') 18 alist.extend(\'new\') 19 alist.extend([\'hello\', \'world\', \'hehe\'])
45-检查合法标识符
import sys import keyword import string first_chs = string.ascii_letters + \'_\' all_chs = first_chs + string.digits def check_id(idt): if keyword.iskeyword(idt): return "%s is keyword" % idt if idt[0] not in first_chs: return "1st invalid" for ind, ch in enumerate(idt[1:]): if ch not in all_chs: return "char in postion #%s invalid" % (ind + 2) return "%s is valid" % idt if __name__ == \'__main__\': print(check_id(sys.argv[1])) # python3 checkid.py abc@123
46-创建用户,设置随机密码
randpass模块参见《37-生成密码/验证码》
1 import subprocess 2 import sys 3 from randpass import gen_pass 4 5 def adduser(username, password, fname): 6 data = """user information: 7 %s: %s 8 """ 9 subprocess.call(\'useradd %s\' % username, shell=True) 10 subprocess.call( 11 \'echo %s | passwd --stdin %s\' % (password, username), 12 shell=True 13 ) 14 with open(fname, \'a\') as fobj: 15 fobj.write(data % (username, password)) 16 17 if __name__ == \'__main__\': 18 username = sys.argv[1] 19 password = gen_pass() 20 adduser(username, password, \'/tmp/user.txt\') 21 # python3 adduser.py john
47-列表练习:模拟栈操作
1 stack = [] 2 3 def push_it(): 4 item = input(\'item to push: \') 5 stack.append(item) 6 7 def pop_it(): 8 if stack: 9 print("from stack popped %s" % stack.pop()) 10 11 def view_it(): 12 print(stack) 13 14 def show_menu(): 15 cmds = {\'0\': push_it, \'1\': pop_it, \'2\': view_it} # 将函数存入字典 16 prompt = """(0) push it 17 (1) pop it 18 (2) view it 19 (3) exit 20 Please input your choice(0/1/2/3): """ 21 22 while True: 23 # input()得到字符串,用strip()去除两端空白,再取下标为0的字符 24 choice = input(prompt).strip()[0] 25 if choice not in \'0123\': 26 print(\'Invalid input. Try again.\') 27 continue 28 29 if choice == \'3\': 30 break 31 32 cmds[choice]() 33 34 35 if __name__ == \'__main__\': 36 show_menu()
48-实现Linux系统中unix2dos功能
1 import sys 2 3 def unix2dos(fname): 4 dst_fname = fname + \'.txt\' 5 6 with open(fname) as src_fobj: 7 with open(dst_fname, \'w\') as dst_fobj: 8 for line in src_fobj: 9 line = line.rstrip() + \'\r\n\' 10 dst_fobj.write(line) 11 12 13 if __name__ == \'__main__\': 14 unix2dos(sys.argv[1])
49-动画程序:@从一行#中穿过
\r是回车不换行
1 import time 2 3 length = 19 4 count = 0 5 6 while True: 7 print(\'\r%s@%s\' % (\'#\' * count, \'#\' * (length - count)), end=\'\') 8 try: 9 time.sleep(0.3) 10 except KeyboardInterrupt: 11 print(\'\nBye-bye\') 12 break 13 if count == length: 14 count = 0 15 count += 1
50-字典基础用法
1 adict = dict() # {} 2 dict([\'ab\', \'cd\']) 3 bdict = dict([(\'name\', \'bob\'),(\'age\', 25)]) 4 {}.fromkeys([\'zhangsan\', \'lisi\', \'wangwu\'], 11) 5 6 for key in bdict: 7 print(\'%s: %s\' % (key, bdict[key])) 8 9 print("%(name)s: %(age)s" % bdict) 10 11 bdict[\'name\'] = \'tom\' 12 bdict[\'email\'] = \'tom@tedu.cn\' 13 14 del bdict[\'email\'] 15 bdict.pop(\'age\') 16 bdict.clear()
51-字典常用方法
1 adict = dict([(\'name\', \'bob\'),(\'age\', 25)]) 2 len(adict) 3 hash(10) # 判断给定的数据是不是不可变的,不可变数据才能作为key 4 adict.keys() 5 adict.values() 6 adict.items() 7 # get方法常用,重要 8 adict.get(\'name\') # 取出字典中name对应的value,如果没有返回None 9 print(adict.get(\'qq\')) # None 10 print(adict.get(\'qq\', \'not found\')) # 没有qq,返回指定内容 11 print(adict.get(\'age\', \'not found\')) 12 adict.update({\'phone\': \'13455667788\'})
52-集合常用方法
1 # 集合相当于是无值的字典,所以也用{}表示 2 myset = set(\'hello\') 3 len(myset) 4 for ch in myset: 5 print(ch) 6 7 aset = set(\'abc\') 8 bset = set(\'cde\') 9 aset & bset # 交集 10 aset.intersection(bset) # 交集 11 aset | bset # 并集 12 aset.union(bset) # 并集 13 aset - bset # 差补 14 aset.difference(bset) # 差补 15 aset.add(\'new\') 16 aset.update([\'aaa\', \'bbb\']) 17 aset.remove(\'bbb\') 18 cset = set(\'abcde\') 19 dset = set(\'bcd\') 20 cset.issuperset(dset) # cset是dset的超集么? 21 cset.issubset(dset) # cset是dset的子集么?
53-集合实例:取出第二个文件有,第一个文件没有的行
1 # cp /etc/passwd . 2 # cp /etc/passwd mima 3 # vim mima -> 修改,与passwd有些区别 4 5 with open(\'passwd\') as fobj: 6 aset = set(fobj) 7 8 with open(\'mima\') as fobj: 9 bset = set(fobj) 10 11 with open(\'diff.txt\', \'w\') as fobj: 12 fobj.writelines(bset - aset)
54-字典练习:模拟注册/登陆
1 import getpass 2 3 userdb = {} 4 5 def register(): 6 username = input(\'username: \') 7 if username in userdb: 8 print(\'%s already exists.\' % username) 9 else: 10 password = input(\'password: \') 11 userdb[username] = password 12 13 def login(): 14 username = input(\'username: \') 15 password = getpass.getpass("password: ") 16 if userdb.get(username) != password: 17 print(\'login failed\') 18 else: 19 print(\'login successful\') 20 21 22 def show_menu(): 23 cmds = {\'0\': register, \'1\': login} 24 prompt = """(0) register 25 (1) login 26 (2) exit 27 Please input your choice(0/1/2): """ 28 29 while True: 30 choice = input(prompt).strip()[0] 31 if choice not in \'012\': 32 print(\'Invalid inupt. Try again.\') 33 continue 34 if choice == \'2\': 35 break 36 37 cmds[choice]() 38 39 if __name__ == \'__main__\': 40 show_menu()
55-计算千万次加法运算时间
1 import time 2 3 result = 0 4 start = time.time() # 返回运算前时间戳 5 for i in range(10000000): 6 result += i 7 end = time.time() # 返回运算后时间戳 8 print(result) 9 print(end - start)
56-时间相关模块常用方法
1 import time 2 3 t = time.localtime() # 返回当前时间的九元组 4 time.gmtime() # 返回格林威治0时区当前时间的九元组 5 time.time() # 常用,与1970-1-1 8:00之间的秒数,时间戳 6 time.mktime(t) # 把九元组时间转成时间戳 7 time.sleep(1) 8 time.asctime() # 如果有参数,是九元组形式 9 time.ctime() # 返回当前时间,参数是时间戳,常用 10 time.strftime("%Y-%m-%d") # 常用 11 time.strptime(\'2018-07-20\', "%Y-%m-%d") # 返回九元组时间格式 12 time.strftime(\'%H:%M:%S\') 13 14 ########################################### 15 from datetime import datetime 16 from datetime import timedelta 17 datetime.today() # 返回当前时间的datetime对象 18 datetime.now() # 同上,可以用时区作参数 19 datetime.strptime(\'2018/06/30\', \'%Y/%m/%d\') # 返回datetime对象 20 dt = datetime.today() 21 datetime.ctime(dt) 22 datetime.strftime(dt, "%Y%m%d") 23 24 days = timedelta(days=90, hours=3) # 常用 25 dt2 = dt + days 26 dt2.year 27 dt2.month 28 dt2.day 29 dt2.hour
57-os模块常用方法
1 import os 2 3 os.getcwd() # 显示当前路径 4 os.listdir() # ls -a 5 os.listdir(\'/tmp\') # ls -a /tmp 6 os.mkdir(\'/tmp/mydemo\') # mkdir /tmp/mydemo 7 os.chdir(\'/tmp/mydemo\') # cd /tmp/mydemo 8 os.listdir() 9 os.mknod(\'test.txt\') # touch test.txt 10 os.symlink(\'/etc/hosts\', \'zhuji\') # ln -s /etc/hosts zhuji 11 os.path.isfile(\'test.txt\') # 判断test.txt是不是文件 12 os.path.islink(\'zhuji\') # 判断zhuji是不是软链接 13 os.path.isdir(\'/etc\') 14 os.path.exists(\'/tmp\') # 判断是否存在 15 os.path.basename(\'/tmp/abc/aaa.txt\') 16 os.path.dirname(\'/tmp/abc/aaa.txt\') 17 os.path.split(\'/tmp/abc/aaa.txt\') 18 os.path.join(\'/home/tom\', \'xyz.txt\') 19 os.path.abspath(\'test.txt\') # 返回当前目录test.txt的绝对路径
58-pickle存储器
1 import pickle 2 """以前的文件写入,只能写入字符串,如果希望把任意数据对象(数字、列表等)写入文件, 3 取出来的时候数据类型不变,就用到pickle了 4 """ 5 6 # shop_list = ["eggs", "apple", "peach"] 7 # with open(\'/tmp/shop.data\', \'wb\') as fobj: 8 # pickle.dump(shop_list, fobj) 9 10 with open(\'/tmp/shop.data\', \'rb\') as fobj: 11 mylist = pickle.load(fobj) 12 13 print(mylist[0], mylist[1], mylist[2])
59-异常处理基础
1 try: # 把有可能发生异常的语句放到try里执行 2 n = int(input("number: ")) 3 result = 100 / n 4 print(result) 5 except ValueError: 6 print(\'invalid number\') 7 except ZeroDivisionError: 8 print(\'0 not allowed\') 9 except KeyboardInterrupt: 10 print(\'Bye-bye\') 11 except EOFError: 12 print(\'Bye-bye\') 13 14 print(\'Done\')
60-异常处理完整语法
1 try: 2 n = int(input("number: ")) 3 result = 100 / n 4 except (ValueError, ZeroDivisionError): 5 print(\'invalid number\') 6 except (KeyboardInterrupt, EOFError): 7 print(\'\nBye-bye\') 8 else: 9 print(result) # 异常不发生时才执行else子句 10 finally: 11 print(\'Done\') # 不管异常是否发生都必须执行的语句 12 13 # 常用形式有try-except和try-finally