Level 1: Parameters of Functions - Bricks to Build Function Houses
mission details
When we need to perform the same type of task multiple times in the program, we don't need to repeatedly write code segments to complete the task, but can use function tools to greatly facilitate our programming work. Functions are reusable pieces of code used to implement associated functionality.
The goal of this training is to let readers understand and master the relevant knowledge of the function structure, and the small goal of this level is to let the readers first understand and master the relevant knowledge of function parameters.
related information
Before we use a function, we must first define a function that meets our own requirements. The basic structure for defining a function is:
def functionname( parameters ):
"函数_文档字符串"
function_suite
return [expression]
- The definition function
def
starts with a keyword, followed by the function name, parentheses()
, parameters in parentheses, and a colon; - Then, write the function body in the indented block. The first line of the function is usually written as a document string, which is used to store the function description, or you can choose not to write it;
Return[expression]
Indicates the end function and returns a value. Without an expressionreturn
is equivalent to returning a null value.
The focus of this level is to study the parameters of the function parameters
. When defining a function, the names and positions of the parameters are determined, and the interface definition of the function is also completed. When we call a function, we only need to know what parameters to pass. The internal operation of the function has been encapsulated, and the user does not need to understand it.
Python
The function parameters mainly include the following:
- Required parameters;
- Default parameters;
- variable parameter;
- keyword arguments.
required parameter
Mandatory parameters are also called positional parameters, which are the most commonly used parameters in functions. Mandatory parameters are parameters that must be specified when calling a function, for example:
#定义加法函数plus,参数a,b就是必选参数
def plus(a,b):
c=a+b
return(c)
#调用函数plus时,必须给参数a,b传递值
d=plus(1,2)
#输出结果d
print(d)
Output result:
3
If plus
the parameters passed in do not meet the requirements when calling the function, for example:
>>d = plus()
TypeError: plus() missing 2 required positional arguments: 'a' and 'b'
>>d = plus(1)
TypeError: plus() missing 1 required positional argument: 'b'
default parameters
A default parameter refers to providing a default value for a function parameter. If no value is passed to the parameter when the function is called, the parameter uses the default value. For example:
#定义加法函数plus,参数a是必选参数,参数b是默认值2的参数
def plus(a,b=2):
c=a+b
return(c)
#调用函数plus时,必须给参数a传递值,若不给b传递值,则b默认为2
d=plus(1)
#输出结果d
print(d)
As can be seen from the above example, there is no need to pass parameter values to default parameters during function calls. But when using default parameters, there are two points to note:
- Default parameters should be placed after all required parameters;
- Default arguments must point to immutable objects.
variable parameter
In some cases, when we define a function, we cannot determine how many parameters the function should contain. At this time, we can use variable parameters, which means that the number of parameters passed in is variable. For example:
#定义plus函数,完成的功能是返回输入的整数之和。
# 参数numbers是可变参数,表示输入的参数个数可以为任意值
def plus(*numbers):
add = 0
for i in numbers:
add += i
return(add)
#调用3次plus函数,每次的参数个数都不相同
d1 = plus(1,2,3)
d2 = plus(1,2,3,4)
d3 = plus(1,3,5,7,9)
#向函数中可以传递任意参数,包括0个参数
d4 = plus()
#输出结果
print(d1)
print(d2)
print(d3)
print(d4)
Output result:
6
10
25
0
In the above example, numbers
it is a variable parameter, and an identifier is added in front of the variable parameter *
. Inside the function, numbers
the value received by the variable parameter is one tuple
.
When we call a function whose parameters are variable parameters, we can pass any number of parameters to the function, including 0
parameters.
keyword arguments
Variable parameters allow us to pass in any number of parameters when calling a function, and these variable parameters are automatically assembled into one when the function is called tuple
.
The keyword parameters allow us to pass in any number of parameters with parameter names, and these keyword parameters are automatically assembled into one when the function is called dict
. That is, keyword arguments pass key-value pairs of any length, as arguments, to functions.
#定义一个包含关键字参数的函数,返回值为参数值
def plus(**kw):
return kw
#调用plus函数,参数值为空
d1 = plus()
#调用plus函数,参数值为x=1
d2 = plus(x=1)
#调用plus函数,参数值为x=1,y=2
d3 = plus(x=1, y=2)
#输出d1,d2,d3
print(d1)
print(d2)
print(d3)
Output result:
{}
{'x': 1}
{'x': 1, 'y': 2}
In the above example, kw
it is a keyword parameter, and two *
words are added in front of the keyword parameter. The keyword parameter can expand the function of the function and make the process of passing parameters easier, for example:
#定义一个plus函数,有3个参数,返回值是3个参数之和
def plus(x,y,z):
return x+y+z
#有一个dict列表,当中3个键的值分别为1,2,3
dict = {'x':1, 'y':2, 'z':3}
#将dict列表中的3个值传入plus函数中,得到返回值d
d = plus(dict['x'],dict['y'],dict['z'])
#输出d
print(d)
Output result:
6
But in the above example, plus
the method of passing parameters from the value in the dictionary to the function is too cumbersome, and the method of keyword parameters can be adopted. For example:
#定义一个plus函数,有3个参数,返回值是3个参数之和
def plus(x,y,z):
return x+y+z
#有一个dict列表,当中3个键的值分别为1,2,3
dict = {'x':1, 'y':2, 'z':3}
#用关键字参数的方法将dict列表中的3个值传入plus函数中,得到返回值d
d = plus(**dict)
#输出d
print(d)
Output result:
6
The method of using keyword parameters **dict
can greatly improve the efficiency of parameter passing.
parameter combination
In the process of function definition, we can use one or more of mandatory parameters, default parameters, variable parameters, and keyword parameters at the same time. However, it is important to note that these four parameters are in order during use, and the order should be mandatory parameters, default parameters, variable parameters, and keyword parameters.
For example:
#定义一个包含必选参数、默认参数、可变参数和关键字参数的函数plus
def plus(x, y, z=0, *args, **kw):
print('x=',x)
print('y=',y)
print('z=',z)
print('args=',args)
print('kw=',kw)
#调用函数plus,输入两个参数1,2
plus(1,2)
Output result:
x= 1
y= 2
z= 0
args= ()
kw= {}
In the above example , plus
two mandatory parameters 1
and are passed into the function 2
. The mandatory parameters must provide values, but the default parameters, variable parameters and keyword parameters do not need to provide values.
We can also pass values to default parameters, variadic parameters and keyword parameters, for example:
定义一个包含必选参数、默认参数、可变参数和关键字参数的函数plus
def plus(x, y, z=0, *args, **kw):
print('x=',x)
print('y=',y)
print('z=',z)
print('args=',args)
print('kw=',kw)
#调用函数plus,输入参数x=1,y=2,z=3,args=(4,5,6),kw={}
plus(1,2,3,4,5,6)
print('\n')
#调用函数plus,输入参数x=1,y=2,z=3,args=(4,5,6),kw={'k':7, 'm':8}
plus(1,2,3,4,5,6,k=7,m=8)
Output result:
x= 1
y= 2
z= 3
args= (4, 5, 6)
kw= {}
x= 1
y= 2
z= 3
args= (4, 5, 6)
kw= {'k': 7, 'm': 8}
summary
- Different types of parameters are ordered, followed by mandatory parameters, default parameters, variable parameters and keyword parameters;
- Default parameters must use immutable objects, and using variable objects is prone to logic errors;
*args
Represents variable parameters and*args
receives a tuple;**kw
Represents keyword arguments and**kw
receives a dictionary.
programming requirements
The programming task of this level is to complete src/Step1/plus.py
the code of the file and realize the corresponding function. Specific requirements are as follows:
- Define a function
plus
, the function is to accumulate the numerical elements in the parameter (a list), and the number of elements in the list is uncertain; - The function returns the accumulated result.
The code framework of the code files involved in this level src/Step1/plus.py
is as follows:
#coding=uft-8
#创建一个空列表numbers
numbers = []
#str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表
str = input()
lst1 = str.split(' ')
#将输入的数字字符串转换为整型并赋值给numbers列表
for i in range(len(lst1)):
numbers.append(int(lst1.pop()))
# 请在此添加函数plus的代码,函数参数为一个列表
#********** Begin *********#
#********** End **********#
d = plus(numbers)
print(d)
Test instruction
The test file of this level is src/Step1/plus.py
, the test process is as follows:
- The platform automatically compiles and generates
plus.exe
; - The platform runs
plus.exe
and provides test input as standard input; - The platform takes
plus.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/Step1/plus.py
a sample test set for a platform pair:
Test Input: 1 2 3 4 5
Expected Output:15
Test Input: 1 3 5 7 9 11
Expected Output:36
Test Input: 2 4 6 8 10 12 14 16
Expected Output:72
Let's start your mission, I wish you success!
Even though I have nothing to do every day, I don't feel a little bit relaxed. Why don't you go exercise
If you think the content of this level is helpful to you, please like it below.
code:
#coding=utf-8
#创建一个空列表numbers
numbers = []
#str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表
str = input()
lst1 = str.split(' ')
#将输入的数字字符串转换为整型并赋值给numbers列表
for i in range(len(lst1)):
numbers.append(int(lst1.pop()))
# 请在此添加函数plus的代码,函数参数为一个列表,对列表中的数值元素进行累加求和
#********** Begin *********#
def plus(numbers):
add=0
for i in numbers:
add+=i
return add
#********** End **********#
#调用plus函数,并将返回结果存储到变量d中
d = plus(numbers)
print(d)
Level 2: The return value of the function - dispensable return
mission details
After the function performs operation processing, the value returned is called the return value. The value returned by the function is return
executed through the statement. The return value allows us to directly get the result of the function processing without having to care about the complex and heavy calculation process inside the function, which greatly improves the programming efficiency.
The main goal of this level is to let readers understand and master the relevant knowledge of function return values.
related information
return
The statement returns the value to the exit of the calling function, and the function must have return
a return value to be a complete function. If we don't define the function return value in the function, then the program will automatically let the function return a result, which is None
an object, and None
the object means that there is no value.
return value as
There is only one return value of a function, but sometimes we find that some functions seem to have multiple return values. In fact, the "multiple" here does not mean multiple return values. For example, a function returns a list containing many element values. This is similar to: only one box can be taken away from the supermarket, but we are allowed to put some things in the box as one thing to take away. For example:
def f():
return 1,'abc','1234'
print(f())
Output result:
(1, 'abc', '1234')
When the function is called f()
, the output of the program is a tuple, so the return value of the function is a value on the surface 3
, but in fact it returns a tuple, which contains three different elements (the tuple syntax does not need to be enclosed in parentheses).
function as return value
In addition to using various types of values as return values, we can also use functions as return values.
For example, we want to define a function to calculate the sum of the numerical elements in the list. Generally, we define it like this:
def plus(*args):
s = 0
for n in args:
s = s + n
return s
However, what if we don't need to sum immediately, but calculate according to the needs in the later program? At this time, the function we define may not return the result of the summation, but return the function of calculating the summation!
So we can also define functions as follows:
def lazy_plus(*args):
def plus():
s = 0
for n in args:
s = s + n
return s
return plus
When we call lazy_plus()
, what is returned is not the result of the sum, but a function that calculates the sum:
#定义求和函数,返回的并不是求和结果,而是计算求和的函数
def lazy_plus(*args):
def plus():
s = 0
for n in args:
s = s + n
return s
return plus
#调用lazy_plus()时,返回的并不是求和结果,而是求和函数
f = lazy_plus(1,2,3,4,5)
print(f)
Output result:
<function lazy_plus.<locals>.plus at 0x000001DAC97F9950>
f
The result of the summation is actually calculated when the function is called :
#定义求和函数,返回的并不是求和结果,而是计算求和的函数
def lazy_plus(*args):
def plus():
s = 0
for n in args:
s = s + n
return s
return plus
#调用函数f时,得到真正求和的结果
f = lazy_plus(1,2,3,4,5)
print(f())
Output result:
15
In the above example, we lazy_plus
defined the function in the function plus
, and the internal function plus
can refer to lazy_plus
the parameters and local variables of the external function. When the function lazy_plus
returns to the function plus
, the relevant parameters and variables will also be saved in the returned function. This method is also called “闭包(Closure)”
.
Summary: In addition to the value calculated by the function as the return value, we can also use the function as the return value.
If you want to know more about list operations, please refer to:
【美】Eric Matthes著《Python编程——从入门到实践》第八章
.
programming requirements
The programming task of this level is to complete src/step2/return.py
the code of the file and realize the corresponding function. Specific requirements are as follows:
- Define a function
gcd
, the function is to find the greatest common divisor of two positive integers;
The code framework of the code files involved in this level src/step2/return.py
is as follows:
#coding=utf-8
#输入两个正整数a,b
a = int(input())
b = int(input())
# 请在此添加函数gcd代码,求两个正整数的最大公约数
#********** Begin *********#
#********** End **********#
#调用函数,并输出最大公约数
print(gcd(a,b))
Test instruction
The test file of this level is src/step2/return.py
, the test process is as follows:
- The platform automatically compiles and generates
return.exe
; - The platform runs
return.exe
and provides test input as standard input; - The platform takes
return.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/step2/return.py
a sample test set for a platform pair:
Test Input: 1
8
Expected Output:1
Test Input: 9
3
Expected Output:3
Test Input: 9
21
Expected Output:3
Test Input: 126
36
Expected Output:18
Let's start your mission, I wish you success!
There is always someone who is better, more handsome, and more self-satisfied than yourself. Accept this reality, but you still want to be the king in your heart.
If you think the content of this level is helpful to you, please like it below.
code:
#coding=utf-8
#输入两个正整数a,b
a = int(input())
b = int(input())
# 请在此添加函数gcd代码,求两个正整数的最大公约数
#********** Begin *********#
def gcd(a,b):
if a<b:
t=a
a=b
b=t
while b:
maxs=a%b
a=b
b=maxs
return a
#********** End **********#
#调用函数,并输出最大公约数
print(gcd(a,b))
Level 3: Scope of use of functions: Python scope
mission details
Functions have a scope of use. In a module, we can define many functions and variables, but we hope that some functions and variables can be used by others, and some functions and variables can only be used inside the module. That's Python
the problem with scope.
The goal of this chapter is to let readers understand and master the scope of use of functions, that is, the Python
relevant knowledge of scope.
related information
In Python
, normal function and variable names are public ( public
) and can be directly referenced, such as: abs()
, abc
, dir()
and so on.
Variables like __xxx__
this format are special variables that are allowed to be referenced directly, but will be used for special purposes, for example __author__
, __name__
are special variables. hello
The documentation comments defined by the module can also be accessed with special variables __doc__
, and the variables defined by our own programming generally do not use such variable names.
Functions and variables similar _xxx
to __xxx
this format are non-public ( private
) and should not be referenced directly.
Supplement: _xxx
The functions and variables are protected
that we directly access from the outside will not generate exceptions. __xxx
For functions and variables private
, we will report an exception when we directly access them from the outside. We should pay attention to the difference in prefix symbols.
We should pay attention to the difference in terms, we say that private
functions and variables "should not" be directly referenced, not "cannot" be directly referenced, this is because there is no Python
way to really completely restrict access to private
functions or variables. variable. But in order to develop good programming habits, we should not refer to private
functions or variables.
private
The function of the function is to hide the internal logic of the function, so that the function has better encapsulation.
For example:
def _private_1(name):
return 'Hello, %s' % name
def _private_2(name):
return 'Hi, %s' % name
def greeting(name):
if len(name) > 3:
return _private_1(name)
else:
return _private_2(name)
We expose greeting()
the function in the above program block, greeting()
the function needs to use _private_1()
and _private_2()
the function, and the reader does not need to know greeting()
the internal implementation details of the function. So we can private
hide the internal logic with functions. This is a very common method of code encapsulation.
Summary: In order to make the encapsulation of the program better, we generally limit the scope of use of functions. Generally, we define functions that need to be used externally as functions, public
and define functions that are only used internally and do not need to be referenced externally as functions private
.
programming requirements
The programming task of this level is to complete src/step3/scope.py
the code of the file and realize the corresponding function. Specific requirements are as follows:
- Write a program whose function is to find the least common multiple of two positive integers;
- Required implementation method: first define a
private
function_gcd()
to find the greatest common divisor of two positive integers, and then definepublic
a functionlcm()
call_gcd()
function to find the least common multiple of two positive integers.
The code framework of the code files involved in this level src/step3/scope.py
is as follows:
#coding=utf-8
#输入两个正整数a,b
a = int(input())
b = int(input())
# 请在此添加一个private函数_gcd()求两个正整数的最大公约数
#********** Begin *********#
#********** End **********#
# 请在此添加一个public函数lcm(),通过调用_gcd()求两个正整数的最小公倍数
#********** Begin *********#
#********** End **********#
#调用函数,并输出a,b的最小公倍数
print(lcm(a,b))
Test instruction
The test file of this level is src/step3/scope.py
, the test process is as follows:
- The platform automatically compiles and generates
scope.exe
; - The platform runs
scope.exe
and provides test input as standard input; - The platform takes
scope.exe
the output and compares its output with the expected output. If it matches, the test passes, otherwise the test fails.
The following is src/step3/scope.py
a sample test set for a platform pair:
Test Input: 5
6
Expected Output:30
Test Input: 8
10
Expected Output:40
Test Input: 16
24
Expected Output:48
Test Input: 132
214
Expected Output:14124
Let's start your mission, I wish you success!
There will be a lot of troubles and difficulties in the journey, we need to endure, but also to solve, Yu Minhong once said: Persevere, not because we are strong enough, but because we have no choice.
If you think the content of this level is helpful to you, please like it below.
code:
#coding=utf-8
#输入两个正整数a,b
a = int(input())
b = int(input())
# 请在此添加一个private函数_gcd()求两个正整数的最大公约数
#********** Begin *********#
def gcd(a,b):
if a<b:
t=a
a=b
b=t
while b:
maxs=a%b
a=b
b=maxs
return a
#********** End **********#
#请在此添加一个public函数lcm(),在lcm()函数中调用_gcd()函数,求两个正整数的最小公倍数
#********** Begin *********#
def lcm(a,b):
return int(a*b/gcd(a,b))
#********** End **********#
#调用函数,并输出a,b的最小公倍数
print(lcm(a,b))
Level 4: Function Comprehensive Training※
mission details
The task of this level: use the knowledge of functions to complete the following exercises.
Relevant knowledge (omitted)
programming requirements
Begin-End
According to the prompt, supplement the code in the editor on the right to complete the following requirements:
first question
If the three sides of a triangle are a
, b
, c
, respectively p=(a+b+c)/2
, then the area of the triangle is:
S=p(p−a)(p−b)(p−c)
In this question, we will use triArea
the function to calculate the area of the shaded part in the figure below, and print out the result. Your task is to program a function triArea(a,b,c)
to calculate the area of a triangle using the above formula.
second question
This question uses programming to verify Goldbach's conjecture, that is, any even number greater than or equal to 6 can be expressed as the sum of two prime numbers. For example: 11111112 = 11 + 11111101
. Your task: 1) Implement a program isPrime(x)
to determine x
whether an integer is a prime number; 2) The program will use the function Goldbach(N)
to N
decompose an integer into the sum of two prime numbers to verify Goldbach's conjecture. You need to complete the function code.
third question
It is known that the initial launch velocity of a certain type of mortar is 300m/s
, the projectile has no power during flight, and the air resistance is not considered, and the acceleration due to gravity is taken as 9.8m2/s
. Under different angles, the landing time and flying position of the shell are different. This question uses programming to draw [30, 45, 60, 75]
the trajectory of the bomb when the angles are degrees. The function calculates position coordinates calBombT\frace(theta)
during the flight of the shell , and the time samples are evenly distributed. n
Your task is to complete the program code.
The calculation logic example is as follows (rounding is not required when programming):
When the angle is 30
degrees, the flight time of the bomb in the air is about 30.6s
,
If 5
a uniform time sample is taken, they are approximately[ 0, 7.6, 15.3, 22.9, 30.6 ]
Then the corresponding x
coordinates are[0,1988, 3976, 5964, 7953]
The corresponding y
coordinates are then[ 0, 860,1147, 860, 0 ]
fourth question
As shown, the equation of the uniform function is
f(x)=exsin(x)
Find [0,pi]
the length of the function curve in the interval. Your task: 1) Write a function f(x)
to calculate the value of the above function; 2) Write a function pt(a, b)
to calculate the length of the hypotenuse of a right triangle using the Pythagorean theorem.
Tip: Divide the interval into n
small intervals, and the curve can be approximated as a line segment. When the number of intervals in the small interval is large enough, the approximate length is close to the real value.
Test instruction
The platform will test the code you write: Test input:
60
30
Expected output:
24.201994
60 = 7 + 53
[0.0, 158.339198, 316.678395, 475.017593, 633.356791, 791.695989, 950.035186, 1108.374384, 1266.713582, 1425.05278, 1583.391977, 1741.731175, 1900.070373, 2058.409571, 2216.748768, 2375.087966, 2533.427164, 2691.766362, 2850.105559, 3008.444757, 3166.783955, 3325.123153, 3483.46235, 3641.801548, 3800.140746, 3958.479944, 4116.819141, 4275.158339, 4433.497537, 4591.836735]
[0.0, 570.553037, 1100.352285, 1589.397745, 2037.689417, 2445.2273, 2812.011395, 3138.041702, 3423.31822, 3667.84095, 3871.609892, 4034.625045, 4156.88641, 4238.393987, 4279.147775, 4279.147775, 4238.393987, 4156.88641, 4034.625045, 3871.609892, 3667.84095, 3423.31822, 3138.041702, 2812.011395, 2445.2273, 2037.689417, 1589.397745, 1100.352285, 570.553037, 0.0]
l = 15.476558
Let's start your mission, I wish you success!
code:
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt #导入matplotlib.pyplot
# 第一题
######## begin ###########
# 请编写函数triArea(a ,b , c),返回三角形的面积
def triArea(a,b,c):
p=((a+b+c)/2)
S=pow(p*(p-a)*(p-b)*(p-c),1/2)
return(S)
######## end #########
S1 = triArea(9.8, 9.3, 6.4)
S2 = triArea(2.9, 4.1, 4.7)
S3 = triArea(2.0, 1.4, 2.3)
print('%.6f' %(S1-S2+S3))
# 第二题
######## begin ###########
# 请编写函数isPrime(x)。判断x是否是素数,返回True或者False
def isPrime(x):
n=0
for i in range(2,x//2):
if x%i==0:
n+=1
if n==0:
return("True")
else:
return("False")
####### end ############
def Goldbach(N): # 将N分解成两素数之和
if N < 6 or N % 2 == 1: # 若N小于6或N为奇数
print('N应该是大于等于6的偶数')
else:
# 循环判断,得到符合要求的小于N的两个素数,并打印
for x in range(2, N // 2): # 想想为什么是从2到N/2
# 调用isPrime函数,得到符合要求的小于N的两个素数
######## begin ###########
if isPrime(x)=="True" and isPrime(N-x)=="True":
######## end ###########
print(N, '=', x, '+', N - x)
break
N = int(input())
Goldbach(N)
# 第三题
# calBombTrace 函数
def calBombTrace(theta):
v0, g, n = 300, 9.8, 30
theta_d = np.radians(theta) #因numpy中cos、sin的输入为弧度值,故先将theta从度转换为弧度
v0_x = v0*np.cos(theta_d) #炮弹水平初速度
v0_y = v0*np.sin(theta_d) #炮弹垂直初速度
tmax = 2*v0_y/g #落地时间,即v0_y*t-0.5gtt=0的解
t = np.linspace(0, tmax, n) #n个时刻
xt = v0_x*t #n个时刻的横坐标
yt = v0_y*t-1/2*g*t**2 #n个时刻的纵坐标
return xt, yt
for theta in [30, 45, 60, 75]:
############ begin #########
# 调用函数,得到theta返回的值,并存储到xt与yt变量
xt,yt=calBombTrace(theta)
########### end #############
plt.plot(xt, yt)
plt.grid('on')
plt.axis([0, 10000, 0, 5000])
plt.savefig('./src/step4/res/轨迹.png')
plt.close()
print([round(x,6) for x in xt])
print([round(x,6) for x in yt])
# 第四题
# 在此添加代码,编写函数f(x),计算f(x)的值
from math import *
########### begin #############
def f(x):
a=((np.e)**x)*(np.sin(x))
return(a)
########### end #############
# 在此添加代码,编写函数pt(a, b),利用勾股定理计算直角三角形的斜边长
########### begin #############
def pt(a, b):
c=pow(a**2+b**2,1/2)
return(c)
########### end ############
n = 1000 # 细分成n个子区间
x = np.linspace(0, np.pi, n + 1) # n个子区间的n+1个端点
l, h = 0, np.pi / n # l为曲线长度、h为子区间宽度
for i in range(n): # 对每个子区间
li = pt(f(x[i + 1]) - f(x[i]), h) # 曲线在第i个子区间的近似长度
l += li # 将航渡累加到l中
print('l = %.6f' %l)