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:

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

import sys

2. import os:

 # os用于系统交互,调用系统路径等
import os
# cmd_res = os.system('dir') # 只执行命令,不保存结果,系统交互
cmd_res = os.popen('dir').read()
print('---->',cmd_res)
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.

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

knowledge point

 example 1:

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

     

 # Author: Eva Han

 import getpass

 _username = 'eva'
_password = ''
username = input("username:")
password = input("password:") if _username == username and _password == password:
print("welcome {name} to my world!".format(name=username))
else:
print("invalid information!!!") 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')   

      

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

encode & decode

5. triple operation & systems

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

knowledge point

Part 2: List

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

 # Author: Eva Han
import copy
'''
功能:将所有人的名字存成列表并调用
新数据类型:列表
''' names = ['Peggi', 'Georgia', 'Peggi_Pappa',['Eva','Katrina'], 'Peggi_Mom'] # 按步长切片
print(names[0:-1:2])
print(names[::2])
print(names[:]) # 列表内容循环
for i in names:
print(i) '''
# 浅copy只copy第一层-创造联合账号,深copy可以copy到所有
name2 = names.copy()
name3 = copy.copy(names)
name5 = list(person) # 浅copy
name4 = copy.deepcopy(names)
names[3][1] = '0000'
print(names)
print(name2)
print(name3)
print(name4)
''' '''
# 附加与插入
names.append('Peggi_Grandpa')
names.insert(1,'Peggi_Grandma')
print(names) # 改与删
names[2] = 'new name'
names.remove('Peggi')
del names[0] # 与names.pop(0)相同
names.pop() # 默认删除最后一个值
print(names) print(names[0], names[2])
# 切片:从1位置取到3位置,起始位置包括,终止位置不包括
print(names[1:3])
# 取最后一个的值
print(names [-1])
print(names[-3:])
# 可以忽略0 # 输出位置
print(names[names.index('Peggi_Pappa')])
# count_统计数目,clear_清空列表,reverse_列表顺序反转
# sort_按特殊符号-数字-大写字母-小写字母顺序排序 print(names)
names2 = [1,2,3,4]
names.extend(names2)
print(names)
'''

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.

 # Author: Eva Han

 # 元组 = 只读列表
names = ('Eva','Anna','Nancy','Georgia','Nancy')
print(names.index('Georgia'))
print(names.count('Nancy'))

tuple

Part 4: String

All commands may be included in the string.

 # Author: Eva Han

 name = 'my \t{name} is {Eva} Han'

 # 首字母大写
print(name.capitalize())
# 计数字母
print(name.count('n'))
# 公输入50个字符,不满的用-填满
print(name.center(50,'-'))
# encode,discode
# endwith_以...结尾
print(name.endswith('ex'))
# 将tab键制定扩成空格
print(name.expandtabs(tabsize=20))
# 查找位置,进行切片
print(name[name.find('name'):])
# format进行格式化,format_map用于字典
print(name.format(name='kkk',Eva='qqq'))
print(name.format_map( {'name':'kkk','Eva':'qqq'} ))
# isalnum—是否是阿拉伯数字和字母
# isalpha-是否是英文(大写、小写)字母
# isdecimal-是否是十进制
# isdigit-是否是整数
# isidentifier-判断是不是一个合法的标识符、变量名
# islower - 是不是小写
# isnumeric - 判断是不是纯数字
# isspace - 是不是空格
# istitle - 每个首字母大写
# isprintable - 设备终端需要,ttf file/ drive file
# isupper - 是否全是大写
# join - 连接
print('ab_23'.isalnum())
print('+'.join(['','','','']))
# 左加*,右加*
print(name.ljust(50,'*'))
print(name.rjust(50,'*'))
# lower - 大写变小写
print('EVA'.lower())
print('eva'.upper())
# 从左边去掉空格与回车,\n换行
print(' Eva '.lstrip())
print(' Eva '.rstrip())
print(' Eva '.strip())
# 加密,对应转换,随机密码
p = str.maketrans('abcdef','')
print('Eva Han'.translate(p)) print('Eva'.replace('a','A',1)) # 替换第一个a
print('eva han'.rfind('h')) # 返回最后面的值
print('1+2+3+4+5+6'.split('+')) # 把字符串按--分成列表
print('1+2\n+3+4'.splitlines()) # 按换行符来存
print('Eva Han'.swapcase()) # 大小写互换
print('eva han'.title()) # 标题首字母大写
print('eva han'.zfill(50)) # 不够的用0填空

