1.Input()的工作原理
1.1 input()函数让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便使用。
- 如:message = input("Tell me something, and I will repeat it back to you:") 该程序会显示Tell...文本来进行提示。
1.2 可将提示存储在一个变量中,再将该变量传递给函数input()。
1.3 可以使用int()来获取数值输入。(在使用input()时,Python将用户输入解读为字符串)
- 使用方法:
height = int(input())
2.使用while循环来处理列表和字典
2.1 因为python中的for循环是for each循环,不能很好的处理在遍历列表的同时对其进行修改。
2.2 可以用while来判断列表是否为空,在通过pop等方法进行操作。
2.3 删除包含特定值的所有列表元素:
while 'cat' in pets:
pets.remove('cat')
3.函数
3.1 函数定义:使用关键字def。
def greet_user():
print('Hello!')
3.2 关键字实参:是传递给函数的名称——值对。可以直接在实参中将名称和值关联起来,在向函数传递实参时不会混淆。
# 两者显示相同
def describe_pet(animal_type,pet_name):
print('name='+animal_type+'.')
print('type='+pet_name+'.')
describe_pet(animal_type='aaa',pet_name='bbb')
describe_pet(pet_name='bbb',animal_type='aaa')
3.3 在编写函数时,可给每个形参指定默认值。
#默认宠物类型为dog
def describe_pet(pet_name,animal_type='dog')
...
3.4 返回值:使用关键字return。
4.在函数中修改列表
4.1 在函数中对这个列表所做的任何修改都是永久性的。
4.2 函数中的传递的参数采用对象的引用。
4.3 如果不想函数对对象进行修改,可以传递该对象的副本。
- 一般用切片表示法[:]创建列表的副本。
5.传递任意数量的实参
#实例
def make_pizza(*toppings):
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
5.1 该实例中,形参名*toppings中的星号让Python创建一个名为toppings的空元祖,并将收到的所有值都封装在这个元组中。
5.2 如果要让函数接收不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
6.传递任意数量的关键字实参
#实例
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['second_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)
6.1 示例中的形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称——值对都封装到这个字典中。
7.将函数存储在模块中
7.1 将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前允许的程序文件中使用模块的代码。
7.2 模块是扩展名为.py,包含要导入到程序中的代码。
如:from module_name import function_name
8.as
8.1 给函数指定别名:from pizza import make_pizza as mp
8.2 给模块指定别名:import pizza as p