Python,day3-python Foundation 3

Source: Internet
Author: User

1. What is the basic syntax and function of the function?

function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, the specific difference, we will say later, the function of programming in English also has a lot of different names. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

Characteristics:

    1. Reduce duplicate code

    2. To make the program extensible

    3. Make programs easier to maintain

Syntax definitions
Def sayhi (): #函数名 print ("Hello, I ' m nobody!") Sayhi () #调用函数

can take parameters

#下面这段代码a, b = 5,8c = A**bprint (c) #改成用函数写def calc (x, y): res = x**y return res #返回函数执行结果 c = Calc (b) # result assigned to c variable print (c)
2. Function parameters and Local variables

A parameter variable allocates a memory unit only when it is called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

650) this.width=650; "Src=" Http://s3.51cto.com/wyfs02/M00/85/DA/wKioL1esUsyQ85ZtAABeHblJ2rA475.png-wh_500x0-wm_3 -wmp_4-s_3572000357.png "title=" parameter. png "alt=" wkiol1esusyq85ztaabehblj2ra475.png-wh_50 "/>

3. Default parameters

Look at the code below

def func_test (x, y): #x, y for parameter res = x+y return Resz = func_test (2,4) #2, 4 for x, y argument print (z)


Test (x,y,z=9) test (1,z=8,y=2) test C:\Users\congcong.du\AppData\Local\Programs\Python\Python35\ Python.exe c:/users/congcong.du/pycharmprojects/test/day3/123------------------------129------------

In addition, you may have noticed that after turning the country into the default parameter, I moved the position to the last side, why?


4. Parameter group *args, pass dictionary **kwargs


#参数组 # If your function is undefined, you can use a non-fixed parameter if you are not sure how many arguments the user wants to pass in. #*args  receive positional parameters, do not accept keyword parameters, convert to tuple def test1 (Name,*args):         Print (name)         print (args) test1 ("Alex", 1,2,3,4,5,5) C:\Users\ congcong.du\appdata\local\programs\python\python35\python.exe c:/users/congcong.du/pycharmprojects/test/ Day3/func.pyalex (1, 2, 3, 4, 5, 5) print ("========= dictionary =======") #传字典  **kwargs  : Convert keyword argument to dictionary def test2 (**kwargs):         print (Kwargs)          print (kwargs["name"]) test2 (name= "Alex", age=8,sex= "man") test2 (**{' age ': 8,  ' name ':  ' Alex ',  ' sex ':  ' man '}) #混和def  test3 (Name,age=18,**kwargs):         print (name)         print (age )         print (Kwargs) test3 ("Alex",  sex= "man") test3 ("Alex", 1,sex= "man", hobby= "TSL") test3 ("Alex", sex= "man", hobby= "TSL", age=1) print ("---------------------") def  test4 (Name,age=18,*args,**kwargs):     print (name)     print (age)     print (args)     print (Kwargs) test4 ("Alex", 34,1,2,3,sex= "man",  Hobby= "TSL")   #关键字参数, be sure to maintest4 after the last position parameter ("Alex", age=34,sex= "man", hobby= "TSL")

5. Local Variables

Local variables only work within his scope, and can also be declared as global variables, but it is not recommended because it can be messy when writing code long.

def change_name (name): Print ("Before change:", name) name = "local variable inside" print ("After change:", name) name= (' Outside Change_name (name) print ("Look outside name changed?", "name") ' before change: outside of the variable after the change inside the variable outside to see the name changed? Outside of the variable ' ' '
Print ("=========== global/local variable =======") Sex = "M" Def TEST5 (n): #global age #如果要在函数内改全局变量, use global to declare sex = "G" #局部变量改不了全局的变量 Print ("Before Change:", n,sex) n = "Alex Li" #这个函数就是这个变量的作用域 age = Print ("After change:", N,age,sex) NA me = "Alex" Test5 (name) #print (name,age,sex) #age局部变量不能在函数外使用print (name,sex)

Within a function is the ability to modify the global list

Print ("====== function modification List = = = =") names = ["Alex", "Jack", "Rain"]def change_list (): names[0]= "Alex" Print (names) change_list () Print (names)

6. Recursive functions
#函数内部调用自己. #1. There must be a definite end condition with a maximum recursion count of 999. #2. Each time you enter a deeper level of recursion, the problem size should be reduced by up to the previous recursion. Inefficient, too many recursive hierarchies can cause stacks to overflow (in a computer, function calls are implemented through the data structure of the stack). Whenever a function call is entered, the stack adds a stack frame, and whenever the function returns, the stack is reduced by a stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.
Print ("======== recursive function =========") #函数内部调用自己. 1. There must be a clear end condition with a maximum recursion count of 999. #2. Each time you enter a deeper level of recursion, the problem size should be reduced by as much as the last recursion. Low efficiency def TEST6 (n): print (n) if int (N/2) > 0:retur n Test6 (int (N/2)) print ("--", N) test6 (10)
7. Higher-order functions
Print ("======== higher order function =========") #变量可以指向函数, the function parameter can receive the variable, then one function can receive another function as the parameter, this function is called the higher order function. #abs converted to positive function def add (x,y,f): Return f (x) +f (y) res = Add (3,-6,abs) print (res)


8. Character encoding and transcoding

The default character encoding in Python3 is Unicode and can be encode directly to other encodings

The default in Python2 is GBK under Windows, all non-Unicode first decode to Unicode, and then encode to other character encodings.

Borrowing diagram

650) this.width=650; "Src=" Http://s2.51cto.com/wyfs02/M02/85/DC/wKiom1esacvA6DnyAAMp8AVB0cs616.png-wh_500x0-wm_3 -wmp_4-s_2222948684.png "title=" transcoding. png "alt=" wkiom1esacva6dnyaamp8avb0cs616.png-wh_50 "/>

