Hello, guys! I found it pretty difficult to get my content according to my key words. So in this note, I'd like to optimize my key word to do some help.

Content

  • set: logical relation between sets; sets operation
  • file: file operation, including append, delete, modify and seek
  • encode & decode
  • function: definition, use, create, variety, recursive function and higher-order function

Part 1_SET

There are some codes to judge the relation between sets, involving intersection, union, difference, subset, superset. Also, sometimes sets need to be operated. Thus, some operations in sets like append and delete are worth our attention. Because they are really easy to understand and use, codes are presented directly below:

SET

Part 2_FILE

1 open & close

To open a file, command of open can be used and give the file value to a named variety. However, there are multiple modes to open a file, which decide how the file can be operated. Thus, these modes include:

  r: files can only be read;

  r+: files would be read first and append is allowed, most commonly use;

  rb: binary file, mainly used to open a binary file like net transferring file to prevent corrupting;

  w: create a file and write something new into the file, but cannot be read;

  w+: files would be wriiten first and read in the followting;

  a: append sth. new into the file;

  a+: append sth. new into the file and can be read;

And the complete code to open and close a file shows below:

f = open('time after time','r+')
f.write('hello binary'.encode())
f.close()

But sometimes, we always forget to use .close() to close a file. To prevent this from happening, the best way to open a file is with open:

import sys

# 自动关闭文件
with open('lyric','r',encoding='utf-8') as f1,\
open ('lyric.bak','r',encoding='utf-8') as f2:
for line in f1:
print(line)
for content in f2:
print(content)

2 operation: read & write

Several modes can be used to read a file, including read, readline, readlines. And codes can most clearly show their use:

# 读取5行数据并打印
for i in range(5):
print(f.readline()) # 将每行存成列表进行读取,readlines只适合于读小文件
for index,line in enumerate(f.readlines()):
if index == 9:
print('---------我是分割线--------')
continue
print(line.strip()) # improve last loop, making it possible to only store a line each time.
count = 0
for line in f:
if count == 3:
print('--------hhhhhhh-----------')
count += 1
continue
count += 1
print(line)

Usually, there is a pointer in the system to locate the file' content you're trying to operate. So we can use .tell() to tell the pointer's location anc use .seek() to get back to some specific position.

with open('lyric','r',encoding='utf-8') as f1,\
open ('lyric.bak','r',encoding='utf-8') as f2:
for line in f1:
print(line)
for content in f2:
print(content) print (f.tell()) # output the pointer's location of the file handle
print(f.readline())
print(f.readline())
print(f.readline())
print(f.tell())
f.seek(0) # tell--pointer's location; seek--back to some position; use both together usually
print(f.readline())

pointer

3 others

there are some other operations, like replace:

f = open('lyric','r',encoding = 'utf-8')
f_new = open('lyric.bak','w',encoding = 'utf-8') for line in f:
if'大大的世界上'in line:
line = line.replace('大大的世界上','aaaaayoyoyoyo')
f_new.write(line)
f.close()
f_new.close()

replace

flush: it's better to add .flush() in the file code to help update and store.  Besides, flush can be used to do some pretty interesting things. For example, flush can show the process of loading sth.

'''
利用flush显示进度条,stdout--标准输出,time.sleep--调整时间间隔
import sys以及time模块,显示进度条
''' import sys,time for i in range(50):
sys.stdout.write('#')
sys.stdout.flush()
time.sleep(0.1) # 设定刷新周期

flush

Part 3_ENCODE&DECODE

In this part, only one thing worth remembering: Unicode is the key to all. We can use .decode() to get to the unicode from other types and .encode() to get to the other coding types from unicode.

Part 4_FUNCTION

1 return

After defining a function, it's pretty important to use return to return a value. Because we need a result for the proof of executing a function.

# function
def func1():
'testing1'
print('in the func1')
return 0 # process: is a function without return
def func2():
'testing2'
print('in the func2') def func3():
'testing 3: return type,可以return任何东西'
print('in the func3')
return 0,'hello world',['hello',23],{'name':'Eva'} x = func1()
y = func2()
z = func3() print(x)
print(y)
print(z)

function&return

2 parameter

There are 2 parameters in the function. In the definition part, we need to define formal parameters. While using, actual parameters need to be defined. Besides, if parameters are input directly when invoking a function, they are named location parameters and one-to-one match with formal parameters. Also, key parameters can be used and location is not that important while using key parameters.

# (m,n)形参;(1,2)实参;一一对应
def test(m,n):
print(m)
print(n) # 位置参数调用
test(1,2) # 关键参数调用,关键字参数不能写在位置参数前面
test(n=5,m=7) # 默认参数特点:调用参数,默认参数非必须传递
# 用途:默认安装值;默认主机服务端口
def test2(i,k=7):
print(i)
print(k) test2(3)

parameters

3 *args & **kwargs

Well, sometimes, we are not that sure about the number of actual parameters. And then, *args & **kwargs can be used to transform parameters into tuple or dictionary.

