[Learn python from zero] 26. Application of function parameters and return values

Function parameters (1)

Think about a question as follows:

Now we need to define a function that can complete the addition of two numbers and print out the result. How should we design it? Is the code below ok? Are there any flaws?

def add2num():
  a = 11
  b = 22
  c = a+b
  print(c)

In order to make a function more general, that is, let it calculate the sum of the two numbers that you want it to calculate. When defining the function, you can let the function receive data, which solves this problem. This is the function parameters

1. Define and call a function with parameters

Define a add2num(a, b) function to calculate the sum of any two numbers:

def add2num(a, b):
    c = a+b
    print(c)

add2num(11, 22) # 调用带有参数的函数时,需要在小括号中,传递数据

important point:

  • When defining a function, write the name of the variable waiting to be assigned in parentheses
  • When calling the function, write the actual data to be calculated in parentheses

Call the run procedure with a parameter function:

Second, practice

Requirements: Define a function to complete the addition of the first two numbers, and then subtract the third number; then call this function

When using def to define a function, pay attention to the fact that there are 3 parameters
. When calling, this function has several parameters when it is defined, so you need to pass several parameters

3. The order of parameters when calling a function

def test(a,b):
    print(a,b)

test(1,2)  # 位置参数
test(b=1,a=2)  # 关键字参数
test(b=1,2)  # 关键字参数写在位置参数之前会导致出错

4. Summary

  • Parameters in parentheses when defined are used to receive parameters and are called "formal parameters"
  • The parameters in parentheses when calling are used to pass to the function, called "actual parameters"

Function return value (1)

1. Introduction to "return value"
Scenarios in real life:

I gave my son 10 yuan to buy me an ice cream. In this example, I gave 10 yuan to my son, which is equivalent to passing the parameter when calling the function. The ultimate goal of letting my son buy ice cream is that I need to let him bring the ice cream back. At this time, the ice cream is the return value.

Scenario in development:

A function is defined, and the indoor temperature is obtained. Think about whether this result should be given to the caller. Only when the caller has this return value can the appropriate adjustment be made according to the current temperature.

In summary:

The so-called "return value" is the final result to the caller after the function in the program completes one thing. The
prerequisite for using the return value is that the function caller wants to use the calculation result outside the function.

2. Functions with return values

If you want to return the result to the caller in the function, you need to use return in the function

For example:

def add2num(a, b):
    c = a+b
    return c  # return 后可以写变量名

或者

def add2num(a, b):
    return a+b  # return 后可以写计算表达式

3. Save the return value of the function

At the beginning of this section, in the example of "buying ice cream" mentioned above, when your son gave you ice cream at the end, you must have taken it from your son, right? The same is true for programs. If a function returns a piece of data, then If you want to use this data, you need to save

An example of the return value of the save function is as follows:

#定义函数
def add2num(a, b):
    return a+b

#调用函数,顺便保存函数的返回值
result = add2num(100,98)

#因为result已经保存了add2num的返回值,所以接下来就可以使用了
print(result)

result:

198

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132291153