Python knowledge points (6) Custom functions

1. Function

Definition: A piece of code that can complete a certain function.

Use functions: You can call a function through its name, allowing the computer to complete a certain function.

Example: Input two numbers and output the largest number between the two numbers.

a=int(input())
b=int(input())
c=max(a,b)
print(c)

分析:max()函数
功能:返回给定参数的最大值,参数可以为序列。
语法:max(x, y, z, ....)   #参数可以有若干个

Classification:

System functions: a series of programmed programs provided to users

Custom function: a program written by the user according to his or her own needs

System function

System functions provided by the current python version:

Official document query:https://docs.python.org/3.7/library/functions.html

Built-in Functions

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

you()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

word()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

only()

property()

type()

chr()

frozenset()

list()

range()

whose()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

A summary of commonly used functions among the above system functions:

1. Input and output:

input()

print()

2. Data types and conversion:

int()、float()、complex()、bool()、str()

ord()——returns the ASCII code value of the character

chr()——Returns the character corresponding to the ASCII code value

3. Mathematical operations:

abs()——returns the absolute value

round(a,2)——retain a to 2 decimal places

pow(a,b)——Returns a raised to the power b

sum()、max()、min()

divmod(a,b)——Returns the quotient and remainder of a divided by b

bin(a)——Convert decimal number a to binary number (binary)

oct (a) - Convert decimal number a to octal number (octal)

hex(a)——Convert decimal number a to hexadecimal number (hexadecimal),

Complement: int() Other usages: int ("11", 2) - Convert the binary number 11 to a decimal number. The first parameter must be in string form

4. Sequence (list, tuple, set, etc.) related:

list() - Convert an object into a list

tuple() – Convert an object into a tuple

set() - creates an unordered set of non-repeating elements

dict() – Create a new dictionary

range() – creates a list of integers

len() - returns the number of elements in an object

sorted()——sort

reversed() - reverse the sequence

map() - maps the execution sequence according to the provided function

slice() – slice of list

5. File operation related:

open() - open a file

6.Others

help() - used to view a description of the purpose of a function or module

Custom function:

Written by users themselves: written according to their own requirements

Module: a series of function collections with similar functions (the third party has compiled and released it, and we can directly import it and use it)

Written by the user himself:

Basic format:

def 函数名(参数):
  语句或语句组  #函数体,函数完成某功能的代码
  return 返回值
其中参数用来向函数传递值,当有多个参数时,各参数之间用逗号隔开。函数执行完成后,由return语句将表达式的值返回给调用者,结束函数。
函数调用格式:函数名(参数)

Code analysis:

例1:
def cf():
    print("中国")

#主程序
cf()

运行结果:
中国

分析:代码从主程序开始运行,遇到不认识的函数向前找,执行自定义函数。(函数名和函数体不能省)

例2:
def cf(n):   #n是一个形参
    for i in range(n):  #功能:输出n遍中国
        print("中国")   
#主程序
cf(3)   #3是实参
运行结果:
中国
中国
中国

分析:代码从主程序开始运行,遇到不认识的函数向前找,将实参3的值传递给形参n,再执行函数体语句。

例3:
def lj(n):
    s=0
    for i in range(1,n+1):
        s=s+i
    return s

a=lj(10)
print(a)

运行结果:
55

分析:从主程序开始执行,将实参10的值传递给形参n,执行函数体语句,将结果s返回到调用函数即lj(10)的地方,再赋值给变量a。如果没有return s ,lj(10)这个地方则没有值,也就无法赋值或进行算术运算

Module import:

1. Import the entire module

import 模块名
举例:import math
使用math模块中的函数仍然需要指明模块名
模块名.函数名()
举例:math.sqrt(9)——求出9的平方根

import 模块名 as 昵称
举例:import math as m

2. Import a function in the module

from 模块名 import 函数名
举例:from math import sqrt
使用math模块中sqrt()函数无需指明模块名
sqrt(9)——求出9的平方根

3. Import all functions in the module

from 模块名 import *
举例:from math import *
使用math模块中sqrt()函数无需指明模块名
sqrt(9)——求出9的平方根

Common module arrangement:

numpy module:Scientific computing package, including many mathematical functions, such as trigonometric functions, matrix calculation methods, etc.

numpy.arange(0,101,2) generates an arithmetic sequence (can be a decimal sequence)

pi: Numeric constant, pi

numpy.sin(x) finds the sine of x, x must be in radians

matplotlib module:Plotting library in python

matplotlib.plot(x,y) connects the coordinate points corresponding to the (x, y) list

matplotlib.title('sin(x)') creates the title of the coordinate system

matplotlib.xlabel('x') creates the x-axis title

matplotlib.ylabel('y') creates the y-axis title

matplotlib.show() displays the connected function image

tkinter model:GUIopen model
tkinter.Tk() creates a window
tkinter.StringVar() provides some text variables that can be bound to components and their values ​​can be set
random module
random.random() generates a random floating point number, ranging from 0.0 to 1.0.
random.randint() randomly generates an integer type int, and you can specify the range of this integer

math module

ceil: Take the smallest integer value greater than or equal to x. If x is an integer, return x
cos: Find the cosine of x, x must be radians
factorial: Take the value of the factorial of x
pi: digital constant, pi
sqrt: Find the square root of x
log2: Returns the base 2 logarithm of x
fabs: returns the absolute value of x


 

Guess you like

Origin blog.csdn.net/qq_28782419/article/details/127615770