python的函数基础知识与练习

36 篇文章 1 订阅

1.定义函数

1)定义函数
def say_hello():
    print('hello1')
    print('hello2')
    print('hello3')
say_hello()		引用函数
运行结果:
hello1
hello2
hello3

def sum_num():
    num1=2
    num2=3
    sum1=num1+num2
    print('%d + %d =%d' %(num1,num2,sum1))
sum_num()
运行结果:2 + 3 =5

2)函数嵌套
def westos():
    print('westos')
    def python():
        print('python')
    python()
westos()
运行结果:
westos
python


def welcome(a):		定义函数的时候的变量 叫形参(可以任意起名)
    print('hello',a)
welcome('aaa')		真实的数据信息,调用函数的时候传的参数叫实参
运行结果: hello aaa

2.四大参数

参数:形参 实参
形参: 位置参数 默认参数 可变参数 关键字参数
1)位置参数:形参和实参个数必须保持一致,最好按位置传参

def getInfo(name, age):
    print(name, age)

getInfo('hr', 45)
getInfo(24, 'ww')
getInfo(age=11, name='westos')
运行结果:
hr 45
24 ww
westos 11     

2)默认参数:形参和实参可以不一致

def mypow(x,y=2):		行参中y=2
print(x**y)

mypow(4,3)		实参y=3
运行结果:64		结果是4的3次方

3)可变参数

def mysum(*a):
    """
    :param a:
    :return:
    *a:可变参数
    a:是元组数据类型
    """
    # print(a)
    sum = 0
    for item in a:
        sum += item
    print(sum)
mysum(1,2,3,4,5,6,7,8,9)
运行结果:45

4)关键字参数

def getStuInfo(name,age,**kwargs):
    """
    **kwargs是一个字典,可以传递任意多的key-value
    :param name:
    :param age:
    :param kwargs:
    :return:
    """
    print(name,age)
    print(kwargs)

getStuInfo('westos','19',hobbies=['coding','running'],gender='female')
运行结果:
westos 19
{'hobbies': ['coding', 'running'], 'gender': 'female'}

3.函数的返回值

返回值:函数运行的结果,还需要进一步操作时,给一个返回值。
return用来返回函数执行结果,如果没有返回值,默认为None,python可以间接返回多个值(返回了一个元组)。一旦遇到return,函数执行结束,后面的代码不会执行。

def mypow(x, y=2):
    return x ** y, x + y
    print('hello')
	
a, b = mypow(3, 4)
print(a, b)
运行结果:81 7		输出没有hello说明,程序遇到return执行结束。

def mypow(x, y=2):
    print(x ** y)

a = mypow(2)
print(a)
运行结果:
4
None

4.变量的作用域

局部变量:在函数内部定义的变量,只在函数内部起作用,函数执行结束变量会自动删除。

全局变量 :可以被程序所有对象或函数引用。

a = 1
print('outside:', id(a))	查看变量ID。

def fun():
    global a
    a = 5
    print('inside:', id(a))

fun()
print(a)
print(id(a))
运行结果:
outside: 9334784		全局变量ID
inside: 9334912			局部变量ID
5
9334912
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值