1、使用函数input()时, Python将用户输入解读为字符串。
age= input("How old are you?")
print(age)
当输入12时,输出为:12, 当输入为old时,输出也为:old, 从输出看,并未体现出这一点。在控制台上测试,输出为带单引号的字符串。这或许是因为Spyder对输出进行修饰的原因。
2、删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
pet= 'cat'
while pet in pets: #此处,关键字in的用法比较重要。
pets.remove(pet) #pet in pets 本身是一句判断,若用print(pet in pets)则会输出True.
print(pets)
3、函数调用
def build_person(first_name, last_name, age=''):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
输出:{'first': 'jimi', 'last': 'hendrix', 'age': 27} 函数返回一个字典。函数的作用:构造一个字典。如果调用函数的时候,不提供age信息,则创建的字典无age信息;若提供age信息,则创建含age的字典。
4、在函数中修改list,原list也遭修改。说明形参对应的list和实参的list,是同一个list,而非备份的关系。
def modify_list(test1_list):
test1_list.pop(1)
test_list=['china', 'germany','france', 'america']
print(test_list)
modify_list(test_list)
print(test_list)
输出:
['china', 'germany', 'france', 'america']
['china', 'france', 'america']
5、传递任意数量的实参。最方便动态添加,且简单的数据结构是列表。因此,函数中形参为列表。
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
if toppings:
for topping in toppings:
print(topping.title())
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers', 'extra cheese')
6、使用任意数量的关键字实参
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_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)
注意,字典中的键值对顺序比较随机。因此,输出为:
{'last_name': 'einstein', 'location': 'princeton', 'field': 'physics', 'first_name': 'albert'}