Python Automation fifth session

Source: Internet
Author: User

First, the function,

1. Built-in functions
Python comes with some of the functions that come directly to use
ID () #看内存地址
Type () #看数据类型
Print () #打印
Input () #输入
List () #转list
Set () # Go to Collection
STR () #转字符串
Dict () #转字典
Int () #转int
Float () #转float类型
Len () #取长度
Max ()
Min ()
Dir () #帮助你的
Sorted () #排序
Round (11.00011,2) #保留几位小数
2. Functions defined by yourself:
def # name    of function Print ('hello') # function Body

Note: The function is not called and is not executed

Say () #调用就可以了

Parameters for functions: required and default parameters, default parameters can be blank

1 defCalc (A, B):#Formal parameter, form parameters2     #positional parameters, required parameters3res = A *b4     Print('%s *%s =%s'%(a,b,res))5 6 #Calc (7,8) #实参, actual parameters7 defOp_file (file_name,conent=None):8     #default value parameter, it is not required9f = open (file_name,'A +', encoding='Utf-8')Ten f.seek (0) One     ifConent:#do not write for empty representatives A f.write (conent) - F.flush () -     Else: theAll_users =F.read () -         returnAll_users#What results are returned after the function is called - f.close () - #res = op_file (' a.txt ') + #Print (res) - defhaha (): +     #function, the return function is immediately over. A      forIinchRange (5): at         Print(i) -         ifI==3: -             return  #just write a return and return to none. - #res = haha () - #Print (res)
parameter Explanation
1 defIs_float (s):2s =Str (s)3     ifS.count ('.') ==1:#number of decimal points4S_list = S.split ('.')5left = S_list[0]#left of decimal point6right = S_list[1]#right of decimal point7         ifLeft.isdigit () andRight.isdigit ():#Positive Decimals8             returnTrue9         elifLeft.startswith ('-') andLeft.count ('-') ==1 and TenLeft.split ('-') [1].isdigit () and  OneRight.isdigit ():#Judging legal negative decimals A                 returnTrue -     returnFalse
Example: A function that determines whether a legal decimal is valid

About the invariant parameters of a function: parameter groups and keyword parameters

defSyz (A,*args):#parameter group *arg is a non-required parameter, without limiting the number of parameters    Print(a) Username=Args[0] pwd= Args[1] Age= Args[2]#Syz (' Niuhanyang ', ' 2423 ', 2323)#syz (' 1s ', ' sdf ')defSYZ2 (Time,**kwargs):#keyword parameter, non-required parameter, no limit on the number of parameters    Print(Kwargs) syz2 ('SDF')#{}SYZ2 (name='Nhy', age=38,time='20180912') syz2 ('2018', name='Nhy', age=38,addr='Huilongguan', home='Henan') syz2 ( time='xx', xx='XXX')
non-fixed parameters

About recursion, that is, the function itself calls itself

deftest1 (): Num= Int (Input ('Please enter a number:'))    ifNum%2==0:#determine if the number entered is even       returnTrue#if it is an even number, the program exits and returns True.    Print('not even please re-enter! ')    returnTest1 ()#if it is not even, continue calling yourself, enter the value#print (Test1 ()) #调用test#Recursion is less recursive, recursion is recursive 999, and recursion is inefficient. 
Recursive Example

2nd variable, constant

Variable branch variables and global variables,

Local variables: Only valid within function, out of function invalid

Global variables: Once modified, it will affect the entire code, so it is not safe, if you want to modify the global variables, you need to declare that you want to modify the global variables

A constant is an unchanging value.

' Cheion ' # Global Variables # If you want to change the global variables, then you must first declare that you modify the value is a global variable def sayname ():     Global name     ' Liu Wei '    Print ('name1', name)

Module:

Use of the Random module JSON module after introduction

Import random,json,string

Random,string

 1  import   random,string  2  #   print ( string.printable) #代表 numbers + letters + special characters  3  #   print (Random.randint (1,10)) #随机取整数  4  #   print (round (Random.uniform (1,99), 2)) # Random decimal  5  #   print (Random.choice ([1,2,3,4])) #只能随机取1个元素  6  #   print ( Random.sample (string.printable,5)) #随机取N个元素, returns a list  
1 pickts = ['A','J','Q' ,'K', 2,3,4,5,6]2# can only pass list3  Print(pickts)
Example: Shuffle

JSON module

Introducing the JSON module

Import JSON
ImportJSON#The JSON string is a stringf = open ('Product.json', encoding='Utf-8')#res = F.read ()#product_dic = json.loads (res) #把json串, the data type that becomes Python#Print (Json.load (f)) #传一个文件对象 It will help you read the fileD =  {    'Zll':{        'Addr':'Beijing',        ' Age': 28    },    'LJJ':{        'Addr':'Beijing',        ' Age': 38}}FW= Open ('User_info.json','W', encoding='Utf-8')#Dic_json = json.dumps (d,ensure_ascii=false,indent=4) #字典转成json, the dictionary turns into a string#fw.write (Dic_json)Json.dump (d,fw,ensure_ascii=false,indent=10)#Manipulating Files

About modifying files

Method One,

1. Open a file to get all of his content
2. Modify the Content
3. Empty the contents of the original file
4. Write the new content in
f = open ('username',' a+' for inch F:     ='syz_'+s    all_str=all_str+# empty file contents  f.write (ALL_STR) f.close ()

Method Two,

1. Open 2 files
2.a file
3. Write a line to the B file
4.a.txt A.txt.bak
5. Delete a file, b file name changed to a file name into OS
ImportOswith Open ('words', encoding='Utf-8') as Fr,open ('. Words.bak','W', encoding='Utf-8') as FW: forLineinchFr:new_line= Line.replace ('Flowers','Flower') Fw.write (new_line) os.remove ('words')#Deleting FilesOs.rename ('. Words.bak','words')#renaming



Python Automation fifth session

Related Article

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.