Python中函数的基本用法

创建函数
用 def关键字定义函数

 def my_function():
	print("Hello from a function")
 my_function()

运行结果

     Hello from a function

参数
可以在函数中设定参数

def my_function(fname):
    print(fname + "Gates")
my_function("Rory John")
my_function("Jennifer Katharine")
my_function("Phoebe Adele")

运行结果

Rory JohnGates
Jennifer KatharineGates
Phoebe AdeleGates

默认参数值
可以在函数中直接为变量设置参数

def my_function(country = "china"):
     print("I am from" + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

运行结果

I am fromSweden
I am fromIndia
I am fromchina
I am fromBrazil

以列表传参

  def my_function(food):
    for x in food:
	    print(x)
fruits = ["apple","banana","cherry"]
my_function(fiuits)

运行代码为

apple
banana
cherry

返回值
函数的返回值可以返回到函数的调用处

def my_function(x):
    return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

运行结果

15
25
45

关键字参数

def my_function(child1,child2,child3):
     print("The youngest child is " + child3)
my_function(child1 = "Phoebe",child2 = "Jennifer" ,child3 = "Rory")

得到结果

The youngest child is Rory

任意参数
可以通过列表的索引值来输出想要的输出的结果

def my_function(*kids):
   print("The youngest child is " + kids[2])
my_function("Phoebe","Jennifer","Rory")

输出结果

The youngest child is Rory

pass语句

 def my_function:
     pass

输出结果为空

递归

def tri_recursion(k):
    if(k>0):
        result = k+tri_recursion(k-1)
        print(result)
    else:
        result = 0
        return result

print("\n\nRecursion Example Results")
tri_recursion(6)

运行结果

1
3
6
10
15
21
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值