# 遍历列表
magicians =['alice','david','carolina']for magician in magicians:print(magician)# Python函数range()让你能够轻松地生成一系列的数字。for value inrange(1,5):print(value)# 使用range()创建数字列表
numbers=list(range(1,6))print(numbers)# 切片
players =['charles','martina','michael','florence','eli']print(players[0:3])print(players[:4])print(players[2:])print(players[-3:])#输出名单上的最后三名队员# 遍历切片 for player in players[:3]:print(player.title())# 复制列表
friend_foods = my_foods[:]# 元组"""列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网 站的用户列表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修改的元素, 元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组。 """# 元组看起来犹如列表,但使用圆括号而不是方括号来标识。
dimensions =(200,50)print(dimensions[0])print(dimensions[1])# 遍历
dimensions =(200,50)for dimension in dimensions:print(dimension)
if语句
for car in cars:if car =='bmw':print(car.upper())else:print(car.title())# 要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一; 使用or检查多个条件 if age <4:print("Your admission cost is $0.")elif age <18:print("Your admission cost is $5.")else:print("Your admission cost is $10.")# 有时候必须检查你关心的所有条件,连续使用多个if
字典
# 在Python中,字典是一系列键—值对。
alien_0 ={'color':'green','points':5}print(alien_0['color'])# 添加键—值对
alien_0 ={'color':'green','points':5}
alien_0['x_position']=0# 先使用一对 空的花括号定义一个字典,再分行添加各个键—值对。
alien_0 ={}
alien_0['color']='green'
alien_0['points']=5# 修改字典中的值
alien_0['color']='yellow'# 删除键—值对 del alien_0['points']# 遍历字典
user_0 ={'username':'efermi','first':'enrico','last':'fermi',}for key, value in user_0.items():print("\nKey: "+ key)print("Value: "+ value)# 遍历字典中的所有键,方法keys()很有用。for name in favorite_languages.keys():print(name.title())# 遍历字典中的所有值,可使用方法values().for language in favorite_languages.values():print(language.title())"""为剔除重复项,可使用集合(set)。 集合类似于列表,但每个元素都必须是独一无二的: """for language inset(favorite_languages.values()):print(language.title())# 字典列表
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)# 在字典中存储列表
pizza ={'crust':'thick','toppings':['mushrooms','extra cheese'],}# 在字典中存储字典
users ={'aeinstein':{'first':'albert','last':'einstein','location':'princeton',},'mcurie':{'first':'marie','last':'curie','location':'paris',},}
用户输入和while循环
message =input("Tell me something, and I will repeat it back to you: ")# 类型转换:int()str()float()# 如果你使用的是Python 2.7,应使用函数raw_input()来提示用户输入。# 使用while 循环 while message !='quit':
message =input(prompt)print(message)# 使用break 退出循环 ,在循环中使用 continue # 删除包含特定值的所有列表元素
pets =['dog','cat','dog','goldfish','cat','rabbit','cat']print(pets)while'cat'in pets:
pets.remove('cat')
函 数
# 向函数传递信息 defgreet_user(username):"""显示简单的问候语"""print("Hello, "+ username.title()+"!")# 关键字实参 """关键字实参让你无需考虑函 数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。 """defdescribe_pet(animal_type, pet_name):"""显示宠物的信息"""print("\nI have a "+ animal_type +".")print("My "+ animal_type +"'s name is "+ pet_name.title()+".") describe_pet(animal_type='hamster', pet_name='harry')# 函数可返回任何类型的值,包括列表和字典等较复杂的数据结构# 传递列表defgreet_users(names):"""向列表中的每位用户都发出简单的问候"""for name in names:
msg ="Hello, "+ name.title()+"!"print(msg)"""将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永 久性的,这让你能够高效地处理大量的数据"""defprint_models(unprinted_designs, completed_models):""" 模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中 """while unprinted_designs:
current_design = unprinted_designs.pop()# 模拟根据设计制作3D打印模型的过程 print("Printing model: "+ current_design)
completed_models.append(current_design)# 传递任意数量的实参 # 函数只有一个形参*toppings,但不管调用语句提供了多少实参,这个形参都将它们 统统收入囊中defmake_pizza(*toppings):"""打印顾客点的所有配料"""print(toppings)# 使用任意数量的关键字实参 """有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种 情况下,可将函数编写成能够接受任意数量的键—值对——调用语句提供了多少就接受多少。
形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所 有名称—值对都封装到这个字典中"""defbuild_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')# 使用as 给函数指定别名 from pizza import make_pizza as mp
# 导入模块中的所有函数 # 使用星号(*)运算符可让Python导入模块中的所有函数from pizza import*
类
# 根据约定,在Python中,首字母大写的名称指的是类classDog():"""一次模拟小狗的简单尝试"""def__init__(self, name, age):"""self必不可少,还必须位于其他形参的前面。""""""初始化属性name和age"""
self.name = name
self.age = age
defsit(self):"""模拟小狗被命令时蹲下"""print(self.name.title()+" is now sitting.")defroll_over(self):"""模拟小狗被命令时打滚"""print(self.name.title()+" rolled over!")# 在Python 2.7中创建类时,需要做细微的修改——在括号内包含单词object: classClassName(object):# 调用方法
my_dog = Dog('willie',6)# 实例化
my_dog.sit()# 调用sit()方法#-------------继承----------------------# 子类的方法__init__() classElectricCar(Car):"""电动汽车的独特之处"""def__init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year)"""的super()是一个特殊函数,帮助Python将父类和子类关联起来。这行代码让Python调用 ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。父类也称为超 类(superclass),名称super因此而得名"""# 在Python 2.7中,继承语法稍有不同,ElectricCar类的定义类似于下面这样: classCar(object):def__init__(self, make, model, year):-snip --classElectricCar(Car):def__init__(self, make, model, year):super(ElectricCar, self).__init__(make, model, year)# Python标准库 # OrderedDict实例的行为 几乎与字典相同,区别只在于记录了键—值对的添加顺序。 from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen']='python'
favorite_languages['sarah']='c'
favorite_languages['edward']='ruby'
favorite_languages['phil']='python'for name, language in favorite_languages.items():print(name.title()+"'s favorite language is "+ language.title()+".")