python note #2

This passage will talk about some small but pretty important knowledge points, including using method of string, tuple, dictionary and some specific examples.

Part 1: Import a Program

1. import sys:

1 import sys
2 print (sys.path) # 打印环境变量
3 print(sys.argv)
4 # Sys.argv[ ]其实就是一个列表,里边的项为用户输入的参数,
5 # 这参数是从程序外部输入的,而非代码本身的什么地方,要想看
6 # 到它的效果就应该将程序保存了,从外部来运行程序并给出参数。
7 print(sys.argv[2])
import sys

2. import os:

1 # os用于系统交互,调用系统路径等
2 import os
3 # cmd_res = os.system('dir') # 只执行命令,不保存结果,系统交互
4 cmd_res = os.popen('dir').read()
5 print('---->',cmd_res)
6 os.mkdir('new_dir')
import os

3. import a file from other directory

  use (import file_name) directly. And this knowledge point shows how the python file imported work.

1 '''
2 .pyc中,c = compile
3 命令行中输入python hello.py ---> (系统编译)--->激活解释器
4 python编译器结果 --> 内存中PyCodeObject --> 程序结束,PyCodeObject写回到.pyc文件中
5 再次运行时,直接读取.pyc,避免重复过程
6 即.pyc是PyCodeObject的永久保存文件
7 '''
knowledge point

 example 1:

  step1: create a file for importing and save it into 'D:\Python\Lib\site-packages'

     
 1 # Author: Eva Han
 2 
 3 import getpass
 4 
 5 _username = 'eva'
 6 _password = '123456'
 7 username = input("username:")
 8 password = input("password:")
 9 
10 if _username == username and _password == password:
11     print("welcome {name} to my world!".format(name=username))
12 else:
13     print("invalid information!!!")
14 
15 print(_username,_password)
password

  step2: import file_name

     import password 

4. the type of data

  1) number

    int  eg: 1, 2, 3

    float  eg: 3.23, 3E-6

    complex  eg: -5+4j 

  2) bull

    1 ---> True  0 ---> False

  3) string

    eg: 'Hello World!'

  4) types of bytes

          encode

    string ---------------------------------> bytes

         <--------------------------------  

          decode

     eg: '$20'.encode('utf-8')   

      
1 msg = '我爱python!'
2 print(msg.encode('utf-8'))
3 print(msg.encode('utf-8').decode('utf-8'))
encode & decode

5. triple operation & systems

 1 '''
 2 三元运算 triple operation
 3     result = 值1 if 条件 else 值2
 4 进制 system
 5     十六进制与二进制 (取四合一)
 6     0     /1     /2     /3     /4     /5     /6     /7     /8     /9
 7     0000  0001   0010   0011   0100   0101   0110   0111   1000   1001
 8     
 9     A     /B     /C     /E     /F
10     1010  1011   1101   1110   1111
11     十六进制
12         H ---> 后缀 BH表示的是B
13         0X ---> 前缀 0X53表示的是53
14         补位 ---> 以小数点为分割线,向左向右取四位后进行补位
15             eg:10111.011 ---> 0001 、 0111 、 0110
16 
17 '''
knowledge point

Part 2: List

function: save all users' name into a list and use it

 1 # Author: Eva Han
 2 import copy
 3 '''
 4 功能:将所有人的名字存成列表并调用
 5 新数据类型:列表
 6 '''
 7 
 8 names = ['Peggi', 'Georgia', 'Peggi_Pappa',['Eva','Katrina'], 'Peggi_Mom']
 9 
