Python函数的基础使用
#------------------------调用函数------------------------#
# 知道函数的名称和参数
print('调用函数abs(X)求绝对值:', abs(-100))
qq = abs
print('变量qq指向函数abs,即给函数abs起了一个qq的别名:', qq(-100))
#------------------------定义函数,格式为def 函数名(参数[可选],参数[可选])------------------------#
def speak(peopleName, word):
print(peopleName + '说:' + word)
speak('周杰伦', '大家好')
# 函数中使用return
# 使用pass 占位符,比如还没想好要怎么处理,如果不写处理过程,运行可能报错
def ret(score):
if score>=100:
pass
elif score >= 90:
return 'nice'
elif score >= 80:
return 'good'
else:
return 'normal'
print(ret(85))
print(ret(105))
# 函数中使用continue,跳出本次循环
def con(scoreList):
for score in scoreList:
if score % 2 == 0:
continue
else:
print('奇数:', score)
scoreList = [15, 22, 59, 78, 63, 24]
con(scoreList)
# 函数中使用break,结束循环
def bre(scoreList):
for score in scoreList:
if score % 2 == 0:
print('碰到第一个偶数结束循环:', score)
break
else:
print('奇数:', score)
bre(scoreList)
#函数可以返回多个值,多个值以元组的方式返回
def moreResult(x,y):
x=x+y
y=x-y
return x,y
print(moreResult(20, 10))
#------------------------函数的参数------------------------#
#位置参数:即定义函数时定义参数,使用函数的时候需要按照参数的位置设置参数值
def hello(name,age):
print(name+'的年龄是:'+age)
hello('周杰伦', '42')
#默认参数:调用某一个函数,但某一个参数不是必需值,不填的话函数调用会报错,因此调用函数时参数为非必要时,可设置默认参数
hello('周杰伦', age='保密')
#打印结果
调用函数abs(X)求绝对值: 100
变量qq指向函数abs,即给函数abs起了一个qq的别名: 100
周杰伦说:大家好
good
None
奇数: 15
奇数: 59
奇数: 63
奇数: 15
碰到第一个偶数结束循环: 22
(30, 20)
周杰伦的年龄是:42
周杰伦的年龄是:保密