cars =['audi','bmw','subaru','toyota']for car in cars: ❶
if car =='bmw':print(car.upper())else:print(car.title())# if else 的冒号别忘了 关于字符串的一些 lower()、upper()、title()等方法 在比较时可以使用# == != >= <= 检查多个条件 and or# 检查特定元素是否在列表内 不在列表内 使用in 和 not in 关键字
requested_toppings =['mushrooms','onions','pineapple']if'mushrooms'in requested_toppings
banned_users =['andrew','carolina','david']
user ='marie'if user notin banned_users:print(user.title()+", you can post a response if you wish.")# 多个条件判断 if-elif-else 注意冒号别忘了
age =12if age <4:
price =0elif age <18:
price =5else:# else 代码块不是必须的
price =10print("Your admission cost is $"+str(price)+".")# 注意,字符串和数字,用str()函数,将整数转化为字符串,否则编译器报错
requested_toppings =['mushrooms','green peppers','extra cheese']for requested_topping in requested_toppings:if requested_topping =='green peppers':print("Sorry, we are out of green peppers right now.")else:print("Adding "+ requested_topping +".")print("\nFinished making your pizza!")# for循环中嵌套if 进行条件判断 注意冒号# 在if 语句中将列表名用在条件表达式中 时,Python将在列表至少包含一个元素时返回True ,并在列表为空时返回False
requested_toppings =[]if requested_toppings:for requested_topping in requested_toppings:print("Adding "+ requested_topping +".")print("\nFinished making your pizza!")else:print("Are you sure you want a plain pizza?")# 如果列表为空 执行什么操作 非空执行什么操作
available_toppings =['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings =['mushrooms','french fries','extra cheese']for requested_topping in requested_toppings:# 对需求列表进行遍历if requested_topping in available_toppings:# 判断顾客需求列表的元素是否在可提供列表中print("Adding "+ requested_topping +".")else:print("Sorry, we don't have "+ requested_topping +".")print("\nFinished making your pizza!")
字典
# 字典,有种结构体的感觉 字典用 {} 进行标识
alien_0 ={'color':'green','points':5}# 键值对 键和值之间用 : 分隔 键值对之间用 , 分隔# 用键来访问与之相关联的值,与键相关联的值可以是数字、字符串、列表乃至字典。#访问字典中的值 获取与键相关联的值,依次指定字典名和放在方括号内的键
alien_0 ={'color':'green'}print(alien_0['color'])# green# 字典中可以包含任意数量的键值对# 添加键值对
alien_0 ={'color':'green','points':5}print(alien_0)
alien_0['x_position']=0# 指出新的键名 再给出对应的值
alien_0['y_position']=25print(alien_0)# {'color': 'green', 'points': 5} 新增前# {'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0} 新增后#字典、列表、元组都是类似的,直接print(名字),打印出来对应的字典或者...包括标识【()、[]、{} 】都打印的#注意,键—值对的排列顺序与添加顺序不同。Python不关心键—值对 的添加顺序,而只关心键和值之间的关联关系。#修改字典中的值,和添加键值对一样,都是指定键名给出键值
alien_0 ={'color':'green'}print("The alien is "+ alien_0['color']+".")
alien_0['color']='yellow'print("The alien is now "+ alien_0['color']+".")# 删除键值对 使用del语句
alien_0 ={'color':'green','points':5}del alien_0['points']# 指定键名进行删除 同时键值也对应删除
favorite_languages ={'jen':'python','sarah':'c','edward':'ruby','phil':'python',}# 这样看起来方便 格式# 遍历字典# for循环遍历字典 声明两个变量 对应字典中的键和值
user_0 ={'username':'efermi','first':'enrico','last':'fermi',}for key, value in user_0.items():print("\nKey: "+ key)print("Value: "+ value)# item()方法把字典中每对key和value组成一个元组,并把这些元组放在列表中返回# 即便遍历字典时,键—值对的返回顺序也与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。# 尽可能的将变量命名实义化
favorite_languages ={'jen':'python','sarah':'c','edward':'ruby','phil':'python',}for name, language in favorite_languages.items():print(name.title()+"'s favorite language is "+ language.title()+".")# 遍历字典中的所有键 方法keys() 只需要键名,不需要键值
favorite_languages ={'jen':'python','sarah':'c','edward':'ruby','phil':'python',}for name in favorite_languages.keys():print(name.title())# 调用item()返回键名和键值组成的列表 调用keys()返回键名# 按顺序遍历字典中的所有键
favorite_languages ={'jen':'python','sarah':'c','edward':'ruby','phil':'python',}for name insorted(favorite_languages.keys()):print(name.title()+", thank you for taking the poll.")# 先得到有键名组成的列表favorite_languages.keys(),再使用sorted()函数创建列表副本,最后使用for循环遍历得出有序的键名#同理,使用values()函数,可得到键值for language in favorite_languages.values():print(language.title())# 得到键值组成的列表再遍历输出,这样是全部输出,可能会有重复。使用集合set,类似于列表,但是有唯一性(不重复)for language inset(favorite_languages.values()):print(language.title())# 通过对包含重复元素的列表调用set() ,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。#字典嵌套
alien_0 ={'color':'green','points':5}
alien_1 ={'color':'yellow','points':10}
alien_2 ={'color':'red','points':15}
aliens =[alien_0, alien_1, alien_2]# 字典列表for alien in aliens:print(alien)# 输出列表中的三个字典# {'color': 'green', 'points': 5} # {'color': 'yellow', 'points': 10} # {'color': 'red', 'points': 15}# 在字典中存储列表 存储所点比萨的信息
pizza ={'crust':'thick','toppings':['mushrooms','extra cheese'],# 键名toppings,关联的键值是一个列表}print("You ordered a "+ pizza['crust']+"-crust pizza "+"with the following toppings:")for topping in pizza['toppings']:print("\t"+ topping)# 在字典中存储字典
users ={'aeinstein':{'first':'albert','last':'einstein','location':'princeton',},'mcurie':{'first':'marie','last':'curie','location':'paris',},}# 定义一个字典user 存储用户信息 ,其中对应的键相关联的又是一个字典for username, user_info in users.items():print("\nUsername: "+ username)
full_name = user_info['first']+" "+ user_info['last']
location = user_info['location']print("\tFull name: "+ full_name.title())print("\tLocation: "+ location.title())# 即username指向字典user的两个键名,user_info对应两个键名所对应的字典 user_info['first']访问嵌套内的值