Python函数定义与实现

1.python定义函数用def表示,参数不需要写出参数类型,给出参数列表即可,在参数列表中可以给出默认值,不过戴莫任职的参数要放在最后,函数最后要加“:”,和if else一样,python函数返回值可以有多个,其实相当于返回的是一格元组,接收时根据位置传入值。

def 函数名(参数1,参数2,...):  

   ....

   .... 

因为python采取缩进来表示外部内部关系,之后函数体要相比前面一行至少空出一格,表示在此函数内部,否则会跳转在函数外部执行,其他if else,while体内执行的语句写法也一样。

 

2.函数代码样例如下所示:

import math

def squre(a,b,c=0):

  t=b*b-4*a*c
  if t<0:
    print("No results!")
    return None,None
  elif t==0:
    print("Only one result!")
    x=(-b+math.sqrt(b*b-4*a*c))/2*a
    return x,None
  else:
    print("Two result!")
    x1=(-b+math.sqrt(b*b-4*a*c))/2*a
    x2=(-b-math.sqrt(b*b-4*a*c))/2*a
    return x1,x2


print("this is a function:x*x-5x+4=0")
x1,x2=squre(1,-5,4)
print(x1,x2)
print("this is a function:x*x-4x+4=0")
x1,x2=squre(1,-4,4)
print(x1,x2)
print("this is a function:x*x-x+4=0")
x1,x2=squre(1,-1,4)

print(x1,x2)

3.执行结果


猜你喜欢

转载自blog.csdn.net/kuishao1314aa/article/details/81015054