Python's Path function basics

Source: Internet
Author: User

What is the basic definition 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(a,b) #结果赋值给c变量print(c)

Parameters can make your function more flexible, not only to do the dead, but also to determine the execution flow within the function according to the different call Shishun.

function parameters

Shape parametric

The memory unit is allocated only when it is called, and the allocated memory unit is freed 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

Actual parameters

Can be constants, variables, expressions, functions, and so on, regardless of the amount of the arguments, they must have a definite value when making a function call 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

Default parameters

Look at the following code

def stu_register(name,age,country,course):    print("----注册学生信息------")    print("姓名:",name)    print("age:",age)    print("国籍:",country)    print("课程:",course)stu_register("王山炮",22,"CN","python_devops")stu_register("张叫春",21,"CN","linux")stu_register("刘老根",25,"CN","linux")

Found country This parameter is basically "CN", just like we registered users on the site, such as the nationality of this information, you do not fill in, the default will be China, which is implemented by default parameters, the country into the default parameters is very simple

def stu_register(name,age,course,country="CN"):

Thus, this parameter is not specified at the time of invocation, and the default is CN, specified by the value you specify.

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

Key parameters

Under normal circumstances, to the function parameters to order, do not want to order the key parameters can be used, just specify the parameter name (parameter name parameters are called key parameters), but remember a requirement is that the key parameters must be placed in the positional parameters (in order to determine the corresponding relationship parameters) after

def stu_register(name, age, course=‘PY‘ ,country=‘CN‘):    print("----注册学生信息------")    print("姓名:", name)    print("age:", age)    print("国籍:", country)    print("课程:", course)

Call can do this

stu_register("王山炮",course=‘PY‘, age=22,country=‘JP‘ )

But it's never going to happen.

stu_register("王山炮",course=‘PY‘,22,country=‘JP‘ )

Of course that's not true.

stu_register("王山炮",22,age=25,country=‘JP‘ )

This is equivalent to 2 times the age assignment, will be an error!

Non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

def stu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式    print(name,age,args)stu_register("Alex",22)#输出#Alex 22 () #后面这个()就是args,只是因为没传值,所以为空stu_register("Jack",32,"CN","Python")#输出# Jack 32 (‘CN‘, ‘Python‘)

can also have a **kwargs

def stu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式    print(name,age,args,kwargs)stu_register("Alex",22)#输出#Alex 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")#输出# Jack 32 (‘CN‘, ‘Python‘) {‘province‘: ‘ShanDong‘, ‘sex‘: ‘Male‘}
return value

Code outside the function to get the execution result of the function, you can return the result in the function with a return statement

def stu_register(name, age, course=‘PY‘ ,country=‘CN‘):    print("----注册学生信息------")    print("姓名:", name)    print("age:", age)    print("国籍:", country)    print("课程:", course)    if age > 22:        return False    else:        return Trueregistriation_status = stu_register("王山炮",22,course="PY全栈开发",country=‘JP‘)if registriation_status:    print("注册成功")else:    print("too old to be a student.")

Attention

    • The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
    • If return is not specified in the function, the return value of this function is None
Global vs. local variables
name = "Alex Li"def change_name(name):    print("before change:",name)    name = "金角大王,一个有Tesla的男人"    print("after change", name)change_name(name)print("在外面看看name改了么?",name)

Output

before change: Alex Liafter change 金角大王,一个有Tesla的男人在外面看看name改了么? Alex Li

You can call the outside variable in the function without passing the name value into the function.

name = "Alex Li"def change_name():    name = "金角大王,一个有Tesla的男人"    print("after change", name)change_name()print("在外面看看name改了么?", name)

But just can't change!

    • A variable defined in a function is called a local variable, and a variable defined at the beginning of the program is called a global variable.
    • A global variable scope is the entire program, and the local variable scope is the function that defines the variable.
    • When a global variable has the same name as a local variable, the local variable functions within the function that defines the local variable, and in other places the global variable works.
Scope

Scope (scope), the concept of programming, generally speaking, the name used in a program code is not always valid/available, and the scope of the code that qualifies the name's availability is the scope of the name.

It's not a good place to go, LEGB rule later.

How do I modify a global variable in a function?
name = "Alex Li"def change_name():    global name    name = "Alex 又名 金角大王,路飞学城讲师"    print("after change", name)change_name()print("在外面看看name改了么?", name)

global nameis to declare the global variable name in the function, which means that the topmost print name = "Alex Li" , even if it is not written, prints the name at the back of the program.

Nested functions
name = "Alex"def change_name():    name = "Alex2"    def change_name2():        name = "Alex3"        print("第3层打印", name)    change_name2()  # 调用内层函数    print("第2层打印", name)change_name()print("最外层打印", name)

Output

第3层打印 Alex3第2层打印 Alex2最外层打印 Alex

At this point, what happens when you call Change_name2 () at the outermost layer?

Yes, it went wrong, why?

The use of nested functions will be, but what's the use of it? The next lesson is announced ...

anonymous functions

Anonymous functions simply do not require explicit function names.

#这段代码def calc(x,y):    return x**yprint(calc(2,5))#换成匿名函数calc = lambda x,y:x**yprint(calc(2,5))

You may say that it is not convenient to use this thing. Oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows

res = map(lambda x:x**2,[1,5,7,4,8])for i in res:    print(i)

Output

125491664
Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

def add(x,y,f):    return f(x) + f(y)res = add(3,-6,abs)print(res)

Only one of the following conditions is required, which is the higher order function

    • Accept one or more functions as input
    • Return returns a different function
Recursive

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

def calc(n):    print(n)    if int(n/2) ==0:        return n    return calc(int(n/2))calc(10)

Output

