Python Learning Notes-functions, collections, packages, modules

Source: Internet
Author: User

First, the function

A=1, b=2, Exchange value

Defines the c,c=none of the intermediate volume,

A,b=b,a

a,b,c=1,2,3

sys.argv

Implements certain functions specified, can be called directly when used, simplifies code, improves code reusability

def fun (): #定义一个函数, followed by a function name
Print ("Hello World") #函数体

For example:

1. Def sayHello ():

Print ("Hello World")

SayHello ()--Call

2. Def sayname (name):--Formal parameter

Print (' Welcome to log in%s '%name)

Sayname (' Alice ')--argument

3. Def calc (A, B):--Required parameters

Print (' result is%d '% (a+b))

Calc (2,3)

4. Link MySQL

def conn_mysql (host,username,passwd,port=3306)--port default parameter, not required, need to be written after required parameters

Print (' already connected to MySQL ')

Print (' IP ', host)

Print (' username ', username)

Print (' passwd ', passwd)

Print (' Port ', port)

Conn_mysql (' 1920168.0.0 ', ' Alice ', ' 123456 ')--position parameters, each corresponding

Conn_mysql (' 1920168.0.0 ', ' Alice ', ' 123456 ', 3309)--port3309

Conn_mysql (host= ' 1920168.0.0 ',

Passswd= ' 123456 ',

Username= ' Alice ')--keyword parameter, the position does not correspond

5, Def myfun (*arg):--variable parameter, parameter group, not limit the number of parameters, not required

Print (ARG)

Myfun (' Alice ', ' Emily ', ' 8080 ')

Keyword parameters must be placed last, variable and default parameters have no precedence

Order: Required parameter, default value parameter, parameter group, keyword parameter

6, Def myfun (**args):--Dictionary, keyword parameters

Print (args)

Myfun (name= ' Alice ', name1= ' Emily ', port= ' 8080 ')

--Output ' name ': ' Alice ', ' name1 ': Emily, ' Port ': 8080

7. Def calc (A, B):--Multiplication Calculator

Return a*b

Print (A*B)--Inside the function, the content behind the return is not executed, so it does not print

Res=calc (3*4)

Print (RES/2)

function does not write return, default returns none

8. Def calc (A, B):

C=A*B--Local variables

Print (c)

Calc (5,4)

Print (c)

Global variables defined in the first row

When printing, first find the keywords inside, priority printing

Modify the value of the global variable, using global, declare that the variable is a global variable, int, string, Ganso

The higher order function, the entry parameter of a function is a function

Two, set

A collection is also a data type, similar to a list, which is characterized by unordered, non-repeating, meaning that there is no duplicate data in the collection

Function of the collection:

1, it can be a list of duplicate data removed, and do not need you to write judgment

2, can do relationship testing, for example, there are two classes, a performance test class, one is the interface test class, want to find out both the performance and learning the interface test students, you can use the collection

List = [2,3,1,2,3,4]

S_list = set (list) #这样就定义了一个集合

Set1 = Set ([1,3,4,5,6]) #这种方式和上面的都是把list转换成一个集合

set2={' hehe ', ' hehe1 ', ' hehe3 '} #这种方式是直接定义一个集合

intersection– intersection

&--Take intersection

Union-collection of unions (combined de-weight)

| --Fetch and set

Difference--Take the difference set

Three, package, module OS SYS random time

Import Os,sys--built-in modules

Each python file is a module with an import file name (No. py)

The essence of the import module is to take the Python file and execute it once.

The role of environment variables is to have a command that can be used anywhere

Python setup.py Install

To modify the PIP Source:

Pip.ini

[Global]
Index-url = https://pypi.doubanio.com/simple/
[Install]
Trusted-host=pypi.doubanio.com

Pip Uninstall

From Pg.write_log import Write_log #直接导入包里面python文件里的函数
From PG Import Write_log #导入包里面的某一个python文件

Import json,requests
Url= ' Http://211.149.218.16:8081/get_user '
res = requests.get (URL). text
Res_dic = json.loads (res) #序列化, turn the JSON string into a dictionary

Import OS
Print (OS.GETCWD ()) #取当前工作目录

Os.chmod ("/usr/local", 7) #给文件/directory plus permissions
Print (Os.chdir (". /")) #更改当前目录
Print (Os.curdir) #当前目录
Print (Os.pardir) #父目录
Print (Os.makedirs ("/usr/hehe/hehe1")) #递归创建文件夹, parent directory does not exist when parent directory is created
Print (Os.removedirs ("/usr/hehe/hehe1")) #递归删除空目录
Print (Os.mkdir ("Test1")) #创建文件夹
Print (Os.rmdir ("Test1")) #删除指定的文件夹
Print (Os.remove ("Test")) #删除文件
Print (Os.listdir ('. ')) #列出一个目录下的所有文件
Os.rename ("Test", "Test1") #重命名
Print (Os.stat ("len_os.py")) #获取文件信息
Print (OS.SEP) #当前操作系统的路径分隔符
Print (OS.LINESEP) #当前操作系统的换行符
Print (OS.PATHSEP) #当前系统的环境变量中每个路径的分隔符, Linux is:, Windows is;
Print (Os.environ) #当前系统的环境变量
Print (Os.name) #当前系统名称
Print (Os.path.abspath (__file__)) #获取绝对路径
Print (Os.path.split ("/usr/hehe/hehe.txt")) #分割路径和文件名
Print (Os.path.dirname ("/usr/local")) #获取父目录
Print (Os.path.basename ("/usr/local")) #获取最后一级, if the file displays the filename, if the directory displays the directory name
Print (Os.path.exists ("/usr/local")) #目录/file is present
Print (Os.path.isabs (".")) #判断是否是绝对路径
Print (Os.path.isfile ("/usr/local")) #判断是否是一个文件
Print (Os.path.isdir ("/usr/local")) #是否是一个路径
Print (Os.path.join ("/root", ' hehe ', ' a.sql ')) #拼接成一个路径
Print (Os.path.getatime ("len_os.py")) #输出最近访问时间
Print (Os.path.getmtime ("len_os.py")) #输出最近访问时间

Sys

SYS.ARGV command line argument list, the first element is the path of the program itself
Sys.exit (n) exit program, Exit normally (0)
Sys.version get version information for Python interpreter
Sys.maxint the largest int value
Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.platform returns the operating system platform name
Sys.stdout.write (' please: ') #向屏幕输出一句话
val = Sys.stdin.readline () [: -1] #获取输入的值

Random
Print (Random.random ()) #随机浮点数, default to 0-1, cannot specify range
Print (Random.randint (1,20)) #随机整数
Print (Random.randrange (1,20)) #随机产生一个range
Print (Random.choice (' x23serw4 ')) #随机取一个元素
Print (random.sample (' Hello ', 2)) #从序列中随机取几个元素
Print (Random.uniform (1,9)) #随机取浮点数, you can specify a range
x = [1,2,3,4,6,7]
Random.shuffle (x) #洗牌, in order to change the value of the original list
Print (x)
Print (string.ascii_letters+string.digits) #所有的数字和字母

Import Datetime,time
Print (Time.timezone) #和标准时间相差的时间, unit is s
Print (Time.time ()) #获取当前时间戳
Print (Time.sleep (1)) #休息几s

Python Learning Notes-functions, collections, packages, modules

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.