10 # 按步长切片
11 print(names[0:-1:2])
12 print(names[::2])
13 print(names[:])
14 
15 # 列表内容循环
16 for i in names:
17     print(i)
18 
19 '''
20 # 浅copy只copy第一层-创造联合账号,深copy可以copy到所有
21 name2 = names.copy()
22 name3 = copy.copy(names)
23 name5 = list(person)  # 浅copy
24 name4 = copy.deepcopy(names)
25 names[3][1] = '0000'
26 print(names)
27 print(name2)
28 print(name3)
29 print(name4)
30 '''
31 
32 '''
33 # 附加与插入
34 names.append('Peggi_Grandpa')
35 names.insert(1,'Peggi_Grandma')
36 print(names)
37 
38 # 改与删
39 names[2] = 'new name'
40 names.remove('Peggi')
41 del names[0] # 与names.pop(0)相同
42 names.pop() # 默认删除最后一个值
43 print(names)
44 
45 print(names[0], names[2])
46 # 切片:从1位置取到3位置,起始位置包括,终止位置不包括
47 print(names[1:3])
48 # 取最后一个的值
49 print(names [-1])
50 print(names[-3:])
51 # 可以忽略0
52 
53 # 输出位置
54 print(names[names.index('Peggi_Pappa')])
55 # count_统计数目,clear_清空列表,reverse_列表顺序反转
56 # sort_按特殊符号-数字-大写字母-小写字母顺序排序
57 
58 print(names)
59 names2 = [1,2,3,4]
60 names.extend(names2)
61 print(names)
62 '''
list

Notice!!! The logic about assigning a value between string, number and lists is pretty different.

example 2: 

  1) string and number

    a = 1 ---> b = a ---> a = 555 ---> b = 1

  2) list

    a = [1, 2, 3] ---> b=a ---> a[1] = 555 ---> b = [1, 555, 3]

Part 3: Tuple

The Tuple can only be read, and cannot be revised.

1 # Author: Eva Han
2 
3 # 元组 = 只读列表
4 names = ('Eva','Anna','Nancy','Georgia','Nancy')
5 print(names.index('Georgia'))
6 print(names.count('Nancy'))
tuple

Part 4: String

All commands may be included in the string.

 1 # Author: Eva Han
 2 
 3 name = 'my \t{name} is {Eva} Han'
 4 
 5 # 首字母大写
 6 print(name.capitalize())
 7 # 计数字母
 8 print(name.count('n'))
 9 # 公输入50个字符,不满的用-填满
10 print(name.center(50,'-'))
11 # encode,discode
12 # endwith_以...结尾
13 print(name.endswith('ex'))
14 # 将tab键制定扩成空格
15 print(name.expandtabs(tabsize=20))
16 # 查找位置,进行切片
17 print(name[name.find('name'):])
18 # format进行格式化,format_map用于字典
19 print(name.format(name='kkk',Eva='qqq'))
20 print(name.format_map( {'name':'kkk','Eva':'qqq'} ))
21 # isalnum—是否是阿拉伯数字和字母
22 # isalpha-是否是英文(大写、小写)字母
23 # isdecimal-是否是十进制
24 # isdigit-是否是整数
25 # isidentifier-判断是不是一个合法的标识符、变量名
26 # islower - 是不是小写
27 # isnumeric - 判断是不是纯数字
28 # isspace - 是不是空格
29 # istitle - 每个首字母大写
30 # isprintable - 设备终端需要,ttf file/ drive file
31 # isupper - 是否全是大写
32 # join - 连接
33 print('ab_23'.isalnum())
34 print('+'.join(['1','2','3','4']))
35 # 左加*,右加*
36 print(name.ljust(50,'*'))
37 print(name.rjust(50,'*'))
38 # lower - 大写变小写
39 print('EVA'.lower())
40 print('eva'.upper())
41 # 从左边去掉空格与回车,\n换行
42 print('  Eva  '.lstrip())
43 print('  Eva  '.rstrip())
44 print('  Eva  '.strip())
45 # 加密,对应转换,随机密码
46 p = str.maketrans('abcdef','123456')
47 print('Eva Han'.translate(p))
48 
49 print('Eva'.replace('a','A',1)) # 替换第一个a
50 print('eva han'.rfind('h')) # 返回最后面的值
51 print('1+2+3+4+5+6'.split('+')) # 把字符串按--分成列表
52 print('1+2\n+3+4'.splitlines()) # 按换行符来存
53 print('Eva Han'.swapcase()) # 大小写互换
54 print('eva han'.title()) # 标题首字母大写
55 print('eva han'.zfill(50)) # 不够的用0填空
string

