提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、函数
1. 示例:
def greet_user():
"""这里放置文档字符串(docstring)的注释,描述函数是做什么的"""
print("Hello")
greet_user()
greet_user.__doc__
# 文档字符串:可以通过函数名.__doc__ 进行查看函数注释
2. 参数设置
第一种:位置实参
def describe_pet(animal_type, pet_name):
"""显示宠物信息"""
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name.title()}")
describe_pet('hamster','harry')
第二种:关键字参数
describe_pet(animal_type = 'hamster', pet_name = 'harry')
describe_pet(pet_name = 'harry', animal_type = 'hamster') # 两种调用等效
第三种:默认值
形参设置默认值的意义在于调用时可以省略部分实参的传递,但是设置默认值的形参位于没有设置默认值的前面,将导致不能省略有默认值形参的实参传递,否则将会把没有默认值的形参的实参值传递给设有默认值的形参,还导致部分形参没有指定值。
def describe_pet(pet_name, animal_type = 'dog'):
"""显示宠物信息"""
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name.title()}")
describe_pet('harry')
describe_pet(pet_name = 'harry', animal_type = 'hamster')
3. 让实参变为可选
def get_formatted_name(first_name, last_name, middle_name = ''):
"""返回整洁的姓名"""
if middle_name:
full_name = f"{first_name} {last_name} {middle_name }"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jhon', 'edward')
musician = get_formatted_name('jhon', 'edward', 'ella')
4. 函数结合while函数使用
def get_formatted_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("Please tell me your name.")
print("enter 'q' to quit")
f_name = input("Your first name:")
if f_name == 'q':
break
l_name = input("Your last name:")
if l_name == 'q':
break
print(get_formatted_name(f_name,l_name))
5.在函数中修改列表
def print_models(unprinted_designs, completed_models):
"""模拟打印每个设计,直到没有未打印的设计为止。打印每个设计后,都将其移到列表completed_models中"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model:{current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['phone','robot']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
# 注:这里的理念是:每个函数都只负责一项具体工作
# 注:函数调用函数不需要定义在前调用在后。
# 注:若不想更改列表,可以传递列表的副本:print_models(unprinted_designs[:], completed_models)
6.tuple参数
def make_pizza(*toppings):
for topping in toppings:
print(topping)
make_pizza('mushroom', 'green peppers')
# 注:形参名*args 可以收集任意数量的实参
7.关键字参数
def make_car(manufacturer, model, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model'] = model
return car_info
make_car('porsche','718 cayman', price = 20000, color = 'green')
# **kwargs可接受任意数量的关键字实参,传递形式为字典
二、例题
1.Perfct Number
Write a Python function to check whether a positive integer is perfect or not. Then write a Python program to test your function.
Note:
According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.
def isPerfect(n):
s = 0
for i in range(1,n):
if n % i == 0:
s += i
return s == n
n = int(input('Please input a number:'))
print(f"{n} {'is' if isPerfect(n) else 'is not'} a pefect number."