Import Sysprint (sys.getdefaultencoding ()) #显示字符编码a_unicode = "The End of the Wind yuqingping" #这个是unicode格式print (a_unicode) A_gbk=a_ Unicode.encode (' GBK ') #默认是unicode格式, converted to GBK format print (A_GBK) a_gb2312=a_gbk.decode (' GBK '). Encode (' gb2312 ') # First decode converted to Unicode format, the parentheses tell themselves to be GBK format, and then encode conversion, in parentheses to write the format to be converted. Print (a_gb2312) #gbk是gb2312升级版, the encoding of commonly used Chinese characters is basically the same a_unicode2=a_gbk.decode (' GBK ') #转化为unicode格式print (A_UNICODE2)
9.DAY3 file operation seek tell modifies the open file mode:
    • R, read-only mode "default"

    • W, write-only mode "unreadable; not exist" create; Delete content; "

    • A, append mode is "unreadable, not present", and only append content;

"+" reads and writes a file at the same time:
    • r+, can read and write files. "Readable; can be appended"

    • w+, write and read

    • A +, Additional Reading

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading
    • RU

    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)
    • Rb

    • Wb

    • Ab

The difference between 1.read (), ReadLine (), ReadLines ()
#!/usr/bin/env python#-*-coding:utf-8-*-# author:dcc## #默认读取模式file = open ("Test_file", "R", encoding= "Utf-8") # The file handle print (File.read ()) data = File.read () #所有内容data1 = File.read () #第二次读, is the File.seek (0) #将光标归零data2 = File.read () that does not read the data #光 After the mark is zero, the data can be read out again File.close ()
#!/usr/bin/env python#-*- coding:utf-8 -*-# author :D Ccfile = open ("Test_file", "R", encoding= "Utf-8")   #文件句柄print (File.read ())   #读出全部file. Seek (0 ) Print (File.readline ())   #读出一行file. Seek (0) print (File.readlines ())   #把文章内容以换行符分割, and generate the list format C:\Users\ congcong.du\appdata\local\programs\python\python35\python.exe c:/users/congcong.du/pycharmprojects/test/ Day3/file.py1 If you really love me   let me go 2 distressed you said that 3 if you really love me   let me go 4 I'm determined not from the dreams   Break Free 5 If you really love me   Let me go away 6 distressed you hid the bitterness of separation for me 7 if I know you are so sad 8 will a person go to lonely 1 if you really love me   let me go away [' 1 if you really love me   let Me Go ',  ' 2 distressed you say ',  ' 3 If you really love me   let me go \,  ' 4 I am determined not to break from the dream  ,  ' 5 If you really love me   let me go away \,  ' 6 distressed you hid the bitterness of separation for me \ ',  ' 7 If I know you are so sad \,  ' 8 will be a person to lonely '] 
File = Open ("Test_file", "R", encoding= "Utf-8") #文件句柄for I in range (5): Print (File.readline ()) #读出前五行 File.close ()
For line in File.readlines (): #转化为列表格式了 print (Line.strip ())
#!/usr/bin/env python#-*- coding:utf-8 -*-# author :D Ccfile = open ("Test_file", "R", encoding= "Utf-8")   #文件句柄 # Read all the files into memory for index,line in  enumerate (File.readlines ()):  #读列表和下标     if index == 9:         print ("-----------------")          continue  print (Line.strip ())      "     #这个效率最高, for  line in file, progressive read to memory "' count = 0for line in file:     if count == 9:        print ("-------------------- ")     count += 1    continue  print (line)      count += 1 ' 
#!/usr/bin/env python#-*- coding:utf-8 -*-# author :D cc# #默认读取模式file  = open ("Test_file", "R", encoding= "Utf-8")   #文件句柄print (File.tell ())  # Print cursor current position print (File.readline ()) print (File.readline ()) print (File.readline ()) print (File.tell ()) File.seek (0)    #移动归零print (File.tell ()) file.flush  #刷新, write from memory to disk File.close () C:\Users\congcong.du\AppData\Local\ Programs\python\python35\python.exe c:/users/congcong.du/pycharmprojects/test/day3/file.py01 If you really love me   Let me go away 2 distressed you say that 3 if you really love me   let me walk away 1100 
#!/usr/bin/env python#-*- coding:utf-8 -*-# author :D cc# Modify Ideas: Open a file, from the old file, read one line to write a line, change one line, write a line F = open ("Test_file", "R", encoding= "Utf-8") F_new = open ("Test_file.bak", "W", encoding= "Utf-8") for line in f:         if  "Distressed"  in line:      line = line.replace ("distressed", " Xinteng ")            print (line)      F_new.write (line) F.close () f_new.close () 
#with #python Line does not exceed 80 characters, with newline with open ("Yesterday", "R", encoding= "Utf-8") as F,open ("Yesterday2", "R", encoding= "Utf-8 ") as F2:for line in F:print (line) for line2 in F2:print (line2)


This article from "Dongfeng Ten Li Tenderness" blog, declined reproduced!

Python,day3-python Foundation 3

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.