Part 5: Dictionary

 1 # Author: Eva Han
 2 # 字典,索引表来查对应页的详细信息,key-value
 3 
 4 
 5 info = {
 6     '2018200079':'Eva Han',
 7     '2014110543':'Nancy Tang',
 8     '2018200063':'Katrina Yue',
 9 }
10 
11 print(info)
12 # print(info['2014110543'])
13 info['2018200063'] = '卡翠娜·岳'
14 info['2019500033'] = 'Dream High'
15 print(info)
16 # 获取数据
17 print(info.get('2014110542'))
18 print('2014110543' in info)
19 
20 # #del info['2014110543']
21 # info.pop('2014110543')
22 # #随机删除
23 # # info.popitem()
24 # print(info)
25 
26 
27 # # 多级嵌套
28 website_collection = {
29     'search': {
30         'www.baidu.com':['most popular in China','use it when you are in China'],
31         'www.google.com':['popular around the world','best use, clean and convenient'],
32         'www.yahoo.com':['rarely use it','also needs vpn?']
33     },
34     'video':{
35         'www.aiqiyi.com':['BBC videos included','net video included'],
36         'www.bilibili.com':['otaku best love','nya my love!'],
37         'www.tencent.com':['just soso','cheap for students'],
38     },
39     'music':{
40         'www.wangyinetmusic.com':['good music list','good quality'],
41         'kugou_music':['emmmmmmmmmmmmm','cheap vip?'],
42         'kuwo_music':['memories','just soso'],
43     },
44 }
45 
46 # 替换
47 website_collection['video']['www.bilibili.com'][1]='you like it!'
48 # 有值返回,无值增加
49 website_collection.setdefault('study',{'English':['new orientation','famous']})
50 print(website_collection)
51 
52 # update: 合并字典,有交叉更新,无交叉覆盖
53 b = {1:2,3:4,'2014110543':'Tang Fan'}
54 info.update(b)
55 print(info)
56 
57 # items 字典变列表
58 print(info.items())
59 
60 # fromkeys 初始化字典,三个key共享一个地址
61 c = dict.fromkeys([6,7,8],'test')
62 print(c)
63 
64 # 字典循环
65 for i in info:
66     print(i,info[i])
67 
68 # 这种没有上一种高效
69 for k,v in info.items():
70     print(k,v)
dictionary

example 3: three-level menu

 1 # Author: Eva Han
 2 
 3 location = {
 4     'sichuan':{
 5         'chengdu':{ 'jinniu','xipu', 'qingyang'},
 6         'mianyang':{'youxian','anzhou'},
 7         'beichuan':{'dongcheng','xicheng','beicheng'}
 8     },
 9     'chongqing':{
10         'wanzhou':{'zhuxiang','jiuchi'},
11         'changshou':{111,222,333},
12         'banan':{000,444,555},
13     },
14     'Yunnan':{
15         'kunming':{147,258,369},
16         'yuxi':{753,951,456},
17         'lijiang':{777,888,999},
18     },
19 }
20 exit_flag = False
21 
22 while not exit_flag:
23     for i in location:
24         print(i)
25     choice1 = input('>>choose province:')
26     if choice1 in location:
27         while not exit_flag:
28             for j in location[choice1]:
29                 print('\t',j)
30             choice2 = input('>>choose city:')
31             if choice2 in location[choice1]:
32                 while not exit_flag:
33                     for k in location[choice1][choice2]:
34                         print('\t\t',k)
35                     choice3 = input('>>choose district,final level, press b to go back, press q to quit:')
36                     if choice3 == 'b':
37                             break
38                     elif choice3 == 'q':
39                             exit_flag = True
40             if choice2 == 'b':
41                 break
42             elif choice2 == 'q':
43                 exit_flag = True
44 
45 # 字典中按值返回,列表中按位置返回
3-level menu

猜你喜欢

转载自www.cnblogs.com/Eva-Han0615/p/10589392.html