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
>>>