string

Part 5: Dictionary

 # Author: Eva Han
# 字典,索引表来查对应页的详细信息,key-value info = {
'':'Eva Han',
'':'Nancy Tang',
'':'Katrina Yue',
} print(info)
# print(info['2014110543'])
info[''] = '卡翠娜·岳'
info[''] = 'Dream High'
print(info)
# 获取数据
print(info.get(''))
print('' in info) # #del info['2014110543']
# info.pop('2014110543')
# #随机删除
# # info.popitem()
# print(info) # # 多级嵌套
website_collection = {
'search': {
'www.baidu.com':['most popular in China','use it when you are in China'],
'www.google.com':['popular around the world','best use, clean and convenient'],
'www.yahoo.com':['rarely use it','also needs vpn?']
},
'video':{
'www.aiqiyi.com':['BBC videos included','net video included'],
'www.bilibili.com':['otaku best love','nya my love!'],
'www.tencent.com':['just soso','cheap for students'],
},
'music':{
'www.wangyinetmusic.com':['good music list','good quality'],
'kugou_music':['emmmmmmmmmmmmm','cheap vip?'],
'kuwo_music':['memories','just soso'],
},
} # 替换
website_collection['video']['www.bilibili.com'][1]='you like it!'
# 有值返回,无值增加
website_collection.setdefault('study',{'English':['new orientation','famous']})
print(website_collection) # update: 合并字典,有交叉更新,无交叉覆盖
b = {1:2,3:4,'':'Tang Fan'}
info.update(b)
print(info) # items 字典变列表
print(info.items()) # fromkeys 初始化字典,三个key共享一个地址
c = dict.fromkeys([6,7,8],'test')
print(c) # 字典循环
for i in info:
print(i,info[i]) # 这种没有上一种高效
for k,v in info.items():
print(k,v)

dictionary

example 3: three-level menu

 # Author: Eva Han

 location = {
'sichuan':{
'chengdu':{ 'jinniu','xipu', 'qingyang'},
'mianyang':{'youxian','anzhou'},
'beichuan':{'dongcheng','xicheng','beicheng'}
},
'chongqing':{
'wanzhou':{'zhuxiang','jiuchi'},
'changshou':{111,222,333},
'banan':{000,444,555},
},
'Yunnan':{
'kunming':{147,258,369},
'yuxi':{753,951,456},
'lijiang':{777,888,999},
},
}
exit_flag = False while not exit_flag:
for i in location:
print(i)
choice1 = input('>>choose province:')
if choice1 in location:
while not exit_flag:
for j in location[choice1]:
print('\t',j)
choice2 = input('>>choose city:')
if choice2 in location[choice1]:
while not exit_flag:
for k in location[choice1][choice2]:
print('\t\t',k)
choice3 = input('>>choose district,final level, press b to go back, press q to quit:')
if choice3 == 'b':
break
elif choice3 == 'q':
exit_flag = True
if choice2 == 'b':
break
elif choice2 == 'q':
exit_flag = True # 字典中按值返回,列表中按位置返回

3-level menu

