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. 由老同事学习SAP所想到的

    前段时间一位老同事在微信上跟我说他们公司正计划导SAP系统,但整个IT中心几乎无人使用过SAP,知道我在这行业干了多年了,所以想问我怎么开始学习.于是我约他今天出来聊聊,顺便把手里的SAP ECC E ...

  2. android常用控件的使用方法

    引言 xml很强大 TextView <TextView android:id="@+id/text_view" android:layout_width="mat ...

  3. 解读邮箱正则表达式:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

    转自:http://www.cnblogs.com/joyceTING/archive/2013/05/09/3069089.html正则表达式 \w+([-+.]\w+)*@\w+([-.]\w+) ...

  4. 11.IntelliJ IDEA详细配置和使用教程(适用于Java开发人员)

    转自:https://blog.csdn.net/chssheng2007/article/details/79638076 前言 正所谓工欲善其事必先利其器,对开发人员而言若想提高编码效率,一款高效 ...

  5. Idea的一些调试技巧及设置todo

    程序员的工作内容,除了大部分时间写代码之外,因为有不少的时间是用在调试代码上.甚至说不是在调试代码,就是即将调试代码. :) 今天我们来谈谈调试代码的一些技巧,在使用IDE提供的debugger时一些 ...

  6. 洛谷 P4148 简单题 KD-Tree 模板题

    Code: //洛谷 P4148 简单题 KD-Tree 模板题 #include <cstdio> #include <algorithm> #include <cst ...

  7. HTML5的核心内容

    开发者可以放心地使用html5的理由 兼容性.HTML5在老版本的浏览器可以正常运行,同时支持HTML5的新浏览器也能正常运行HTML4,用HTML4创建出来的网站不是必须全部重建的. 实用性.HTM ...

  8. 新机器的vim配置

    最近一直用vim去写acm代码,算是一种练习吧. 用着用着感觉不错,最近也稍微配置了一下vim,用着更舒服了 键盘映射 ESC<->CapsLock 我们知道vim有自带的键盘映射命令,但 ...

  9. info---Linux下info格式的帮助指令。

    info命令是Linux下info格式的帮助指令. 它的几个常用快捷键. ?键:它就会显示info的常用快捷键. N键:显示(相对于本节点的)下一节点的文档内容. P键:显示(相对于本节点的)前一节点 ...

  10. [APIO2009]会议中心(贪心)

    P3626 [APIO2009]会议中心 题目描述 Siruseri 政府建造了一座新的会议中心.许多公司对租借会议中心的会堂很 感兴趣,他们希望能够在里面举行会议. 对于一个客户而言,仅当在开会时能 ...