初识函数

函数

  • 函数的定义和函数的调用
  • 函数的参数和返回值
  • 内置函数
  def func():   #函数定义
  		print('step1')
  		print('step2')
  		print('step3')
  func() #函数的调用
  print(type(func))#<class 'function'>
  print(func()) #能运行,但没有返回值,没有return所以结果None,即打印函数的返回值;
  • 调用函数执行函数定义里面的代码块;
  • 函数的定义要在函数的调用前面
def func1():
	print('we are one')
print('before func1')
func1()
print('after fun1')
#打印结果
before func1
we are one
after func1

参数

def func(a,b):#a,b是形参必填
	print(a,b)
func(1,’a')#1,2是实参,字符串加引号
func(a=1,b=2)
func(b=1,a=2)#可以指名道姓
#结果为1 2
另:def func(a,b,c=0):#c没有用pycharm默认显示灰色,如c=0则为缺省参数,可传可不传
		print(a,b)#可以不用c
	func(1,2,3)#c不是缺省时,必须传c

关键字参数调用
次序可以颠倒,一旦第n个参数使用了关键字参数,后面所有的参数都必须使用关键字;

def foo2(a,b):
	print((a*2+b*4)/22)
foo2(3,4)
foo2(a=3,b=4)
foo2(b=4,a=3)
foo2(3,b=4)
foo2(a=3,4)#此种是错误语法

函数的返回值

def func(a,b):
	if a > b:
		res = '结果:a>b'  效果同return '结果:a>b'
		return [1,2]#可以return列表
		return(3,6)#可以return元组
	else:
		res = '结果:a<b'
	return res#到这里,该函数已经执行完成,后面的不会执行;正规不该有;
	print('end')
 print(func(1,2))
 #结果:a<b

几个内置函数
print、len、max、min

len([1,2,3,4,5])
max([1,2,3,4,5])
min([1,2,3,4,5])
len((1,2,3,4,5))
max((1,2,3,4,5))
min((1,2,3,4,5))

str、int、float

str(1)
str(2.344)
str(‘2.34’)
int(‘54’)
float(‘54.4’)
float(‘54’)

type

type(1)
type([ ])

python程序下的python Modules(手册可查)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值