10521

To see the implementation process, I changed the code

def calc(n):    v = int(n/2)    print(v)    if v > 0:        calc(v)    print(n)calc(10)

Output

521012510

Why does the output result be like this?

Recursive properties:

    1. Must have a definite end condition
    2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
    3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Stack Literacy http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html

What's the use of recursion? There are many uses, today we will talk about a

Recursive function Practical application case, two-point search

data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]def binary_search(dataset,find_num):    print(dataset)    if len(dataset) >1:        mid = int(len(dataset)/2)        if dataset[mid] == find_num:  #find it            print("找到数字",dataset[mid])        elif dataset[mid] > find_num :# 找的数在mid左面            print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])            return binary_search(dataset[0:mid], find_num)        else:# 找的数在mid右面            print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])            return binary_search(dataset[mid+1:],find_num)    else:        if dataset[0] == find_num:  #find it            print("找到数字啦",dataset[0])        else:            print("没的分了,要找的数字[%s]不在列表里" % find_num)binary_search(data,66)
Built-in functions

Python len Why can you use it directly? It must have been defined at the start of the interpreter.

Built-in Parameter details Https://docs.python.org/3/library/functions.html?highlight=built#ascii

Several tricky built-in method usage reminders

#compilef = open("函数递归.py")data =compile(f.read(),‘‘,‘exec‘)exec(data)#printmsg = "又回到最初的起点"f = open("tofile","w")print(msg,"记忆中你青涩的脸",sep="|",end="",file=f)# #slice# a = range(20)# pattern = slice(3,8,2)# for i in a[pattern]: #等于a[3:8:2]#     print(i)###memoryview#usage:#>>> memoryview(b‘abcd‘)#<memory at 0x104069648>#在进行切片并赋值数据时,不需要重新copy原列表数据,可以直接映射原数据内存,import timefor n in (100000, 200000, 300000, 400000):    data = b‘x‘*n    start = time.time()    b = data    while b:        b = b[1:]    print(‘bytes‘, n, time.time()-start)for n in (100000, 200000, 300000, 400000):    data = b‘x‘*n    start = time.time()    b = memoryview(data)    while b:        b = b[1:]    print(‘memoryview‘, n, time.time()-start)几个内置方法用法提醒
Exercises

Modify your personal Information program

To store personal information of more than one person in a file, such as the following

username password  age position department alex     abc123    24   Engineer   ITrain     [email protected]    25   Teacher   Teching....

1. Enter username and password, correct login system, print

1. 修改个人信息2. 打印个人信息3. 修改密码

2. Write a method for each option

3. Error 3 exit procedure during login

Answers to the exercises

def print_personal_info (account_dic,username): "" "Print user info:p Aram account_dic:all account ' s data:p Aram Username:username:return:None "" "Person_data = Account_dic[username] info =" '-----------------          -Name:%s Age:%s Job:%s Dept:%s Phone:%s------------------"% (Person_data[1], PERSON_DATA[2], person_data[3], person_data[4], person_data[5], print (info) def save_back_to_file (account_dic): "" "Turn account dic into string format, write back to file:p Aram Account_dic:: Return:" "" "F . Seek (0) #回到文件头 f.truncate () #清空原文件 for k in account_dic:row = ",". Join (Account_dic[k]) f.write ("%s\n "%row" F.flush () def change_personal_info (account_dic,username): "" "Change user info, thinking as follows 1. The person to print out each of the information, let it choose which field to change, the user chose the number, exactly the index of the field, so that the field directly to find out to get rid of 2. After the change, but also to re-write this new data back to Account.txt, because the new data after the change is dict type, but also need to turn dict into a string, and then write back to the hard disk:p Aram Account_dic:allAccount ' s data:p Aram Username:username:return:None "" "Person_data = Account_dic[username] Print (" per Son data: ", person_data) column_names = [' Username ', ' Password ', ' Name ', ' age ', ' Job ', ' Dept ', ' Phone '] for index,k in enum  Erate (person_data): If index >1: #0 is username and 1 is password print ("%s. %s:%s "% (index, column_names[index],k)) choice = input (" [Select Column ID to change]: "). Strip () if Choice.isdigi T (): choice = Int (choice) If Choice > 0 and Choice < Len (person_data): #index不能超出列表长度边界 col Umn_data = Person_data[choice] #拿到要修改的数据 print ("Current value>:", column_data) New_val = input ("NE W Value>: "). Strip () if New_val: #不为空 person_data[choice] = new_val print (person _data) Save_back_to_file (account_dic) #改完写回文件 else:print ("Cannot be empty ... ") Account_file =" Account.txt "f = open (Account_file," r+ ") raw_dATA = F.readlines () accounts = {} #把账户数据从文件里读书来, turns into dict, so it's good to query for line in Raw_data:line = Line.strip () if not line . StartsWith ("#"): Items = Line.split (",") accounts[items[0]] = Itemsmenu = "' 1. Print personal Information 2. Modify personal Information 3.  Change Password ' count = 0while count <3:username = input ("username:"). Strip () Password = input ("Password:"). Strip () if Username in accounts:if password = = accounts[username][1]: # print ("Welcome%s". Center (+, '-')% user Name) while True: #使用户可以一直停留在这一层 print (menu) User_choice = input (">>>") . Strip () if User_choice.isdigit (): user_choice = Int (user_choice) if                        User_choice = = 1:print_personal_info (accounts,username) elif User_choice = = 2:                    Change_personal_info (accounts,username) elif User_choice = = ' Q ':        Exit ("Bye.")        Else    Print ("Wrong username or password!")    Else:print ("Username does not exist.") Count + = 1else:print ("Too many attempts.")

Python's Path function basics

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.