Python函数教学反思的简单介绍( 二 )


食用方法
将研磨成细小的粉末,和水或者酒一同服下,可以达到上述效果 。
python中函数定义1、函数定义
①使用def关键字定义函数

def 函数名(参数1.参数2.参数3...):
"""文档字符串,docstring,用来说明函数的作用"""
#函数体
return 表达式
注释的作用:说明函数是做什么的,函数有什么功能 。
③遇到冒号要缩进 , 冒号后面所有的缩进的代码块构成了函数体 , 描述了函数是做什么的,即函数的功能是什么 。Python函数的本质与数学中的函数的本质是一致的 。
2、函数调用
①函数必须先定义,才能调用 , 否则会报错 。
②无参数时函数的调用:函数名() , 有参数时函数的调用:函数名(参数1.参数2.……)
③不要在定义函数的时候在函数体里面调用本身 , 否则会出不来,陷入循环调用 。
④函数需要调用函数体才会被执行,单纯的只是定义函数是不会被执行的 。
⑤Debug工具中Step into进入到调用的函数里,Step Into My Code进入到调用的模块里函数 。
Python的函数参数总结import math
a = abs
print(a(-1))
n1 = 255
print(str(hex(n1)))
def my_abs(x):
# 增加了参数的检查
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x = 0:
return x
else:
return -x
print(my_abs(-3))
def nop():
pass
if n1 = 255:
pass
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
print(x, y)
tup = move(100, 100, 60, math.pi / 6)
print(tup)
print(isinstance(tup, tuple))
def quadratic(a, b, c):
k = b * b - 4 * a * c
# print(k)
# print(math.sqrt(k))
if k0:
print('This is no result!')
return None
elif k == 0:
x1 = -(b / 2 * a)
x2 = x1
return x1, x2
else:
x1 = (-b + math.sqrt(k)) / (2 * a)
x2 = (-b - math.sqrt(k)) / (2 * a)
return x1, x2
print(quadratic(2, 3, 1))
def power(x, n=2):
s = 1
while n0:
n = n - 1
s = s * x
return s
print(power(2))
print(power(2, 3))
def enroll(name, gender, age=8, city='BeiJing'):
print('name:', name)
print('gender:', gender)
print('age:', age)
print('city:', city)
enroll('elder', 'F')
enroll('android', 'B', 9)
enroll('pythone', '6', city='AnShan')
def add_end(L=[]):
L.append('end')
return L
print(add_end())
print(add_end())
print(add_end())
def add_end_none(L=None):
if L is None:
L = []
L.append('END')
return L
print(add_end_none())
print(add_end_none())
print(add_end_none())
def calc(*nums):
sum = 0
for n in nums:
sum = sum + n * n
return sum
print(calc(1, 2, 3))
print(calc())
l = [1, 2, 3, 4]
print(calc(*l))
def foo(x, y):
print('x is %s' % x)
print('y is %s' % y)
foo(1, 2)
foo(y=1, x=2)
def person(name, age, **kv):
print('name:', name, 'age:', age, 'other:', kv)
person('Elder', '8')
person('Android', '9', city='BeiJing', Edu='人民大学')
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)
def person2(name, age, *, city, job):
print(name, age, city, job)
person2('Pthon', 8, city='BeiJing', job='Android Engineer')
def person3(name, age, *other, city='BeiJing', job='Android Engineer'):
print(name, age, other, city, job)
person3('Php', 18, 'test', 1, 2, 3)