【Python】Python 入门的60个基础练习
【转】Python入门的60个基础练习【侵删】
01-Hello World
python 的语法逻辑完全靠缩进,建议缩进 4 个空格。 如果是顶级代码,那么必须顶格书写,哪怕只有一个空格也会有语法错误。 下面示例中,满足 if 条件要输出两行内容,这两行内容必须都缩进,而且具有相同的缩进级别。
print('hello world!')if 3 > 0:print('OK')print('yes')x = 3; y = 4 # 不推荐,还是应该写成两行print(x + y)12345678
02-print 函数
print('hello world!')print('hello', 'world!') # 逗号自动添加默认的分隔符:空格 hello world!print('hello' + 'world!') # 加号表示字符拼接 helloworld!print('hello', 'world', sep='***') # 单词间用***分隔 hello***worldprint('#' * 50) # *号表示重复 50 遍print('how are you?', end='') # 默认 print 会打印回车,end=''表示不要回车123456
03-基本运算
运算符可以分为:算术运算符、比较运算符和逻辑运算符。优先级是:算术运算符>比较运算符>逻辑运算符。最好使用括号,增加了代码的可读性。
print(5 / 2) # 2.5print(5 // 2) # 丢弃余数,只保留商print(5 % 2) # 求余数print(5 ** 3) # 5 的 3 次方print(5 > 3) # 返回 Trueprint(3 > 5) # 返回 Falseprint(20 > 10 > 5) # python 支持连续比较print(20 > 10 and 10 > 5) # 与上面相同含义print(not 20 > 10) # False123456789
04-input
number = input("请输入数字:") # input 用于获取键盘输入print(number)print(type(number)) # input 获得的数据是字符型print(number + 10) # 报错,不能把字符和数字做运算print(int(number) + 10) # int 可将字符串 10 转换成数字 10print(number + str(10)) # str 将 10 转换为字符串后实现字符串拼接1234567
05-输入输出基础练习
username = input('username: ')print('welcome', username) # print 各项间默认以空格作为分隔符print('welcome ' + username) # 注意引号内最后的空格123
06-字符串使用基础
python 中,单双引号没有区别,表示一样的含义
sentence = 'tom\'s pet is a cat' # 单引号中间还有单引号,可以转义sentence2 = "tom's pet is a cat" # 也可以用双引号包含单引号sentence3 = "tom said:\"hello world!\""sentence4 = 'tom said:"hello world"'# 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串words = """ hello world abcd"""print(words)py_str = 'python'len(py_str) # 取长度py_str[0] # 第一个字符'python'[0]py_str[-1] # 最后一个字符# py_str[6] # 错误,下标超出范围py_str[2:4] # 切片,起始下标包含,结束下标不包含py_str[2:] # 从下标为 2 的字符取到结尾py_str[:2] # 从开头取到下标是 2 之前的字符py_str[:] # 取全部py_str[::2] # 步长值为 2,默认是 1py_str[1::2] # 取出 yhnpy_str[::-1] # 步长为负,表示自右向左取py_str + ' is good' # 简单的拼接到一起py_str * 3 # 把字符串重复 3 遍't' in py_str # True'th' in py_str # True'to' in py_str # False'to' not in py_str # True1234567891011121314151617181920212223242526272829303132
07-列表基础
列表也是序列对象,但它是容器类型,列表中可以包含各种数据
alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]len(alist)alist[-1] # 取出最后一项alist[-1][-1] # 因为最后一项是列表,列表还可以继续取下标[1,2,3][-1] # [1,2,3] 是列表,[-1] 表示列表最后一项alist[-2][2] # 列表倒数第 2 项是字符串,再取出字符下标为 2 的字符alist[3:5] # ['bob', 'alice']10 in alist # True'o' in alist # False100 not in alist # Truealist[-1] = 100 # 修改最后一项的值alist.append(200) # 向**列表中追加一项123456789101112
08-元组基础
元组与列表基本上是一样的,只是元组不可变,列表可变。
atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])len(atuple)10 in atuple atuple[2]atuple[3:5]# atuple[-1] = 100 # 错误,元组是不可变的123456
09-字典基础
# 字典是 key-value(键-值)对形式的,没有顺序,通过键取出值 adict = {'name': 'bob', 'age': 23} len(adict) 'bob' in adict # False 'name' in adict # True adict['email'] = 'bob@tedu.cn' # 字典中没有 key,则添加新项目 adict['age'] = 25 # 字典中已有 key,修改对应的 value1234567
10-基本判断
单个的数据也可作为判断条件。 任何值为 0 的数字、空对象都是 False,任何非 0 数字、非空对象都是 True。
if 3 > 0:print('yes')print('ok')if 10 in [10, 20, 30]:print('ok')if -0.0:print('yes') # 任何值为 0 的数字都是 Falseif [1, 2]:print('yes') # 非空对象都是 Trueif ' ':print('yes') # 空格字符也是字符,条件为 True123456789101112131415
11-条件表达式、三元运算符
a = 10b = 20if a < b:smaller = aelse:smaller = bprint(smaller)s = a if a < b else b # 和上面的 if-else 语句等价print(s)1234567891011
12-判断练习:用户名和密码是否正确
import getpass # 导入模块username = input('username: ')# getpass 模块中,有一个方法也叫 getpasspassword = getpass.getpass('password: ')if username == 'bob' and password == '123456':print('Login successful')else:print('Login incorrect')12345678910
13-猜数:基础实现
import random num = random.randint(1, 10) # 随机生成 1-10 之间的数字answer = int(input('guess a number: ')) # 将用户输入的字符转成整数if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')print('the number:', num)123456789101112
14-成绩分类 1
score = int(input('分数:'))if score >= 90:print('优秀')elif score >= 80:print('好')elif score >= 70:print('良')elif score >= 60:print('及格')else:print('你要努力了')123456789101112
15-成绩分类 2
score = int(input('分数:'))if score >= 60 and score < 70:print('及格')elif 70 <= score < 80:print('良')elif 80 <= score < 90:print('好')elif score >= 90:print('优秀')else:print('你要努力了')123456789101112
16-石头剪刀布
import random all_choices = ['石头', '剪刀', '布']computer = random.choice(all_choices)player = input('请出拳:')# print('Your choice:', player, "Computer's choice:", computer)print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == '石头':if computer == '石头':print('平局')elif computer == '剪刀':print('You WIN!!!')else:print('You LOSE!!!')elif player == '剪刀':if computer == '石头':print('You LOSE!!!')elif computer == '剪刀':print('平局')else:print('You WIN!!!')else:if computer == '石头':print('You WIN!!!')elif computer == '剪刀':print('You LOSE!!!')else:print('平局')1234567891011121314151617181920212223242526272829
17-改进的石头剪刀布
import random all_choices = ['石头', '剪刀', '布']win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]prompt = """(0) 石头 (1) 剪刀 (2) 布 请选择 (0/1/2): """computer = random.choice(all_choices)ind = int(input(prompt))player = all_choices[ind]print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == computer:print('\033[32;1m 平局、033[0m')elif [player, computer] in win_list:print('\033[31;1mYou WIN!!!\033[0m')else:print('\033[31;1mYou LOSE!!!\033[0m')12345678910111213141516171819
18-猜数,直到猜对
import random num = random.randint(1, 10)running = Truewhile running:answer = int(input('guess the number: '))if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')running = False1234567891011121314
19-猜数,5 次机会
import random num = random.randint(1, 10)counter = 0while counter < 5:answer = int(input('guess the number: '))if answer > num:print('猜大了')elif answer < num:print('猜小了')else:print('猜对了')breakcounter += 1else: # 循环被 break 就不执行了,没有被 break 才执行print('the number is:', num)1234567891011121314151617
20-while 循环,累加至 100
因为循环次数是已知的,实际使用时,建议用 for 循环
sum100 = 0counter = 1while counter < 101:sum100 += counter counter += 1print(sum100)12345678
21-while-break
break 是结束循环,break 之后、循环体内代码不再执行。
while True:yn = input('Continue(y/n): ')if yn in ['n', 'N']:breakprint('running...')12345
22-while-continue
计算 100 以内偶数之和。
continue 是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0counter = 0while counter < 100:counter += 1# if counter % 2:if counter % 2 == 1:continuesum100 += counterprint(sum100)1234567891011
23-for 循环遍历数据对象
astr = 'hello'alist = [10, 20, 30]atuple = ('bob', 'tom', 'alice')adict = {'name': 'john', 'age': 23}for ch in astr:print(ch)for i in alist:print(i)for name in atuple:print(name)for key in adict:print('%s: %s' % (key, adict[key]))12345678910111213141516
24-range 用法及数字累加
# range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# >>> list(range(10))# range(6, 11) # [6, 7, 8, 9, 10]# range(1, 10, 2) # [1, 3, 5, 7, 9]# range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]sum100 = 0for i in range(1, 101):sum100 += iprint(sum100)1234567891011
25-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
fib = [0, 1]for i in range(8):fib.append(fib[-1] + fib[-2])print(fib)123456
26-九九乘法表
for i in range(1, 10):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()# i=1 ->j: [1]# i=2 ->j: [1,2]# i=3 ->j: [1,2,3]# 由用户指定相乘到多少n = int(input('number: '))for i in range(1, n + 1):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()123456789101112131415
27-逐步实现列表解析
# 10+5 的结果放到列表中[10 + 5]# 10+5 这个表达式计算 10 次[10 + 5 for i in range(10)]# 10+i 的 i 来自于循环[10 + i for i in range(10)][10 + i for i in range(1, 11)]# 通过 if 过滤,满足 if 条件的才参与 10+i 的运算[10 + i for i in range(1, 11) if i % 2 == 1][10 + i for i in range(1, 11) if i % 2]# 生成 IP 地址列表['192.168.1.%s' % i for i in range(1, 255)]123456789101112
28-三局两胜的石头剪刀布
import random all_choices = ['石头', '剪刀', '布']win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]prompt = """(0) 石头 (1) 剪刀 (2) 布 请选择 (0/1/2): """cwin = 0pwin = 0while cwin < 2 and pwin < 2:computer = random.choice(all_choices)ind = int(input(prompt))player = all_choices[ind]print("Your choice: %s, Computer's choice: %s" % (player, computer))if player == computer:print('\033[32;1m 平局、033[0m')elif [player, computer] in win_list:pwin += 1print('\033[31;1mYou WIN!!!\033[0m')else:cwin += 1print('\033[31;1mYou LOSE!!!\033[0m')12345678910111213141516171819202122232425
29-文件对象基础操作
# 文件操作的三个步骤:打开、读写、关闭# cp /etc/passwd /tmpf = open('/tmp/passwd') # 默认以 r 的方式打开纯文本文件data = f.read() # read() 把所有内容读取出来print(data)data = f.read() # 随着读写的进行,文件指针向后移动。# 因为第一个 f.read() 已经把文件指针移动到结尾了,所以再读就没有数据了# 所以 data 是空字符串f.close()f = open('/tmp/passwd')data = f.read(4) # 读 4 字节f.readline() # 读到换行符、n 结束f.readlines() # 把每一行数据读出来放到列表中f.close()################################f = open('/tmp/passwd')for line in f:print(line, end='')f.close()##############################f = open('图片地址', 'rb') # 打开非文本文件要加参数 bf.read(4096)f.close()##################################f = open('/tmp/myfile', 'w') # 'w'打开文件,如果文件不存在则创建f.write('hello world!\n')f.flush() # 立即将缓存中的数据同步到磁盘f.writelines(['2nd line.\n', 'new line.\n'])f.close() # 关闭文件的时候,数据保存到磁盘##############################with open('/tmp/passwd') as f:print(f.readline())#########################f = open('/tmp/passwd')f.tell() # 查看文件指针的位置f.readline()f.tell()f.seek(0, 0) # 第一个数字是偏移量,第 2 位是数字是相对位置。 # 相对位置 0 表示开头,1 表示当前,2 表示结尾f.tell()f.close()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
30-拷贝文件
拷贝文件就是以 r 的方式打开源文件,以 w 的方式打开目标文件,将源文件数据读出后,写到目标文件。
以下是【不推荐】的方式,但是可以工作:
f1 = open('/bin/ls', 'rb')f2 = open('/root/ls', 'wb')data = f1.read()f2.write(data)f1.close()f2.close()12345678
31-拷贝文件
每次读取 4K,读完为止:
src_fname = '/bin/ls'dst_fname = '/root/ls'src_fobj = open(src_fname, 'rb')dst_fobj = open(dst_fname, 'wb')while True:data = src_fobj.read(4096) # 每次读取 4Kif not data:breakdst_fobj.write(data)src_fobj.close()dst_fobj.close()1234567891011121314
32-位置参数
注意:位置参数中的数字是字符形式的
import sysprint(sys.argv) # sys.argv 是 sys 模块里的 argv 列表# python3 position_args.py# python3 position_args.py 10# python3 position_args.py 10 bob1234567
33-函数应用-斐波那契数列
def gen_fib(l):fib = [0, 1]for i in range(l - len(fib)):fib.append(fib[-1] + fib[-2])return fib # 返回列表,不返回变量 fiba = gen_fib(10)print(a)print('-' * 50)n = int(input("length: "))print(gen_fib(n)) # 不会把变量 n 传入,是把 n 代表的值赋值给形参12345678910111213
34-函数-拷贝文件
import sysdef copy(src_fname, dst_fname):src_fobj = open(src_fname, 'rb')dst_fobj = open(dst_fname, 'wb')while True:data = src_fobj.read(4096)if not data:breakdst_fobj.write(data)src_fobj.close()dst_fobj.close()copy(sys.argv[1], sys.argv[2])# 执行方式# cp_func.py /etc/hosts /tmp/zhuji.txt123456789101112131415161718
35-函数-九九乘法表
def mtable(n):for i in range(1, n + 1):for j in range(1, i + 1):print('%s*%s=%s' % (j, i, i * j), end=' ')print()mtable(6)mtable(9)12345678
36-模块基础
每一个以 py 作为扩展名的文件都是一个模块。
star.py:
hi = 'hello world!'def pstar(n=50):print('*' * n)if __name__ == '__main__':pstar()pstar(30)12345678
在 call_star.py 中调用 star 模块:
import starprint(star.hi)star.pstar()star.pstar(30)12345
37-生成密码/验证码
此文件名为:randpass.py
思路:
1、设置一个用于随机取出字符的基础字符串,本例使用大小写字母加数字
2、循环 n 次,每次随机取出一个字符
3、将各个字符拼接起来,保存到变量 result 中
from random import choiceimport string all_chs = string.ascii_letters + string.digits # 大小写字母加数字def gen_pass(n=8):result = ''for i in range(n):ch = choice(all_chs)result += chreturn resultif __name__ == '__main__':print(gen_pass())print(gen_pass(4))print(gen_pass(10))123456789101112131415161718
38-序列对象方法
from random import randint alist = list() # []list('hello') # ['h', 'e', 'l', 'l', 'o']list((10, 20, 30)) # [10, 20, 30] 元组转列表astr = str() # ''str(10) # '10'str(['h', 'e', 'l', 'l', 'o']) # 将列表转成字符串atuple = tuple() # ()tuple('hello') # ('h', 'e', 'l', 'l', 'o')num_list = [randint(1, 100) for i in range(10)]max(num_list)min(num_list)12345678910111213
39-序列对象方法 2
alist = [10, 'john']# list(enumerate(alist)) # [(0, 10), (1, 'john')]# a, b = 0, 10 # a->0 ->10for ind in range(len(alist)):print('%s: %s' % (ind, alist[ind]))for item in enumerate(alist):print('%s: %s' % (item[0], item[1]))for ind, val in enumerate(alist):print('%s: %s' % (ind, val))atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)sorted(atuple)sorted('hello')for i in reversed(atuple):print(i, end=',')123456789101112131415161718
40-字符串方法
py_str = 'hello world!'py_str.capitalize()py_str.title()py_str.center(50)py_str.center(50, '#')py_str.ljust(50, '*')py_str.rjust(50, '*')py_str.count('l') # 统计 l 出现的次数py_str.count('lo')py_str.endswith('!') # 以!结尾吗?py_str.endswith('d!')py_str.startswith('a') # 以 a 开头吗?py_str.islower() # 字母都是小写的?其他字符不考虑py_str.isupper() # 字母都是大写的?其他字符不考虑'Hao123'.isdigit() # 所有字符都是数字吗?'Hao123'.isalnum() # 所有字符都是字母数字?' hello\t '.strip() # 去除两端空白字符,常用' hello\t '.lstrip()' hello\t '.rstrip()'how are you?'.split()'hello.tar.gz'.split('.')'.'.join(['hello', 'tar', 'gz'])'-'.join(['hello', 'tar', 'gz'])1234567891011121314151617181920212223
41-字符串格式化
"%s is %s years old" % ('bob', 23) # 常用"%s is %d years old" % ('bob', 23) # 常用"%s is %d years old" % ('bob', 23.5) # %d 是整数 常用"%s is %f years old" % ('bob', 23.5)"%s is %5.2f years old" % ('bob', 23.5) # %5.2f 是宽度为 5,2 位小数"97 is %c" % 97"11 is %#o" % 11 # %#o 表示有前缀的 8 进制"11 is %#x" % 11"%10s%5s" % ('name', 'age') # %10s 表示总宽度为 10,右对齐,常用"%10s%5s" % ('bob', 25)"%10s%5s" % ('alice', 23)"%-10s%-5s" % ('name', 'age') # %-10s 表示左对齐,常用"%-10s%-5s" % ('bob', 25)"%10d" % 123"%010d" % 123"{} is {} years old".format('bob', 25)"{1} is {0} years old".format(25, 'bob')"{:<10}{:<8}".format('name', 'age')12345678910111213141516171819
42-shutil 模块常用方法
import shutilwith open('/etc/passwd', 'rb') as sfobj:with open('/tmp/mima.txt', 'wb') as dfobj:shutil.copyfileobj(sfobj, dfobj) # 拷贝文件对象shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')shutil.copy('/etc/shadow', '/tmp/') # cp /etc/shadow /tmp/shutil.copy2('/etc/shadow', '/tmp/') # cp -p /etc/shadow /tmp/shutil.move('/tmp/mima.txt', '/var/tmp/') # mv /tmp/mima.txt /var/tmp/shutil.copytree('/etc/security', '/tmp/anquan') # cp -r /etc/security /tmp/anquanshutil.rmtree('/tmp/anquan') # rm -rf /tmp/anquan# 将 mima2.txt 的权限设置成与/etc/shadow 一样shutil.copymode('/etc/shadow', '/tmp/mima2.txt')# 将 mima2.txt 的元数据设置成与/etc/shadow 一样# 元数据使用 stat /etc/shadow 查看shutil.copystat('/etc/shadow', '/tmp/mima2.txt')shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')123456789101112131415161718
43-练习:生成文本文件
import osdef get_fname():while True:fname = input('filename: ')if not os.path.exists(fname):breakprint('%s already exists. Try again' % fname)return fnamedef get_content():content = []print('输入数据,输入 end 结束')while True:line = input('> ')if line == 'end':breakcontent.append(line)return contentdef wfile(fname, content):with open(fname, 'w') as fobj:fobj.writelines(content)if __name__ == '__main__':fname = get_fname()content = get_content()content = ['%s\n' % line for line in content]wfile(fname, content)12345678910111213141516171819202122232425262728293031
44-列表方法
alist = [1, 2, 3, 'bob', 'alice']alist[0] = 10alist[1:3] = [20, 30]alist[2:2] = [22, 24, 26, 28]alist.append(100)alist.remove(24) # 删除第一个 24alist.index('bob') # 返回下标blist = alist.copy() # 相当于 blist = alist[:]alist.insert(1, 15) # 向下标为 1 的位置插入数字 15alist.pop() # 默认弹出最后一项alist.pop(2) # 弹出下标为 2 的项目alist.pop(alist.index('bob'))alist.sort()alist.reverse()alist.count(20) # 统计 20 在列表中出现的次数alist.clear() # 清空alist.append('new')alist.extend('new')alist.extend(['hello', 'world', 'hehe'])12345678910111213141516171819
45-检查合法标识符
import sysimport keywordimport string first_chs = string.ascii_letters + '_'all_chs = first_chs + string.digitsdef check_id(idt):if keyword.iskeyword(idt):return "%s is keyword" % idtif 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" % idtif __name__ == '__main__':print(check_id(sys.argv[1])) # python3 checkid.py abc@12312345678910111213141516171819202122
46-创建用户,设置随机密码
randpass 模块参见《37-生成密码/验证码》
import subprocessimport sysfrom randpass import gen_passdef adduser(username, password, fname):data = """user information: %s: %s """subprocess.call('useradd %s' % username, shell=True)subprocess.call('echo %s | passwd --stdin %s' % (password, username),shell=True)with open(fname, 'a') as fobj:fobj.write(data % (username, password))if __name__ == '__main__':username = sys.argv[1]password = gen_pass()adduser(username, password, '/tmp/user.txt')# python3 adduser.py john123456789101112131415161718192021
47-列表练习:模拟栈操作
stack = []def push_it():item = input('item to push: ')stack.append(item)def pop_it():if stack:print("from stack popped %s" % stack.pop())def view_it():print(stack)def show_menu():cmds = {'0': push_it, '1': pop_it, '2': view_it} # 将函数存入字典prompt = """(0) push it (1) pop it (2) view it (3) exit Please input your choice(0/1/2/3): """while True:# input() 得到字符串,用 strip() 去除两端空白,再取下标为 0 的字符choice = input(prompt).strip()[0]if choice not in '0123':print('Invalid input. Try again.')continueif choice == '3':breakcmds[choice]()if __name__ == '__main__':show_menu()1234567891011121314151617181920212223242526272829303132333435
48-实现 Linux 系统中 unix2dos 功能
import sysdef unix2dos(fname):dst_fname = fname + '.txt'with open(fname) as src_fobj:with open(dst_fname, 'w') as dst_fobj:for line in src_fobj:line = line.rstrip() + '\r\n'dst_fobj.write(line)if __name__ == '__main__':unix2dos(sys.argv[1])12345678910111213
49-动画程序:@从一行#中穿过
\r 是回车不换行
import time length = 19count = 0while True:print('\r%s@%s' % ('#' * count, '#' * (length - count)), end='')try:time.sleep(0.3)except KeyboardInterrupt:print('\nBye-bye')breakif count == length:count = 0count += 1123456789101112131415
50-字典基础用法
adict = dict() # {}dict(['ab', 'cd'])bdict = dict([('name', 'bob'),('age', 25)]){}.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)for key in bdict:print('%s: %s' % (key, bdict[key]))print("%(name)s: %(age)s" % bdict)bdict['name'] = 'tom'bdict['email'] = 'tom@tedu.cn'del bdict['email']bdict.pop('age')bdict.clear()12345678910111213141516
51-字典常用方法
adict = dict([('name', 'bob'),('age', 25)])len(adict)hash(10) # 判断给定的数据是不是不可变的,不可变数据才能作为 keyadict.keys()adict.values()adict.items()# get 方法常用,重要adict.get('name') # 取出字典中 name 对应的 value,如果没有返回 Noneprint(adict.get('qq')) # Noneprint(adict.get('qq', 'not found')) # 没有 qq,返回指定内容print(adict.get('age', 'not found'))adict.update({'phone': '13455667788'})123456789101112
52-集合常用方法
# 集合相当于是无值的字典,所以也用{}表示myset = set('hello')len(myset)for ch in myset:print(ch)aset = set('abc')bset = set('cde')aset & bset # 交集aset.intersection(bset) # 交集aset | bset # 并集aset.union(bset) # 并集aset - bset # 差补aset.difference(bset) # 差补aset.add('new')aset.update(['aaa', 'bbb'])aset.remove('bbb')cset = set('abcde')dset = set('bcd')cset.issuperset(dset) # cset 是 dset 的超集么?cset.issubset(dset) # cset 是 dset 的子集么?123456789101112131415161718192021
53-集合实例:取出第二个文件有,第一个文件没有的行
# cp /etc/passwd .# cp /etc/passwd mima# vim mima -> 修改,与 passwd 有些区别with open('passwd') as fobj:aset = set(fobj)with open('mima') as fobj:bset = set(fobj)with open('diff.txt', 'w') as fobj:fobj.writelines(bset - aset)123456789101112
54-字典练习:模拟注册/登陆
import getpass userdb = {}def register():username = input('username: ')if username in userdb:print('%s already exists.' % username)else:password = input('password: ')userdb[username] = passworddef login():username = input('username: ')password = getpass.getpass("password: ")if userdb.get(username) != password:print('login failed')else:print('login successful')def show_menu():cmds = {'0': register, '1': login}prompt = """(0) register (1) login (2) exit Please input your choice(0/1/2): """while True: choice = input(prompt).strip()[0] if choice not in '012': print('Invalid inupt. Try again.') continue if choice == '2': break cmds[choice]() if __name__ == '__main__':show_menu()123456789101112131415161718192021222324252627282930313233343536373839
55-计算千万次加法运算时间
import time result = 0start = time.time() # 返回运算前时间戳for i in range(10000000):result += i end = time.time() # 返回运算后时间戳print(result)print(end - start)123456789
56-时间相关模块常用方法
import time t = time.localtime() # 返回当前时间的九元组time.gmtime() # 返回格林威治 0 时区当前时间的九元组time.time() # 常用,与 1970-1-1 8:00 之间的秒数,时间戳time.mktime(t) # 把九元组时间转成时间戳time.sleep(1)time.asctime() # 如果有参数,是九元组形式time.ctime() # 返回当前时间,参数是时间戳,常用time.strftime("%Y-%m-%d") # 常用time.strptime('2018-07-20', "%Y-%m-%d") # 返回九元组时间格式time.strftime('%H:%M:%S')###########################################from datetime import datetimefrom datetime import timedelta datetime.today() # 返回当前时间的 datetime 对象datetime.now() # 同上,可以用时区作参数datetime.strptime('2018/06/30', '%Y/%m/%d') # 返回 datetime 对象dt = datetime.today()datetime.ctime(dt)datetime.strftime(dt, "%Y%m%d")days = timedelta(days=90, hours=3) # 常用dt2 = dt + days dt2.year dt2.month dt2.day dt2.hour1234567891011121314151617181920212223242526272829
57-os 模块常用方法
import os os.getcwd() # 显示当前路径os.listdir() # ls -aos.listdir('/tmp') # ls -a /tmpos.mkdir('/tmp/mydemo') # mkdir /tmp/mydemoos.chdir('/tmp/mydemo') # cd /tmp/mydemoos.listdir()os.mknod('test.txt') # touch test.txtos.symlink('/etc/hosts', 'zhuji') # ln -s /etc/hosts zhujios.path.isfile('test.txt') # 判断 test.txt 是不是文件os.path.islink('zhuji') # 判断 zhuji 是不是软链接os.path.isdir('/etc')os.path.exists('/tmp') # 判断是否存在os.path.basename('/tmp/abc/aaa.txt')os.path.dirname('/tmp/abc/aaa.txt')os.path.split('/tmp/abc/aaa.txt')os.path.join('/home/tom', 'xyz.txt')os.path.abspath('test.txt') # 返回当前目录 test.txt 的绝对路径12345678910111213141516171819
58-pickle 存储器
import pickle"""以前的文件写入,只能写入字符串,如果希望把任意数据对象(数字、列表等)写入文件, 取出来的时候数据类型不变,就用到 pickle 了 """# shop_list = ["eggs", "apple", "peach"]# with open('/tmp/shop.data', 'wb') as fobj:# pickle.dump(shop_list, fobj)with open('/tmp/shop.data', 'rb') as fobj:mylist = pickle.load(fobj)print(mylist[0], mylist[1], mylist[2])12345678910111213
59-异常处理基础
try: # 把有可能发生异常的语句放到 try 里执行n = int(input("number: "))result = 100 / nprint(result)except ValueError:print('invalid number')except ZeroDivisionError:print('0 not allowed')except KeyboardInterrupt:print('Bye-bye')except EOFError:print('Bye-bye')print('Done')1234567891011121314
60-异常处理完整语法
try:n = int(input("number: "))result = 100 / nexcept (ValueError, ZeroDivisionError):print('invalid number')except (KeyboardInterrupt, EOFError):print('\nBye-bye')else:print(result) # 异常不发生时才执行 else 子句finally:print('Done') # 不管异常是否发生都必须执行的语句# 常用形式有 try-except 和 try-finally12345678910111213
猜你喜欢
- 【Python】Python程序将本地时间转换为GMT时间
- 当我们创建一个允许世界各地的用户预订活动的 Web 服务时,我们可能会使用此程序将每个用户的当地时间转换为 GMT,然后再将其放入数据库中。这将使不同时区的用户更容易比较和显示事件时间。不同时区的用户更容易比较和显示事件时间。在 Python 中,我们有一些内置的时间函数,如 timezone()、localize()、now() 和 astimezone(),可用于将本地时间转换为 GMT。当地时间代表当前时间,而 GMT 是通过计算本初子午线定义的。 GMT 代表格林威治标准时间,但现在称为
- 【Python】Python中的字典与JSON之间的相互转换方法有哪些?
- Python中的字典与JSON之间的相互转换方法有哪些?作为一种十分常用的数据结构,字典在Python中被广泛应用。而JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,也被广泛应用于网络数据传输和存储。在Python中,字典与JSON之间的相互转换是一项常见的操作。本文将介绍几种常用的方法,并附上相应的代码示例。方法一:使用json模块的dumps()函数和loads()函数json模块是Python标准库中用于处理JSON数据的模块。其中,dumps
- 【Python】10个常用python标准库
- Python的标准库包含了大量的模块和函数,这些模块和函数为Python提供了丰富的功能和工具。以下是10个常用的Python标准库:os模块:提供了许多与操作系统交互的函数,例如访问文件系统、创建文件夹、获取环境变量等。sys模块:提供了与Python解释器交互的函数,例如访问命令行参数、退出程序、获取Python解释器的信息等。re模块:提供了正则表达式相关的函数和类,用于匹配和处理文本数据。json模块:提供了处理JSON格式数据的函数和类,例如将JSON数据解析为Python对象、将Py
- 【Python】在Python中如何安装pandas库的方法
- Python中如何安装pandas库?Pandas是一个强大且灵活的数据分析工具,它提供了丰富的数据结构和数据分析功能,使得数据处理更加快速和方便。本文将介绍如何在Python中安装pandas库,并提供具体的代码示例。在开始安装之前,确保你已经安装了Python环境。你可以在Python官网(https://www.python.org)下载最新版本的Python安装程序,并按照提示进行安装。在Python中安装pandas库有多种方法,例如使用pip或conda等软件包管理工具。下面我们将分
- 【Python】Python实现多继承的方法和关注点
- Python多继承的实现方法及注意事项多继承是Python中一个重要的特性,它允许一个类继承多个父类的属性和方法。在实际开发中,多继承可以帮助我们更好地组织和重用代码。本文将介绍Python中多继承的实现方法,并提供一些注意事项。一、多继承的基本概念多继承是指一个类可以同时继承多个父类的特性。在Python中,多继承是通过使用逗号分隔的多个父类来实现的。二、多继承的实现方法方法一:使用super()函数super()函数是一个内置函数,它可以调用父类的方法。在多继承的情况下,可以通过super(
- 【Python】matplotlib显示中文字符的有效方法详解
- 详解matplotlib中显示中文的有效方法,需要具体代码示例在数据可视化中,matplotlib是一个非常常用的库,它提供了强大且灵活的绘图功能。然而,matplotlib默认不支持显示中文字符,这给使用者带来了不便。本文将介绍一些在matplotlib中显示中文的有效方法,并提供具体的代码示例。方法一:使用系统字体matplotlib可以通过设置系统字体路径来实现显示中文。首先,我们需要找到系统中对应的字体文件,比如微软雅黑字体的路径为"C:/Windows/Fonts/msyh.
- 【Python】pythonGUI写一个exe桌面应用程序
- 一、整体步骤1、安装pyinstaller 3.02、安装wxpython3、安装布局工具wxFormBuilder4、将png生成icon5、upx391w(打包成exe程序)二、工具安装安装布局工具(wxFormBuilder_v3.5.1-rc1.exe)下载地址:http://sourceforge.net/projects/wxformbuilder/files/wxformbuilder/3.1.70/教程地址:https://www.cnblogs.com/jikeboy/p/56
- 【Python】pandas数据分析技巧全面解析:从初学到专家
- Pandas是Python中最常用的数据分析库之一,它为数据处理和分析提供了丰富的功能和高效的工具。本文将从入门到精通,介绍一些常用的Pandas数据分析方法,并提供具体的代码示例。一、数据导入与基本操作导入Pandas库和数据集首先,需要导入Pandas库并加载数据集。可以使用以下代码示例:import pandas as pd # 加载CSV文件 data = pd.read_csv('data.csv&#39