输入
获取(字符串):input()
函数内可以添加说明字符串。可通过后加int()将字符值转为数字。
message = input('how old are you?')
message = int(message)
print(message)
how old are you?1
1
while循环
while flag:
xxx
if a == 0:
break #退出循环
elif a == 1:
continue #回到循环开头
else:
xxx
按 ctrl+c 退出循环
函数
传递实参
实参是函数调用中的变量,形参是函数定义中的变量
位置实参、关键字实参、默认值
def describe_pet(animal_type ,pet_name='dahuang'):
print("My "+animal_type+"'s name is "+ pet_name+".")
describe_pet('dog','dahuang') #位置实参
describe_pet(pet_name='ergou',animal_type='dog')#关键字实参
describe_pet('bird')#默认值
My dog's name is dahuang.
My dog's name is ergou.
My bird's name is dahuang.
注:使用默认值时,形参列表中必须先列出没有默认值的形参,再列出有默认值的形参,否则会报错。
如下错误案例:
def describe_pet(animal_type='dog' ,pet_name):
print("My "+animal_type+"'s name is "+ pet_name+".")
describe_pet('dog','dahuang')
报错
SyntaxError: non-default argument follows default argument
将实参变成可选的:给形参指定一个默认值——空字符串,并将其移动到形参列表的末尾。
返回值
1、可返回简单值、列表、字典等任何值
def make_album(singer_name,album_name,music_number=''):
albuminfo = {'singer':singer_name,'album':album_name}
if music_number:
albuminfo['musicn'] =music_number
return albuminfo
alb1 = make_album('刀郎','2002年的第一场雪',1)
alb2 = make_album('jay','双截棍')
alb3 = make_album('bb5','noise')
print(alb1)
print(alb2)
print(alb3)
{'singer': '刀郎', 'album': '2002年的第一场雪', 'musicn': 1}
{'singer': 'jay', 'album': '双截棍'}
{'singer': 'bb5', 'album': 'noise'}
2、禁止函数修改列表
function_name(list_name[:])
注:这里是修改的实参,不是形参!! 也就是在使用函数时加[:]而不是在定义函数时使用!
切片表示法[:]创建列表的副本。
虽然向函数传递列表的副本可保留原始列表的内容,但是除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数。因为让函数使用现成列表可避免花时间和内存创建副本,提高效率。
def show_magicians(magicians_names):
for magicians_name in magicians_names:
print(magicians_name)
def make_great(magicians_names):
for magicians_name in range(len(magicians_names)):
magicians_names[magicians_name] = 'the Great '+ magicians_names[magicians_name];
names =['大刘','小王','二狗']
ma_names = names[:]
show_magicians(names)
make_great(names)
show_magicians(names)
make_great(ma_names[:])
show_magicians(ma_names)
大刘
小王
二狗
the Great 大刘
the Great 小王
the Great 二狗
大刘
小王
二狗
传递任意数量的实参
在形参中使用和**
1、 args是可变参数,args 接收的是一个元组。比如可以向一个函数传入一个列表(或迭代器),在形参中是使用*就可以在函数中依次接收这个列表的每一个元素;
例子 三明治中添加食材
def sandwich_combination(*foods):
for food in foods:
print(food)
sandwich_combination('abc','ppp','noodles','bread')
abc
ppp
noodles
bread
2、**kw 是关键字参数,kw 接收的是一个字典。比如在收集用户信息的时候,除了必填项之外,我们可以用 ** 来方便地接收那些未知个数的可选项。
例子 将一辆汽车的信息存储在一个字典中,接受制造商和型号,以及任意数量的关键字实参,打印函数返回的字典。
def make_car(car_manufacturer,car_type,**car_info):
profile={}
profile['manufacturer'] = car_manufacturer
profile['type']=car_type
for key,value in car_info.items():
profile[key] = value
return profile
car=make_car('subaru','outback',color='blue',tow_package=True)
print(car)
{'manufacturer': 'subaru', 'type': 'outback', 'color': 'blue', 'tow_package': True}
补充:当对象为迭代器时,可在实参中使用*;当对象为一个可迭代的映射时,可在实参中使用**
简化为字典dict:
实参中的*会获取可迭代对象的 key(索引/键值)
实参中的**会获取可迭代映射的 value
def foo(n1, n2, n3, n4, n5):
return n1, n2, n3, n4, n5
d = {'n1': 5, 'n2': 6, 'n3': 7, 'n5': 8, 'n4': 9}
print(foo(*d))
print(foo(**d))
('n1', 'n2', 'n3', 'n5', 'n4')
(5, 6, 7, 9, 8)
将函数存储在模块中
1、导入整个模块
def make_pizza(size,*toppings):
"""概述要制作的披萨"""
print("\nMaking a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("- "+topping)
存入文件pizza.py(作为一个模块)
在该目录下再创建一个making_pizzas.py的文件,导入刚才的模块
注:需要把模块所在目录的上一级目录导入系统环境变量中!
import pizza
pizza.make_pizza(9,'mushrooms','green peppers')
Making a 9-inch pizza with the following toppings:
- mushrooms
- green peppers
2、导入特定函数
from pizza import make_pizza
make_pizza(9,'mushrooms','green peppers')
结果同上一样。但是调用的方式变了。不需要加前面的模块名字,可以直接用其方法函数。
3、使用as给制定函数指定别名
from pizza import make_pizza as mp
mp(9,'mushrooms','green peppers')
结果同上。
4、使用as给模块指定别名
import pizza as p
p.make_pizza(9,'mushrooms','green peppers')
5、导入模块中所有函数
from pizza import *
make_pizza(9,'mushrooms','green peppers')