字典
三、遍历字典
1. 遍历所有键值对:用方法items(),返回键值对列表。用for循环遍历整个字典,声明两个变量来存储键值对中的键和值。
user = {'username':'tt', 'userage':22, 'occupation':'student'}
for key, value in user.items():
print(f"\nkey:{key}")
print((f"value:{value}"))
2. 遍历所有键:用方法keys(),提取字典中所有的键。实际上,遍历字典时,会默认遍历所有的键。因此如果不加这个方法,输出也不会改变。
3. 按特定顺序遍历所有键:调用函数sorted()。
4. 遍历字典中所有值:使用方法values()来返回一个值列表,不包含任何键。这种做法提取了所有的值而没有考虑是否重复。为了剔除重复项,可以使用集合函数set()。(集合可以通过一对花括号直接创建,在其中用逗号分隔元素。)
people = ['tt', 'yh', 'zy', 'cc', 'hh']
friends = {'yh':'java', 'zy': 'python', 'hh':'C'}
for person in people:
if person in friends.keys():
print(f"Thank you for joining us, {person}")
else:
print(f"Please join us, {person}")
四、嵌套
有时候需要一系列字典存储在列表中,获奖列表作为值存储在字典中,这称为嵌套。
1. 列表中存储字典
2. 字典中存储列表:每当需要在字典中将一个值关联到多个值时,都可以在字典中嵌套一个列表。
3. 字典中存储字典
zyt = {'age':22, 'hobby' : 'reading', 'interest':'python'}
zzy = {'age':22, 'hobby' : 'shopping', 'interest':'java'}
byh = {'age':23, 'hobby' : 'gym', 'interest':'C'}
people = {'tt':zyt, 'zy':zzy, 'yh':byh}
for person, personinfo in people.items():
print(f"It's {person} speaking. My age is {personinfo['age']} and my hobby is {personinfo['hobby']}. I am interested in {personinfo['interest']}.")
用户输入和while循环
一、函数input()的工作原理
函数input()让程序暂停运行等待输入文本,获取输入后,Python将其赋给变量以方便使用。
input()将用户输入解读为字符串,int()将用户输入解读为数值。
number = input('please input a integer')
number = int(number)
if number % 10 == 0:
print('the number you have inputted is an integer times of 10')
else:
print("the number you have inputted isn't an integer times of 10")
二、while循环
for循环针对集合中每个元素都执行一个代码块,而while循环则不断运行,直到指定的条件不满足为止。
1. 使用break退出循环:立即退出while循环,不再运行循环中余下的代码,也不管条件测试的结果如何时,使用break语句来控制程序流程。
2. 在循环中使用continue:返回循环开头,并根据条件测试结果决定是否继续执行循环。
sandwich_orders = ['tuna sandwich', 'pastrami', 'beaf sandwich', 'vegetable sandwich','pastrami', 'cheese sandwich', 'pastrami']
finished_orders = []
print('pastrami is sold out')
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
for sandwich_order in sandwich_orders:
finished_orders.append(sandwich_order)
for fi_order in finished_orders:
print(f"{fi_order} is finished.")
函数
一、介绍
1. 使用关键字def定义函数,指出函数名和函数所需要的参数,以冒号结尾。
2. 文档字符串(docstring)注释用三引号括起。
3.
二、向函数传递信息
1. 实参和形参
定义函数时指定的变量名是形参parameter,即函数完成工作所需的信息。值是实参argument,是调用函数时传递给函数的信息。
传递实参有几种方法:位置实参——实参顺序与形参顺序相同;关键字实参——每个实参都由变量名和值组成,位置无关紧要;列表和字典。
def describe_pet(animal_type, pet_name):
print(f"\nI have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')#位置实参
describe_pet(animal_type = 'cat', pet_name = 'kitty')#关键字实参
也可以为形参设置默认值,这样,在调用函数时,如果没有给该形参指定值,Python就把形参设置为默认值。(想让某个参数变为可选择填写的,可以把默认值设为空字符串'')
def describe_pet(animal_type = 'dog', pet_name):
practice8-8
def make_album(singer_name, album_name, number=None):
album = {'singer': singer_name, 'title': album_name, 'amount': number}
return album
while True:
print('if you want to quit in any time, please input q at any time to leave')
in1 = input("please enter one singer's name:")
if in1 == 'q':
break
in2 = input('please enter his or her album name:')
if in2 == 'q':
break
in3 = input('please enter the number of songs in this album(optional):')
if in3 == 'q':
break
elif in3 == '':
album = make_album(in1, in2)
else:
in4 = int(in3)
album = make_album(in1, in2, in4)
print(f"you create this following dict:\n{album}")