python note #2的更多相关文章

  1. python note

    =和C一样,为赋值.==为判断,等于.但是,在python中是不支持行内赋值的,所以,这样避免了在判断的时候少写一个出错. dictionary 的key唯一,值可以为很多类型. list的exten ...

  2. python note 4

    1.使用命令行打开文件 t=open('D:\py\123.txt','r') t.read() 在python和很多程序语言中""转义符号,要想输出\要么多加一个\写成\ 要么在 ...

  3. python note 17 random、time、sys、os模块

    1.random模块(取随机数模块) # 取随机小数 : 数学计算 import random print(random.random())# 取0-1之间的小数 print(random.unifo ...

  4. python note 16 re模块的使用

    1.re模块(#regex) # 查找 # findall : 匹配所有 每一项都是列表中的一个元素 import re ret = re.findall('\d+','dawdawd154wadwa ...

  5. python note 15 正则表达式

    # 正则表达式 只和字符串打交道 # 正则表达式的规则# 规则 字符串 从字符串中找到符合规则的内容 # 字符组 : [] 写在中括号中的内容,都出现在下面的某一个字符的位置上都是符合规则的 # [0 ...

  6. python note 12 生成器、推导式

    1.生成器函数 # 函数中如果有yield 这个函数就是生成器函数. 生成器函数() 获取的是生成器. 这个时候不执行函数# yield: 相当于return 可以返回数据. 但是yield不会彻底中 ...

  7. python note 10 函数变量

    1.命名空间 #内置命名空间 —— python解释器 # 就是python解释器一启动就可以使用的名字存储在内置命名空间中 # 内置的名字在启动解释器的时候被加载进内存里#全局命名空间 —— 我们写 ...

  8. python note 01 计算机基础与变量

    1.计算机基础. 2.python历史. 宏观上:python2 与 python3 区别: python2 源码不标准,混乱,重复代码太多, python3 统一 标准,去除重复代码. 3.pyth ...

  9. python note of decorator

    def decorate_log(decorate_arg,*args,**kwargs): # 存放装饰器参数 def decorate_wrapper(func,*args,**kwargs): ...

  10. python note #1

    To record my process of studying python and to practice my English meanwhile, I'd like to start writ ...

随机推荐

  1. 经常使用传感器协议1:CJ/T-188 水表协议解析1

          本文以实例说明CJ/T-188水表协议的解析过程,下面数据未经特殊说明,均指十六进制. 数据发送:         FE FE FE FE 68 10 44 33 22 11 00 33 ...

  2. matplotlib 可视化 —— 定制 matplotlib

    1. matplotlibrc 文件 matplotlib使用matplotlibrc [matplotlib resource configurations] 配置文件来自定义各种属性,我们称之为 ...

  3. windows电脑空间清理

    最近电脑空间又快满了,想下载一些好电影音频资源都要先临时清理一些文件才行,今天有时间就彻底整理一下,将整理过程及用到的好工具都记录一下,方面下次再遇到问题时可以很方面的参考执行. 1.分析磁盘空间占用 ...

  4. [JZOJ3383] [NOIP2013模拟] 太鼓达人 解题报告(数位欧拉)

    来源:XLk 摘录 HDU2894 Description 七夕祭上,Vani牵着cl的手,在明亮的灯光和欢乐的气氛中愉快地穿行.这时,在前面忽然出现了一台太鼓达人机台,而在机台前坐着的是刚刚被精英队 ...

  5. Most common words

    To find the most common words, we can apply the DSU pattern; most_common takes a histogram and retur ...

  6. 基于分布式的短文本命题实体识别之----人名识别(python实现)

    目前对中文分词精度影响最大的主要是两方面:未登录词的识别和歧义切分. 据统计:未登录词中中文姓人名在文本中一般只占2%左右,但这其中高达50%以上的人名会产生切分错误.在所有的分词错误中,与人名有关的 ...

  7. 51Nod 蜥蜴和地下室(搜索)

    哈利喜欢玩角色扮演的电脑游戏<蜥蜴和地下室>.此时,他正在扮演一个魔术师.在最后一关,他必须和一排的弓箭手战斗.他唯一能消灭他们的办法是一个火球咒语.如果哈利用他的火球咒语攻击第i个弓箭手 ...

  8. GoldenGate 性能优化方法

    从根本上讲,OGG复制性能和要复制的表是否存在主键和唯一索引有很大关系,所以从应用系统开发商对表结构的规范更为有效.OGG调优通常采用拆分进行的方式,拆分方法如下所述. Extract拆分方法 1)  ...

  9. 爬虫--BeautifulSoup使用

    解析库 解析器 使用方法 优势 劣势 Python标准库 BeautifulSoup(markup, "html.parser") Python的内置标准库.执行速度适中 .文档容 ...

  10. 去除input的前后的空格

    这里用的是jquery的方法