This is the 12th day of my participation in Gwen Challenge


First, the introduction of functions

The so-called function is to organize the code block with independent function into a small module, which can be called when needed

Using a function involves two steps:

  1. Define functions – Encapsulate individual functions
  2. Call functions – enjoy the fruits of encapsulation

What functions do: When developing programs, using functions improves writing efficiency and code reuse


Two, the basic use of functions

2.1 Definition of functions

Define the function in the following format:

defThe function name () :Function wrapped code...Copy the code


  1. defIs EnglishdefineThe abbreviation of
  2. The function name should express how the function encapsulates the code and facilitate subsequent calls
  3. The name of the functionShould be namedConform to the Naming rules for identifiers
    • It can contain letters, underscores, and digits
    • You can’t start with a number


2.2 Function Call

Calling a function is very simple, by function name () to complete the call to the function


2.3 The first function walkthrough

demand

  • Write a Hellosay_helloEncapsulate three lines of greeting code
  • Call the greeting code below the function
#! /usr/bin/python3
# -*- coding:utf-8 -*-

name = "hui"

The interpreter knows that a function is defined here
def say_hello() :
    print("hello 1")
    print("hello 2")
    print("hello 3")

print(name)

say_hello()

print(name)
Copy the code


The running results are as follows:

hui
hello 1
hello 2
hello 3
hui
Copy the code


The previously defined function is executed only when the function is called

After the function completes execution, it goes back to the previous program and continues to execute the subsequent code


Once a function is defined, it simply means that the function encapsulates a piece of code

If a function is not actively called, it will not be actively executed


Q: Can a function call be placed above the function definition?

A:

  • Can’t!
  • Because in theUsing function namesBefore you call a function, you have to be surePythonWe already know that functions exist
  • Otherwise the console will promptNameError: name 'say_hello' is not defined (Name error: the name say_hello is not defined)


2.4 PyCharm debugging tool

  • To start debugging, right-click the Python file and select Debug from the menu item that pops up, or click the green bug in the upper right corner.

  • F8 Step Over can Step through code, treating function calls as if they were a line of code

  • F7 Step Into can Step through code and, if it is a function, inside it



2.5 Documentation comments for functions

  • In development, if you want to comment a function, you should use three consecutive pairs of quotation marks below the defined function
  • Write a description of the function between three consecutive pairs of quotation marks
  • inA function callLocation, use shortcut keysCTRL + QYou can view the description of the function



Note: Because the function body is relatively independent, you should leave two blank lines above the function definition and the rest of the code (including comments)


3. Parameters of a function

Drills demand

  1. To develop asum_2_numThe function of
  2. Function can realize the sum function of two numbers

The drill code is as follows:

#! /usr/bin/python3
# -*- coding:utf-8 -*-

def sum_2_num() :

    num1 = 10
    num2 = 20
    result = num1 + num2

    print("%d + %d = %d" % (num1, num2, result))

sum_2_num()  # 10 + 20 = 30

Copy the code


Think about what the problem is

Functions can only add fixed values

How to solve it?

  • It would be nice if we could pass the number we need to calculate inside the function when we call it!


3.1 Use of function parameters

  • Fill in the parameters inside the parentheses following the function name
  • Use between multiple parameters.separated
#! /usr/bin/python3
# -*- coding:utf-8 -*-

def sum_2_num(num1, num2) :

    result = num1 + num2
    
    print("%d + %d = %d" % (num1, num2, result))

sum_2_num(50.20)  # 50 + 20 = 70

Copy the code


3.2 Functions of Parameters

Function, which organizes blocks of code with independent functions into small modules that can be called as needed

Function parameters, increase the versatility of the function, for the same data processing logic, can adapt to more data

  1. Inside the function, the parameters are used as variables for the required data processing
  2. When a function is called, the data that you want to process inside the function is passed through the parameters in the order defined by the function


3.3 Parameters and arguments

Parameter: When defining a function, the arguments in parentheses are used to receive arguments and are used as variables inside the function

Arguments: Arguments in parentheses used to pass data inside a function when it is called



The return value of the function

  • Sometimes, in program development, you want to tell the caller a result after a function is executed, so that the caller can do something about the result
  • The return value is the last result given to the caller after the function has finished its work
  • Used in functionsreturnKeywords can return results
  • On the calling side of the function, variables can be used to receive the return result of the function

Note: return means return, and subsequent code is not executed


#! /usr/bin/python3
# -*- coding:utf-8 -*-

def sum_2_num(num1, num2) :
    """ sum of two numbers """

    return num1 + num2

Call the function and use the result variable to receive the computed result
result = sum_2_num(10.20)

print("Calculated %d" % result)	# 30

Copy the code


5. Nested calls to functions

  • A nested call is a function that calls another function within a function
  • If the functiontest2In, another function is calledtest1
    • So execute to calltest1Delta function, I’m going to put delta function firsttest1All tasks in the
    • Will return totest2Call a function intest1To proceed with the subsequent code
#! /usr/bin/python3
# -*- coding:utf-8 -*-

def test1() :

    print("*" * 50)
    print("test 1")
    print("*" * 50)


def test2() :

    print("-" * 50)
    print("test 2")
    
    test1()
    
    print("-" * 50)

test2()

Copy the code


The running results are as follows:

--------------------------------------------------
test 2
**************************************************
test 1* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --Copy the code


Print divider

Understand that the demands at work are fluid

Demand for 1

  • To define aprint_lineFunction can print*Consisting of aA dividing line
def print_line(char) :

    print("*" * 50)

Copy the code


Demand for 2

  • Defines a function that can print a separator line consisting of arbitrary characters
def print_line(char) :

    print(char * 50)
    
Copy the code


Demand for 3

  • Defines a function that can print a separator line any number of repetitions
def print_line(char, times) :
    """ "param char: param times: number of characters
    print(char * times)

Copy the code


Demand for 4

  • Define a function that prints n lines of separators that meet requirement 3

In view of the changes in the work requirements, we should think calmly, and do not easily modify the functions that have been completed before and can be executed normally!

def print_line(char, times) :
	""" "param char: param times: number of characters
    print(char * times)


def print_lines(char, times, row) :
    """ "Param char: param times: number of characters :param row: number of specified lines """

    line = 0

    while line < row:
        print_line(char, times)

        line += 1

        
# function call
print_lines(char='- * -, times=20, row=2)
print('Test splitter')
print_lines(char='- * -, times=20, row=2)        
Copy the code


The running results are as follows:

- * - * - * * - * - * - * - * - * - * - * - * - * - * - * - * - * * - * - * - - * - * - * * - * - * - * - * - * - * - * - * - * - * - * - * - * * - * - * - test line - * - * - * * - * - * - * - * - * - * - * - * - * - * - * - * - * * - * - * - - * - * - * * - * - * - * - * - * - * - * - * - * - * - * - * - * * - * - * -Copy the code


The tail language

✍ Code writes the world and makes life more interesting. ❤ ️

✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️

✍ code word is not easy, but also hope you heroes support. ❤ ️