2022年4月24日:面向初学者的Python--Python函数

Python函数的基本知识

不带参数的函数

若要创建函数,请使用关键字def,后面跟名称、括号,然后是包含函数代码的主体。

必需参数和可选参数

需要参数的内置函数是一个示例是any()。此函数接收可迭代对象并在可迭代对象中的任何项目为True时返回True。否则,它将返回False。

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def rocket_parts():
...     print("payload,propellant,structure")
...
>>> rocket_parts()
payload,propellant,structure
>>> output=rocket_parts()
payload,propellant,structure
>>> output is None
True
>>> def rocket_parts():
...     return "playload,propellant,structure"
...
>>> output=rocket_parts()
>>> output
'playload,propellant,structure'
>>> any([True,False,False])
True
>>> any([False,False,False])
False
>>> str()
''
>>> str(15)
'15'
>>>

 

在Python中使用函数参数

需要参数

Python 会引发 TypeError,出现一条错误消息,指出该函数需要一个名为 destination 的参数。

多个必需参数

若要使用多个参数,必须 使用逗号分隔它们。

以函数作为参数

 

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def distance_from_earth(destination):
...     if destination=="Moon":
...             return "238,855"
...     else:
...             return "Unable to compute to that destination"
...
>>> distance_from_earth("Moon")
'238,855'
>>> distance_from_earth("Saturn")
'Unable to compute to that destination'
>>> def days_to_complete(distance,speed):
...     hours=distance/speed
...     return hours/24
...
>>> days_to_complete(238855,75)
132.69722222222222
>>> total_days=days_to_complete(238855,75)
>>> round(total_days)
133
>>> round(days_to_complete(238855,75)
... )
133
>>>

在Python中使用关键字参数

可选参数要求赋予默认址。这些已命名的参数称为关键字参数。

混合参数和关键字参数

有时,函数需要组合使用参数和关键字参数。在Python中,此组合遵循特定的顺序。始终首先声明参数,然后声明关键字参数。

 

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import timedelta,datetime
>>> def arrival_time(hours=51):
...     now=datetime.now()
...     arrival=now+timedelta(hours=hours)
...     return arrival.strftime("Arrival: %A %H:%M")
...
>>> arrival_time()
'Arrival: Tuesday 18:11'
>>> arrival_time(hours=0)
'Arrival: Sunday 15:12'
>>>
>>> from datetime import timedelta,datetime
>>> def arrival_time(destination,hours=51):
...     now=datetime.now()
...     arrival=now+timedelta(hours=hours)
...     return arrival.strftime(f"{destination} Arrival: %A %H:%M")
...
>>> arrival_time("Moon")
'Moon Arrival: Tuesday 18:15'
>>> arrival_time("Orbit",hours=0.13)
'Orbit Arrival: Sunday 15:23'
>>>

在Python中使用可变参数

在 Python 中,可以使用任意数量的参数和关键字参数,而无需声明其中的每个参数。

可变参数

函数中的参数是必需的。 但使用可变参数时,函数可允许传入任意数量的参数(包括 0 个参数)。 使用可变参数的语法是在参数名之前加上一个星号 (*)。

 

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def variable_length(*args):
...     print(args)
...
>>> variable_length()
()
>>> variable_length("one","two")
('one', 'two')
>>> variable_length(None)
(None,)
>>> def sequence_time(*args):
...     total_minutes=sum(args)
...     if total_minutes<60:
...             return f"Total time to launch is {total_minutes} minutes"
...     else:
...             return f"Total time to launch is {total_minutes/60} hours"
...
>>>

可变关键字参数

若使用函数接受任意数量 的关键字参数,需要使用双星号。

 

Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def variable_length(**kwargs):
...     print(kwargs)
...
>>> variable_length(tanks=1,day="Wednesday",pilots=3)
{'tanks': 1, 'day': 'Wednesday', 'pilots': 3}
>>> def crew_members(**kwargs):
...     print(f"{len(kwargs)} astronauts assigned for this mission:")
...     for title, name in kwargs.items():
...             print(f"{title}: {name}")
...
>>> crew_mumbers(captain="Neil Armstrong", pilot="Buzz Aldrin", command_pilot="Michael Collins")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'crew_mumbers' is not defined. Did you mean: 'crew_members'?
>>> crew_members(captain="Neil Armstrong", pilot="Buzz Aldrin", command_pilot="Michael Collins")
3 astronauts assigned for this mission:
captain: Neil Armstrong
pilot: Buzz Aldrin
command_pilot: Michael Collins
>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值