# 实参数目不固定==》参数组,将其变成元组,*后面内容随意但最好是args
# *args接收的是位置参数,无法接收关键字参数
def test3(*args):
print(args) test3(1,3,6,5,4,2,8)
test3(*[1,3,6,5,4,2,8]) def test4(p,*name):
print(p)
print(name) test4(1,3,6,5,4,2,8) # N个关键字参数转换成字典--**kwargs,参数组往后放
def test5(**kwargs):
print(kwargs)
print(kwargs['nickname'])
print(kwargs['age'])
print(kwargs['gender']) test5(nickname = 'Eva',age = 66, gender = 'F')
test5(**{'nickname':'Eva','age':66, 'gender':'F'})

*args & **kwargs 1

# 需要先定义,再调用
# def test5(**kwargs):
# print(kwargs)
# print(kwargs['nickname'])
# print(kwargs['age'])
# print(kwargs['gender'])
# print(logger())
#
# test5(nickname = 'Eva',age = 66, gender = 'F')
#
# def logger(source):
# print('from %s' % source)

**kwargs 2

4 variety

The scope of the variety defined in a function can only be used in this function. If we want use it,  we need to global the variety.

school = 'UUU'

# 除了字符串和整数,列表、字典、集合、类都可以在函数的局部变量中直接修改全局变量
def change_name(name):
global school #如果想将局部变量作用于全部程序,要用global
school = 'xxx'
print('before change:',name,school)
name = 'Eva Han' #局部变量:这个函数就是这个变量的作用域
print('after change:',name) print(school)
name = 'eva'
change_name(name)
print(name)

local & global variety

5 recursion function

It's a function that would involk itself in the definition.

'''
递归:一个函数自我调用
要求:
1、有一个明确的结束条件,只能递归999次
2、问题规模应该逐渐减小
3、递归效率不高
''' def calc(x):
print(x)
if int(x/2)>0:
return calc(int(x/2))
print('--->',x) calc(10)

recursion function

6 high-order function

def add(a,b,c): return c(a)+c(b) result = add(3,-6,abs) print(result)

python note #3的更多相关文章

  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. 主程的晋升攻略(4):TCP、消息分包和协议设计

    在<主程的晋升攻略(3):IP.DNS和CDN>中,一次网络请求经过DNS解析知道了目的IP,如今就要发出网络包,这里我们说一说TCP的相关话题. TCP是一种流式协议 讲网络编程的教科书 ...

  2. ural 1989(树状数组+多项式hash)

    题意:给出一个字符串.有两种操作,一个是p a b,问字符串从位置a到位置b的子串是否是一个回文子串.还有一个操作 c a b,把字符串位置a的字符替换为b. 题解:由于字符串长度为1e5且问的次数也 ...

  3. iOS 中client和server的 Web Service 网络通信 (1)

    当你打开你手机上新浪微博应用或者知乎应用是.你是否会去想这些显示在手机上的图片和数据时从哪里来的?又是通过如何的方法实现的?好.那么接下来就介绍是如何实现的.过程又是怎么样的.      当我们浏览着 ...

  4. Fast Flux技术——本质就是跳板,控制多个机器,同一域名指向极多的IP(TTL修改为0),以逃避追踪

    转自:http://ytuwlg.iteye.com/blog/355718 通过病毒邮件和欺诈网站学到的对付网络封锁的好东西:Fast Flux技术 收到一封邮件,引起我的好奇了: 邮件标题是:Ha ...

  5. zookeeper的理解与概述

    文章转自https://www.cnblogs.com/likehua/p/3999600.html  感谢博主 文章转自:http://www.aboutyun.com/thread-9266-1- ...

  6. HBase框架基础(一)

    * HBase框架基础(一) 官方网址:http://hbase.apache.org/ * HBase是什么妖怪? 要解释HBase,我们就先说一说经常接触到的RDBMS,即关系型数据库: ** m ...

  7. 支付宝SDK集成加密库迁移错误问题

    最近项目中集成了第三方支付,主要有微信支付和支付宝支付,当然这里我主要想说一下关于集成支付宝支付. 首先从支付宝开发者网站上下载下来了SDK以及DEMO,我们就可以根据DEMO进行分析以及集成.支付宝 ...

  8. c# 对用户密码加密解密

    一.使用16位.32位.64位MD5方法对用户名加密 1)16位的MD5加密 ? 1 2 3 4 5 6 7 8 9 10 11 12 /// <summary> /// 16位MD5加密 ...

  9. Signal programming

    Signal programming is used in the same sense as dataflow programming, and is similar to event-driven ...

  10. es6 学习1 let表示变量 、const表示常量 与 var 变量的区别

    一.let 1.看下代码,在函数中无论在哪里声明变量,都会自动提到函数顶部,这就是函数变量提升,它的作用于为当前函数中. function aa() { if(bool) { var test = ' ...