print("Hello")
# 变量的使用
message = "hello"
print(message)
# test 2-1
message="simple hello"
print(message)
# test 2-20
message = "hello"
print(message)
message = "change"
print(message)
# 首字母大写
name = "love you"
print(name.title())
name = name.title()
print(name)
#全部字母大写
print(name.upper())
#全部字母小写
print(name.lower())
#拼接字符串
first = "love"
last = "you"
full = first +" " + last
print(full)
制表符 \t
换行符 \n
# Python能够找出字符串开头和末尾多余的空白。要确保字符串末尾没有空白,可使用方法rstrip()
name = "pig "
print(name)
print(name.rstrip())
print(name)
# 将空格去掉后存入新的变量 进行保存
name1 = name.rstrip()
print(name1)
#剔除字符串开头的空白和字符串两端的空白
name = " hahha"
name.lstrip()
name.strip()
#在python 2中
print "hello "
# test 2-3
name = "Li"
print("hello "+name)
# test 2-4
name = "li Li li"
print(name)
print(name.lower())
print(name.upper())
print(name.title())
# test 2-5
print('Albert Einstein oncesaid,"Apersonwho never madea mistake never tried anything new."')
# test 2-6
famous_person = "Albert Einstein"
message = "Apersonwho never madea mistake never tried anything new."
print(famous_person + ' once said, "' + message+ '"')
# test 2-7
name = " Li \n\tli \n li "
print(name)
print(name.lstrip())
print(name.rstrip())
print(name.strip())
print(3/2) ---->1.5
# 结果包含的小数位数可能是不确定的 0.30000000000000004
print(0.2+0.1)
# 类型错误
age = 23
message = "Happy " + age + "rd Birthday!"
print(message)
# 显式的指出将整数用作字符串
age = 23
message = "Happy " + str(age) + " rd birthday"
print(message)
# test 2-8
print(5+3)
print(10-2)
print(2*4)
print(8/1) #8.0
fav_col = "red"
message = "My favorite color is " + fav_col
print(message)
import this
#索引从0开始
bike = ['1a' ,'2b' ,'3c' ,'4d']
print(bike[0])
# test3-1
names = ['xiaoli','ling','xixi']
print(names[0].title())
print(names[1].title())
print(names[2].title())
# tset3-2
names = ['xiaoli','ling','xixi']
print(names[0].title()+" Hello")
print(names[1].title()+" Hello")
print(names[2].title()+" Hello")
# 修改列表元素
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
#在列表中添加元素
#在列表末尾添加元素
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
motorcycles = []
motorcycles.append('cu')
motorcycles.append('de')
motorcycles.append('ya')
print(motorcycles)
motorcycles = ['honda','yamaha','suzuki']
motorcycles.insert(0,'hello')
print(motorcycles)
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
# del motorcycles[0]
# print(motorcycles)
del motorcycles[1]
print(motorcycles)
#删除列表末尾元素
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycles = motorcycles.pop()
print(motorcycles)
print(poped_motorcycles)
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycles = motorcycles.pop(0)
print(motorcycles)
print(poped_motorcycles)
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.remove('yamaha')
print(motorcycles)
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
too_expensive = 'yamaha'
motorcycles.remove(too_expensive)
print(motorcycles)
# test3-4
invest_person = ['ling','xixi','xiaowu']
print('I want to invest '+ invest_person[0]+' and '+ invest_person[1]+' and '+ invest_person[2])
# test 3-5
print(invest_person[1] + " cannot come")
invest_person[1] = 'xiaoqu'
print('I want to invest '+ invest_person[0]+' and '+ invest_person[1]+' and '+ invest_person[2])
# test 3-6
print("I find a bigger table")
invest_person.insert(0,'xinxin')
invest_person.insert(2,'jiajia')
invest_person.append('teng')
print('I want to invest '+ invest_person[0]+' and '+ invest_person[1]+' and '+ invest_person[2]+' and '+ invest_person[3]+' and '+ invest_person[4]+' and '+ invest_person[5])
# test 3-7
print('Sorry, I only can invest two people')
del_person = invest_person.pop(5)
print(del_person + " Sorry")
del_person = invest_person.pop(4)
print(del_person + " Sorry")
del_person = invest_person.pop(3)
print(del_person + " Sorry")
del_person = invest_person.pop(2)
print(del_person + " Sorry")
print(invest_person[0] + ' come')
print(invest_person[1] + ' come')
del invest_person[1]
del invest_person[0]
print(invest_person)
# sort() 对列表进行永久排序
cars = ['buw','audi','toyaota','subaru']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)
cars = ['buw','audi','toyaota','subaru']
print(sorted(cars))
print(cars)
# 倒置列表
cars = ['buw','audi','toyaota','subaru']
print(cars)
cars.reverse()
print(cars)
cars = ['buw','audi','toyaota','subaru']
print(len(cars))
# test3-8
wanted_place = ['dalian','shenyang','beijing','hangzhou','shenzhen']
print(wanted_place)
print(sorted(wanted_place))
print(wanted_place)
print(sorted(wanted_place,reverse=True))
print(wanted_place)
wanted_place.reverse()
print(wanted_place)
wanted_place.reverse()
print(wanted_place)
wanted_place.sort()
print(wanted_place)
wanted_place.sort(reverse=True)
print(wanted_place)
su = ['one']
print(su[-1])
# 操作列表
# 遍历整个列表
magicisans = ['alice','david','carolina']
for magicisan in magicisans:
print(magicisan)
magicisans = ['alice','david','carolina']
for magicisan in magicisans:
print(magicisan.title() + ",that was a great trick!")
print("I can't wait to see your next trick, " + magicisan.title() +" \n")
print("Thank you, everyone.")
# test 4-1 想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for 循环将每种比萨的名称都打印出来。
# 修改这个for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“I like pepperoni pizza”。
# 在程序末尾添加一行代码,它不在for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“I really love pizza!”。
pizzas = ['meet','fruit','veg']
for pizza in pizzas:
print(pizza)
print("I love "+ pizza + ' \n')
print("I love pizza! " + pizzas[0] + " " + pizzas[1]+ " "+pizzas[2])
# test 4-2 想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for 循环将每种动物的名称都打印出来。
#修改这个程序,使其针对每种动物都打印一个句子,如“Adogwould makea great pet”。
#在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“Any oftheseanimals would makea great pet!”这样的句子。
animals =['cat','dog','pig']
for animail in animals:
print(animail)
print('A '+animail+' would make a great pet')
print('Any if these animals would make a great pet')
# 生成数字 range()
for value in range(1,5):
print(value)
# 创建数字列表
numbers = list(range(1,6))
print(numbers)
# 打印1-10内的偶数
even_numbers = list(range(2,11,2))
print(even_numbers)
# 将前十个整数的平方加入一个列表
squares = []
for value in range(1,11):
# square = value ** 2
# squares.append(square)
squares.append(value**2)
print(squares)
# 对数字列表执行简单的统计计算
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
# 列表解析
squares = [value **2 for value in range(1,11)]
print(squares)
# test 4-3 使用一个for 循环打印数字1~20(含)
for value in range(1,21):
print(value)
# test 4-4创建一个列表,其中包含数字1~1 000 000,
# 再使用一个for 循环将这些数字打印出来(如果输出的时间太长,按Ctrl+ C停止输出,或关闭输出窗口)
for value in range(1,1000001):
print(value)
# test 4-5创建一个列表,其中包含数字1~1 000 000,再使用min() 和max() 核实该列表确实是从1开始,到1 000 000结束的。
# 另外,对这个列表调用函数sum() ,看看Python将一百万个数字相加需要多长时间。
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
# test 4-6 通过给函数range() 指定第三个参数来创建一个列表,其中包含1~20的奇数;
# 再使用一个for 循环将这些数字都打印出来
numbers = list(range(1,21,2))
for number in numbers:
print(number)
# test 4-7 创建一个列表,其中包含3~30内能被3整除的数字;
# 再使用一个for 循环将这个列表中的数字都打印出来
numbers = list(range(3,31,3))
for number in numbers:
print(number)
# test 4-8 将同一个数字乘三次称为立方。例如,在Python中,2的立方用2**3 表示
# 请创建一个列表,其中包含前10个整数(即1~10)的立方
# 再使用一个for循环将这些立方数都打印出来
numbers = []
for value in range(1,11):
numbers.append(value ** 3)
print(numbers)
# test 4-9 使用列表解析生成一个列表,其中包含前10个整数的立方
number = [value ** 3 for value in range(1,11)]
print(number)
--------------------------------------------------------------------------------------------
# 处理列表的部分元素 --切片
players = ['chars','martina','michael','florence','eli']
# print(players[0:3])
# print(players[1:4])
# print(players[:4])
# print(players[2:])
# print(players[-3:])
# 遍历切片
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
# 复制列表
my_foods = ['pizza','falafel','carrot']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append("ice cream")
print(my_foods)
print(friend_foods)
# 错误复制 将新变量关联到原列表 即两个变量指向一个列表
my_foods = ['pizza','falafel','carrot']
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append("ice cream")
print(my_foods)
print(friend_foods)
# test 4-10 选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
# 打印消息“Thefirst threeitems in thelistare:”,再使用切片来打印列表的前三个元素。
# 打印消息“Threeitems fromthe middle ofthelistare:”,再使用切片来打印列表中间的三个元素。
# 打印消息“Thelast threeitems in thelistare:”,再使用切片来打印列表末尾的三个元素。
from collections import namedtuple
from typing import ClassVar
my_foods = ['pizza','falafel','carrot','ice_cream','cannoli']
print("Thefirst threeitems in thelistare:")
for food in my_foods[0:3]:
print(food)
print("Threeitems fromthe middle ofthelistare:")
for food in my_foods[2:5]:
print(food)
print("Thelast threeitems in thelistare:")
for food in my_foods[-3:]:
print(food)
# test 4-11在你为完成练习4-1而编写的程序中,创建比萨列表的副本,并将其存储到变量friend_pizzas 中,
# 再完成如下任务。在原来的比萨列表中添加一种比萨。
# 在列表friend_pizzas 中添加另一种比萨。
# 核实你有两个不同的列表。为此,打印消息“My favorite pizzasare:”,
# 再使用一个for 循环来打印第一个列表;
# 打印消息“My friend's favorite pizzasare:”,
# 再使用一个for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。
pizzas = ['meet','fruit','veg']
friend_pizza = pizzas[:]
friend_pizza.append('ice')
print("My favorite pizza are ")
for pizza in pizzas:
print(pizza)
print("My ffiend like")
for friend_pizza in friend_pizza:
print(friend_pizza)
# 元组 不可变的列表
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
# 元组不能赋值修改
# dimensions[0]=250
# print(dimensions[0])
# 元组遍历
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
# 重新定义整个元组
dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400,50)
print("Modified dimensions")
for dimension in dimensions:
print(dimension)
# test 4-13 有一家自助式餐馆,只提供五种简单的食品。请想出五种简单的食品,并将其存储在一个元组中。
# 使用一个for 循环将该餐馆提供的五种食品都打印出来。
# 尝试修改其中的一个元素,核实Python确实会拒绝你这样做。
# 餐馆调整了菜单,替换了它提供的其中两种食品。
# 请编写一个这样的代码块:给元组变量赋值,并使用一个for 循环将新元组的每个元素都打印出来。
foods = ('ice','water','meet','pizza','egg')
print("The food is :")
for food in foods:
print(food)
foods = ('ice','veg','meet','milk','egg')
print("The new food is :")
for food in foods:
print(food)
---------------------------------------------------------------------12:09--------------------
cars =['audi','bnw','subaru','toyota']
for car in cars:
if car == 'bnw':
print(car.upper())
else:
print(car.title())
car = 'Bnw'
print(car=='Bnw')
print(car=='xiaozhu')
print(car.lower()=='bnw')
request_topping = 'mushrooms'
if request_topping != 'anchovies':
print("Hold the achovies")
age = 18
print(age==18)
print(age!=20)
# 检查多个条件
and or
#检查特定值是否包含在列表中 in /not in
requested_toppings = ['mushrooms','onions','pineeapple']
print('mushrooms'in requested_toppings)
print("ice"in requested_toppings)
banned_users =['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
print(user.title()+ ", you can post a reponse if you wish ")
# 布尔表达式
game_active = True
can_edit = False
# test 5-1 编写一系列条件测试;将每个测试以及你对其结果的预测和实际结果都打印出来。
car = 'subaru'
print('Is car == "subaru"? I predict True')
print(car == 'subaru')
print('Is car == "audi"? I predict False')
print(car == 'audi')
# test 5-2 更多的条件测试
print('sa'=='Sa')
sa = 'sa'
Sa = 'Sa'
print(sa==Sa.lower())
fruits = ['apple','pear']
if 'apple' in fruits:
print("aplle in")
if 'egg' not in fruits:
print("egg not in")
age = 17
if age >= 18:
print('You are old enough to vote!')
print('Have you registered to vote yet')
else:
print('Sorry ,you are too young to vote')
age = 12
if age <4:
print("You admission cost is 0")
elif age < 18:
print("You admission cost is 5")
else:
print("You admission cost is 10")
age = 12
if age <4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
# else:
# price = 5
elif age >= 65:
price = 5
print("You admission cost is "+ str(price))
-----------------------------------------------------------------14:15-----------------
# test 5-3
alien_color = 'green'
if alien_color = "green":
print("You get five points")
elif alien_color="red":
print("You get 15 points")
else:
print("You get 10 points")
# test 5-6 判断处于人生的那个阶段
age = 15
if age <2:
print("baby")
elif age >= 2 and age <4:
print("walk")
elif age >=4 and age <14:
print("children")
elif age >=14 and age <20:
print("younger")
elif age >=20 and age <65:
print("adult")
else:
print("older")
requested_toppings =['mushrooms','green pepers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green pepers':
print("Sorry,we are out of green pepers right now")
else:
print("Adding "+requested_topping)
print("Finished making your pizza")
available_toppings = ['mushrooms','olives','green pepers','pepperoni','pineapple','extra cheese']
requested_toppings =['mushrooms','french fries','extra cheese']
for requested_mapping in requested_toppings:
if requested_mapping in available_toppings:
print("exist "+requested_mapping)
else:
print("Sorry,we don't have "+ requested_mapping)
print("Finished making your pizza")
# test 5-8创建一个至少包含5个用户名的列表,且其中一个用户名为'admin' 。
# 想象你要编写代码,在每位用户登录网站后都打印一条问候消息。
# 遍历用户名列表,并向每位用户打印一条问候消息。
# 如果用户名为'admin' ,就打印一条特殊的问候消息,
# 如“Hello admin, would you liketo seeastatus report?”。
# 否则,打印一条普通的问候消息,如“Hello Eric, thank you for logging in again”。
names =['admin','haha','xiaoli','pig','rabbit']
for name in names:
if name == 'admin':
print("Hello "+name+" ,would you like to see a status report?")
else:
print("Hello "+name+" ,thank you for logging in again")
# test 5-9
# names =['admin','haha','xiaoli','pig','rabbit']
names=[]
if names:
for name in names:
if name == 'admin':
print("Hello "+name+" ,would you like to see a status report?")
else:
print("Hello "+name+" ,thank you for logging in again")
else:
print("We need to find some users")
# test 5-10 按下面的说明编写一个程序,模拟网站确保每位用户的用户名都独一无二的方式。
# 创建一个至少包含5个用户名的列表,并将其命名为current_users 。
# 再创建一个包含5个用户名的列表,将其命名为new_users
# 并确保其中有一两个用户名也包含在列表current_users 中。
# 遍历列表new_users ,对于其中的每个用户名,都检查它是否已被使用。
# 如果是这样,就打印一条消息,指出需要输入别的用户名;否则,打印一条消息,指出这个用户名未被使用。
# 确保比较时不区分大消息;换句话说,如果用户名'John' 已被使用,应拒绝用户名'JOHN' 。
current_users =['alin','bro','chaos','david','fav']
current_userslower=[]
for current_user in current_users:
current_userslower.append(current_user.lower())
new_users =['hff','alin','think','Chaos','jack']
for new_user in new_users:
if new_user.lower() in current_users:
print(new_user+" exist")
else:
print(new_user+" unused")
# test 5-11 :序数表示位置,如1st和2nd。大多数序数都以th结尾,只有1、2和3例外。
# 在一个列表中存储数字1~9。遍历这个列表。
# 在循环中使用一个if-elif-else 结构,以打印每个数字对应的序数。
# 输出内容应为1st 、2nd 、3rd 、4th 、5th 、6th 、7th 、8th 和9th ,但每个序数都独占一行。
numbers =list(range(1,10))
for number in numbers:
if number == 1:
print(str(number)+'st')
elif number == 2:
print(str(number)+'nd')
elif number == 3:
print(str(number)+'rd')
else:
print(str(number)+'th')
--------------------------------------------------------------------------------15:38----
alien_0={'color':'green','point':5}
print(alien_0['color'])
print(alien_0['point'])
#字典是一系列的键值对 字典放在{}中
#访问与键相关联的值 可依次指定字典名和[]内的键
alien_0={'color':'green','point':5}
print(alien_0)
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
alien_0 ={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
alien_0 ={'color':'green'}
alien_0['color']='yellow'
print(alien_0)
alien_0 ={'x_position':0,'y_positon':25,'speed':'medium'}
print("Origin x_position : -"+str(alien_0['x_position']))
if alien_0['speed']=='slow':
x_increment =1
elif alien_0['speed']=='medium':
x_increment=2
else:
x_increment=3
alien_0['x_position']=alien_0['x_position']+x_increment
print("New x_position: "+str(alien_0['x_position']))
# 删除键值对
alien_0={'color':'green','point':5}
del alien_0['point']
print(alien_0)
#使用字典存储众多对象的同一种信息
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
print("Sarah's favorite language is " +favorite_language['sarah'].title())
# test6-1 :使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。
# 该字典应包含键first_name 、last_name 、age 和city 。
# 将存储在该字典中的每项信息都打印出来
person_information = {'first_name':'Li','last_name':'li','age':'18','city':'beijing'}
print(person_information)
# test 6-2 :使用一个字典来存储一些人喜欢的数字。
# 请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并
# 将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字
numbers = {
'li':'1',
'zhang':'2',
'xixi':'3',
'qu':'6',
'gu':'9'
}
print(numbers)
# test6-3 词汇表
vol ={
'cat':'small animal',
'apple':'a kind of fruit'
}
print("cat means "+vol['cat'])
print('apple means '+vol['apple'])
user ={
'username':'efermi',
'first':'fermi',
'last':'enrico'
}
for key,value in user.items():
print("\nKey: "+key)
print("Value: "+value)
-------------------------------------------------------------16:36-----------------
# 遍历字典
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
# for name,language in favorite_language.items():
# print(name.title() +" 's favorite language is "+language.title())
# for name in favorite_language.keys():
# print(name.title())
# for name in favorite_language:
# print(name.title())
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
#遍历字典所有键
firends =['chen','sarah']
for name in favorite_language.keys():
print(name.title())
if name in firends:
print(" hi "+ name.title()+ " ,I see your favoite language is "+
favorite_language[name].title())
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
if 'erin' not in favorite_language.keys():
print("Erin,please take our poll")
# 按顺序遍历字典中的所有键
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
for name in sorted(favorite_language.keys()):
print(name.title()+' thank you for taking the poll')
# 遍历字典中的所有值
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
print("The following languages have been mentioned: ")
for language in favorite_language.values():
print(language.title())
# 集合 类似于列表 但是元素都是独一无二的
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
print("The following languages have been mentioned: ")
for lanuage in set(favorite_language.values()):
print(lanuage.title())
# test 6-4 词汇表
words ={
'cat':'cute animal',
'pig':'fat animal',
'dog':'kind of animal'
}
for word,mean in words.items():
print(word+' means '+mean)
# test 6-5 河流替代成词汇
words ={
'cat':'cute animal',
'pig':'fat animal',
'dog':'kind of animal'
}
for word,mean in words.items():
print(word+' means '+mean)
for word in words.keys():
print(word)
for mean in words.values():
print(mean)
# test 6-6
favorite_language ={
'jen':'python',
'sarah':'c',
'edward':'ruby'
}
people= ['enheng','jen']
for person in favorite_language.keys():
if person in people:
print(person+" Thank You")
else:
print(person+" Invite you ")
-----------------------------------------------------------------------20:10------------
arrs =['zhu','tou','xiao','wu']
for arr in arrs:
print(arr)
arr = 'zhu'
for test in arr:
print(test)
# 字典列表 字典是{} 列表是[]
aline_0 = {'color':'green','point':5}
aline_1 = {'color':'yellow','point':10}
aline_2 = {'color':'red','point':15}
alines = [aline_0,aline_1,aline_2]
for aline in alines:
print(aline)
# range自动生成外星人
aliens = []
# 创建30个绿色的外星人
# for alien_number in list(range(30)):
for alien_number in range(30):
new_alien ={'color':'green','point':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("Total number of aliens :"+ str(len(aliens)))
# 修改成群结队的外星人
aliens = []
# 创建30个绿色的外星人
# for alien_number in list(range(30)):
for alien_number in range(30):
new_alien ={'color':'green','point':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['point'] ='10'
alien['speed'] = 'medium'
# elif alien['color'] == 'yellow'
for alien in aliens[0:5]:
print(alien)
# 在字典中存储列表 披萨:外皮类型和配料列表
pizza ={
'crust' :'thick',
'toppings':['mushrooms','extra cheese'],
}
print("You ordered a " +pizza["crust"]+" pizza with the following toppings")
for topping in pizza['toppings']:
print(topping)
favorite_language ={
'jen' :['python','ruby'],
'sarah':['c']
}
for name,languages in favorite_language.items():
print("\n"+name.title()+" like ")
for language in languages:
print(language.title())
# 在字典中存储字典
users ={
'aeinstein' :{
'first':'albert',
'last':'einstin',
'location':'princetion',
},
'bp' :{
'first':'marie',
'last':'curie',
'location':'paris',
}
}
for username,user_info in users.items():
print("Username : "+username)
full_name = user_info['first']+" "+user_info['last']
location =user_info['location']
print("\tFull name : "+full_name.title())
print("\tLocaton : "+location.title())
# test 6-7 :在为完成练习6-1而编写的程序中,再创建两个表示人的字典,
# 然后将这三个字典都存储在一个名为people 的列表中。
# 遍历这个列表,将其中每个人的所有信息都打印出来
person1_information = {'first_name':'Li','last_name':'li','age':'18','city':'beijing'}
person2_information = {'first_name':'ling','last_name':'ling','age':'19','city':'hainan'}
person3_information = {'first_name':'xi','last_name':'xi','age':'17','city':'hangzhou'}
people =[person1_information,person2_information,person3_information]
for person in people:
print(person)
# test 6-8 创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;
# 在每个字典中,包含宠物的类型及其主人的名字。
# 将这些字典存储在一个名为pets 的列表中,再遍历该列表,并将宠物的所有信息都打印出来
tengjiao ={
'type':'cat',
'load':'xiaoli'
}
xiaopang ={
'type':'bird',
'load':'xiaozhu'
}
pets =[tengjiao,xiaopang]
for pet in pets:
print(pet['type'])
print(pet['load'])
# test 6-9创建一个名为favorite_places 的字典。
# 在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。
# 为让这个练习更有趣些,可让一些朋友指出他们喜欢的几个地方。
# 遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来
favorite_places ={
'xiaoli':['beijing','hangzhou'],
'xiaozhu':['shenzhen']
}
for name,favorite_place in favorite_places.items():
print(name.title())
for place in favorite_place:
print("\t"+place)
# test 6-11城市 创建一个名为cities 的字典,其中将三个城市名用作键;
# 对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实
# 在表示每座城市的字典中,应包含country 、population 和fact 等键。
# 将每座城市的名字以及有关它们的信息都打印出来
cities ={
'beijing' :{
'country' :'China',
'population':'much',
'fact':'fast'
},
'changchun' :{
'country' :'China',
'population':'little',
'fact':'slow'
}
}
for name,information in cities.items():
print(name)
print("\t"+information['country'])
print("\t"+information['population'])
print("\t"+information['fact'])
-----------------------------------------------------------------------------------
#用户输入和while循环
message = input("Tell me something")
print(message)
name = input("please enter your name")
print("hello "+name)
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("hello "+name)
height = input("how tall are you , in inches")
height=int(height)
if height > 36:
print("You are tall enough to ride")
else:
print("You will able to ride when you are little older")
#求模运算符 两个数相除返回余数
print(4%3)
#可以利用%判断一个数是奇数还是偶数
number =input("Enter a number,and I will tall you if it is even or odd")
number = int(number)
if number%2 == 0:
print("\nThe number "+str(number)+" is even")
else:
print("\nThe number "+str(number)+" is odd.")
#python 2.7中,应使用raw_input()来提示用户输入
#7-1 编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,
# 如“LetmeseeifIcan find you a Subaru”
# message = input("what kind of cars do you want to rent")
# print("Let me see if I can find you a "+message)
#7-2编写一个程序,询问用户有多少人用餐。
# 如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌
number = input("How many people dou you have ")
number = int(number)
if number >8:
print("There is no room")
else:
print("Please come in")
#7-3让用户输入一个数字,并指出这个数字是否是10的整数倍
number = input("Please enter a number,I will guess ")
number = int(number)
if number % 10 == 0:
print("Yes.")
else:
print("No")
#for循环针对集合中的每个元素都一个代码块
#while循环不断的运行,直到指定的条件不满足
#从1数到5
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
promt = "\nTell me something, and I will repeat it back to you"
promt += "Enter 'quit' to end the program "
message = ""
while message != 'quit':
message = input(promt)
if message != 'quit':
print(message)
#如需要满足很多条件才能继续运行时,可以定义一个变量,
# 用于判断整个程序是否处于活动状态,这个变量就称为标志
promt = "\nTell me something, and I will repeat it back to you"
promt += "Enter 'quit' to end the program "
active = True
while active:
message = input(promt)
if message == 'quit':
active = False
else:
print(message)
promt = "\nTell me something, and I will repeat it back to you"
promt += "Enter 'quit' to end the program "
while True:
message = input(promt)
if message == 'quit':
break
else:
print(message)
promt = "\nTell me something, and I will repeat it back to you"
promt += "Enter 'quit' to end the program "
while True:
message = input(promt)
if message == 'quit':
continue
else:
print(message)
#只打印1-10的偶数
current_number = 0
while current_number < 10:
current_number += 1
if current_number %2 == 0:
print(current_number)
else:
continue
#验证用户
#首先创建一个待验证用户列表
#和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice','brain','candace']
confirmed_users = []
#验证每个用户,直到没有未验证用户为止
#将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("Verifying user: "+current_user.title())
confirmed_users.append(current_user)
#显示所有已验证的用户
print("\nThe following users have been confirmed;")
for confirmed_user in confirmed_users:
print(confirmed_user.title())
#删除列表中所有包含特定值的元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
#使用用户输入来填充字典
responses ={}
#设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
#提示输入被调查者的名字和回答
name = input("What is your name? ")
response = input("Which mountain would you like to climb someday ?")
#将答卷存储在字典中
responses[name] = response
#看看是否还有其他人要参加调查
repeat = input("Would you like to let another person respond")
if repeat == 'no':
polling_active = False
#调查结束 显示结果
print("\n----Poll Results-----")
for name,response in responses.items():
print(name + "would like to climb "+response)
--------------------------函数-----------------------------------------
def greet_user():
'''显示简单的问候语'''
print("hello")
greet_user()
#向函数传递信息
def greet_user(username):
'''显示简单的问候语'''
print("hello "+username.title())
greet_user('Xiaoli')
#函数定义的变量为形参 调用函数时传递给函数的信息时实参
# 传递实参---位置实参 基于实参的顺序
def describe_pet(animal_type,pet_name):
'''显示宠物的信息'''
print("I have a "+animal_type)
print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet('cat','tengjiao')
#函数调用中实参的顺序与函数定义中形参的顺序一致
def describe_pet(animal_type,pet_name):
'''显示宠物的信息'''
print("I have a "+animal_type)
print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet('cat','tengjiao')
describe_pet('dog','huilang')
#关键字实参 传递给函数的名称 值对
def describe_pet(animal_type,pet_name):
'''显示宠物的信息'''
print("I have a "+animal_type)
print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet(animal_type="cat",pet_name="harry")
#给函数的形参指定默认值
def describe_pet(animal_type,pet_name="tengjiao"):
'''显示宠物的信息'''
print("I have a "+animal_type)
print("My "+animal_type+"'s name is "+pet_name.title())
describe_pet(animal_type="cat")
#返回值 return语句将值返回到调用函数的代码行
def get_formatted_name(first_name,last_name):
'''返回整洁的姓名'''
full_name = first_name + ' '+last_name
return full_name.title()
musician = get_formatted_name('lili','haha')
print(musician)
def get_formatted_name(first_name,middle_name,last_name):
'''返回整洁的姓名'''
full_name = first_name + ' '+middle_name+' '+last_name
return full_name.title()
musician = get_formatted_name('lili','haha','tee')
print(musician)
#让实参变成是可选的
#有的人没有中间名 给实参一个默认值-空字符串,并且将其移到形参列表的末尾
def get_formatted_name(first_name,last_name,middle_name=' '):
'''返回整洁的姓名'''
full_name = first_name + ' '+middle_name+' '+last_name
return full_name.title()
musician = get_formatted_name('lili','haha')
print(musician)
#函数可以返回任何类型的值 包括列表和字典
def build_person(first_name,last_name):
'''返回一个字典,其中包含有关一个人的信息'''
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
#修改函数中字典的值
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',10)
print(musician)
#结合使用函数和while循环
def get_formatted_name(first_name,last_name):
'''返回整洁的姓名'''
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name ")
print("enter 'q' at any time to quit ")
f_name = input("Please input your First name ")
if f_name == 'q':
break
l_name = input("Please input your Last name ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name,l_name)
print("\nHello " + formatted_name + "!")
# 向函数传递列表
def greet_users(names):
''' 向列表中的每位用户都发出简单的问候'''
for name in names:
msg = "Hello, "+name.title()+"!"
print(msg)
usernames = ['Lisa','Suria','Wiki']
greet_users(usernames)
#在函数中修改列表
#首先不适用函数情况模拟将一个列表打印后移到另一个列表
#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models =[]
#模拟打印每个设计,直到没有未打印的设计为止
#打印每个设计后,都要将其移到列表completed_models
while unprinted_designs:
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: "+ current_design)
completed_models.append(current_design)
#显示打印好的所有模型
print("\nThe following models have been printed")
for completed_model in completed_models:
print(completed_model)
#重新组织代码 使每个函数只完成一样工作
def print_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)
def show_completed_models(completed_models):
#显示打印好的所有模型
print("\nThe following models have been printed")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models =[]
print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)
#禁止函数修改列表 将列表的副本传递给函数
#重新组织代码 使每个函数只完成一样工作
def print_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)
def show_completed_models(completed_models):
#显示打印好的所有模型
print("\nThe following models have been printed")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case','robot pendant','dodecahedron']
completed_models =[]
print_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
print("The following is origin unprinted_designs ")
for unprinted_desgin in unprinted_designs:
print(unprinted_desgin)
#传递任意数量的实参 *创建一个空元祖,并将收到的所有值封装到这个元祖中
def make_pizza(*toppings):
'''打印顾客点的所有配料'''
print("\nMaking a pizza with the following toppings: ")
# print(toppings)
for topping in toppings:
print('- '+topping)
make_pizza('pepperoni')
make_pizza('mushrooms','green pepers','extra cheese')
#结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):
'''打印顾客点的所有配料'''
print("\nMaking a "+ str(size)+" pizza with the following toppings: ")
# print(toppings)
for topping in toppings:
print('- '+topping)
make_pizza(16,'pepperoni')
make_pizza(25,'mushrooms','green pepers','extra cheese')
#使用任意数量的关键字实参 可将函数编写成能够接受任意数量的键值对
#形参**user_info中的两个星号创建一个空字典 并将收到的所有名称--值对都封装到这个字典中
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='physices')
print(user_profile)
#将函数存储在模块中
#导入整个模块
import pizza
#导入特定的函数
from module_name import function_name
#使用as给函数指定别名
from pizza import make_pizza as mp
#使用as给模块指定别名
import pizza as p
#导入模块中的所有函数
from pizza import *
#给形参指定默认值时,等号两边不要有空格
def function_name(parameter_0,parameter_1='default value')
#对于函数调用中的关键字实参,也遵循这种规定
function_name(value_0,parameter_1='value')
#类
#创建Dog类 表示的不是特定的小狗,而是任何小狗
#类中的函数叫做方法
class Dog():
'''一次模拟小狗的简单尝试'''
def __init__(self,name,age):
'''初始化属性name和age'''
self.name = name
self.age = age
def sit(self):
'''模拟小狗被命令时蹲下'''
print(self.name.title() + " is now sitting")
def roll_over(self):
'''模拟小狗被命令时打滚'''
print(self.name.title() + " rolled over! ")
#创建特定的实例
my_dog = Dog("Tengjiao",1)
# print("My dog's name is "+my_dog.name.title())
# print("My dog is " + str(my_dog.age) + " years old")
#调用方法
my_dog.sit()
my_dog.roll_over()
#创建多个实例
my_dog = Dog("Tengjiao",1)
your_dog = Dog('lucky',2)
print("My dog's name is "+my_dog.name.title())
print("My dog is " + str(my_dog.age) + " years old")
my_dog.sit()
print("\nYour dog's name is "+your_dog.name.title() + ".")
print("Your dog is " + str(your_dog.age))
class Car():
'''一次模拟汽车的简单尝试'''
def __init__(self,make,model,year):
'''初始化描述汽车的属性 将形参存储在根据这个类创建的实例的属性中'''
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
'''返回整洁的描述性信息'''
long_name = str(self.year) + ' '+self.make +' '+self.model
return long_name.title()
my_new_car = Car('audi','a8',2022)
print(my_new_car.get_descriptive_name())
#给属性指定默认值
class Car():
'''一次模拟汽车的简单尝试'''
def __init__(self,make,model,year):
'''初始化描述汽车的属性 将形参存储在根据这个类创建的实例的属性中'''
self.make = make
self.model = model
self.year = year
# self.odometer_reading = 0
self.odometer_reading = 80
def get_descriptive_name(self):
'''返回整洁的描述性信息'''
long_name = str(self.year) + ' '+self.make +' '+self.model
return long_name.title()
def read_odometer(self):
'''打印一条指出汽车里程的信息'''
print("This car has "+str(self.odometer_reading)+" miles on it")
#通过方法修改属性的值
def update_odometer(self,mileage):
'''将里程表读数设置成指定的值'''
# self.odometer_reading = mileage
#禁止将里程表读数往回调
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cann't roll back an odometer")
#通过方法传递增量
def increment_odometer(self,miles):
'''将里程表读数增加指定的量'''
if miles >= 0:
self.odometer_reading += miles
else:
print("You cann't roll back an odometer")
my_new_car = Car('audi','a8',2022)
print(my_new_car.get_descriptive_name())
#直接修改属性的值
# my_new_car.odometer_reading = 23
#通过方法修改属性的值
# my_new_car.update_odometer(52)
#通过方法对属性的值进行递增
my_new_car.increment_odometer(15)
my_new_car.read_odometer()
#继承 子类自动获得另一个类(父类)的所有属性和方法
class Car():
'''一次模拟汽车的简单尝试'''
def __init__(self,make,model,year):
'''初始化描述汽车的属性 将形参存储在根据这个类创建的实例的属性中'''
self.make = make
self.model = model
self.year = year
# self.odometer_reading = 0
self.odometer_reading = 80
def get_descriptive_name(self):
'''返回整洁的描述性信息'''
long_name = str(self.year) + ' '+self.make +' '+self.model
return long_name.title()
def read_odometer(self):
'''打印一条指出汽车里程的信息'''
print("This car has "+str(self.odometer_reading)+" miles on it")
#通过方法修改属性的值
def update_odometer(self,mileage):
'''将里程表读数设置成指定的值'''
# self.odometer_reading = mileage
#禁止将里程表读数往回调
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cann't roll back an odometer")
#通过方法传递增量
def increment_odometer(self,miles):
'''将里程表读数增加指定的量'''
if miles >= 0:
self.odometer_reading += miles
else:
print("You cann't roll back an odometer")
class ElectricCar(Car):
'''电动汽车的独特之处'''
def __init__(self, make, model, year):
'''初始化父类的属性'''
super().__init__(make, model, year)
#初始化电动汽车特有的属性
self.battery_size = 70
def describe_battery(self):
'''打印一条描述电瓶容量的消息'''
print("This car has a "+str(self.battery_size)+" -kWh battery.")
my_tesla = ElectricCar('tesla','model s',2022)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
#重写父类的方法 -----重新定义父类的函数
#将实例用作属性
class Car():
'''一次模拟汽车的简单尝试'''
def __init__(self,make,model,year):
'''初始化描述汽车的属性 将形参存储在根据这个类创建的实例的属性中'''
self.make = make
self.model = model
self.year = year
# self.odometer_reading = 0
self.odometer_reading = 80
def get_descriptive_name(self):
'''返回整洁的描述性信息'''
long_name = str(self.year) + ' '+self.make +' '+self.model
return long_name.title()
def read_odometer(self):
'''打印一条指出汽车里程的信息'''
print("This car has "+str(self.odometer_reading)+" miles on it")
#通过方法修改属性的值
def update_odometer(self,mileage):
'''将里程表读数设置成指定的值'''
# self.odometer_reading = mileage
#禁止将里程表读数往回调
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You cann't roll back an odometer")
#通过方法传递增量
def increment_odometer(self,miles):
'''将里程表读数增加指定的量'''
if miles >= 0:
self.odometer_reading += miles
else:
print("You cann't roll back an odometer")
class Battery():
'''一次模拟电动汽车电瓶的简单尝试'''
def __init__(self,battery_size = 70):
'''初始化电瓶的属性'''
self.battery_size = battery_size
def descript_battery(self):
'''打印一条描述电瓶容量的消息'''
print("This car has a "+str(self.battery_size)+" -kWh battery")
def get_range(self):
'''打印一条消息,指出电瓶的续航里程'''
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approximately "+str(range)
message += " miles on a full charge"
print(message)
class ElectricCar(Car):
'''电动汽车的独特之处'''
def __init__(self, make, model, year):
super().__init__(make, model, year)
#ElectricCar实例都包含一个自动创建的Battery实例
self.battery = Battery()
my_tesla = ElectricCar('tesla','model s',2022)
print(my_tesla.get_descriptive_name())
my_tesla.battery.descript_battery()
my_tesla.battery.get_range()
#导入类
#导入单个类 将Car类存储在car.py的模块中
from car import Car
#可以在一个模块中存储多个类 也可以从一个模块中导入多个类
#也可以导入整个模块 然后使用句号表示法访问需要的类
#导入模块中的所有类
from module_name impot *
#文件和异常
#在当前执行的文件所在的目录中查找指定的文件
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
#可使用相对文件路径来打开文件夹中的文件
#在Linux和OS 中
# with open('text_files/filename.txt') as file_object:
#在windows使用反斜杠\
# with open('text_files\filename.txt') as file_object:
#可使用绝对路径 即计算机中准确的位置
#逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_oject:
for line in file_oject:
print(line.rstrip())
#此时空白行增加 此时消除多余的空白行 使用rstrip()
#创建一个包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
# #使用文件的内容
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string =' '
for line in lines:
pi_string += line.rstrip()
print(pi_string)
print(len(pi_string))
#读取文本文件时,Python将其中的所有文本都解读成字符串
#读取的是数字,并要将其作为数值使用 就必须使用int()将其转换为整数 或float()将其转换为浮点数
#圆周率包含你的生日吗
birthday = input("Enter your birthday, in the form mmddyy ")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi ")
else:
print("Your birthday does not appear in the first million digits of pi ")
# 写入文件
# 写入空文件 open()提供两个实参 第一个实参是要打开的文件的名称
# 第二个实参'w'即写入模式 如果省略模式实参即以只读模式打开文件
# 读取模式'r' 写入模式'w' 附加模式'a' 写入文件的模式'r+'
filename = 'programming.txt'
with open(filename,'w') as file_object:
file_object.write("I love programming\n")
file_object.write("I love creating new games\n")
#如果要给文件添加内容,而不是覆盖原有的内容 可以附加模式打开文件
filename = 'programming.txt'
with open(filename,'a') as file_object:
file_object.write("I also love finding in large datasets\n")
file_object.write("I love creating apps that can run in a brower\n")
#异常 ZeroDivisionError是一个异常对象
print(5/0)
# Traceback (most recent call last):
# File "h:/Python/Python从入门到实践/test1.py", line 1646, in <module>
# print(5/0)
# ZeroDivisionError: division by zero
#使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
#使用异常避免崩溃
print("Give me two numbers,and I'll divide them")
print("Enter 'q' to quit")
while(True):
first_number = input("First number : ")
if first_number == 'q':
break
second_number = input("Second number : ")
if second_number == 'q':
break
try:
'''将可能引发异常的代码放在try中'''
answer = int(first_number) / int(second_number)
# print(answer)
except ZeroDivisionError:
print("You can't divide bby 0! ")
else:
'''try代码成功执行时才需要运行的代码'''
print(answer)
#处理找不到文件的异常
filename = 'alice.txt'
try:
with open(filename) as f_obj:
contents = f_obj.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
except FileNotFoundError:
msg = "Sorry, the file "+filename+" does not exist"
print(msg)
else:
'''计算文件大致包含多少个单词'''
words = contents.split()
num_words = len(words)
print("The title "+filename +" has about "+str(num_words)+" words")
#使用多个文件 将代码封装起来
def count_words(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'
except FileNotFoundError:
# msg = "Sorry, the file "+filename+" does not exist"
# print(msg)
#失败时一声不吭
pass
else:
'''计算文件大致包含多少个单词'''
words = contents.split()
num_words = len(words)
print("The title "+filename +" has about "+str(num_words)+" words")
filenames =['alice.txt','siddhartha.txt','moby_dict.txt','little.txt']
for filename in filenames:
count_words(filename)
#存储这组数字
import json
numbers =[2,3,5,7,11,13]
filename = 'numbers.json'
with open(filename,'w') as f_obj:
json.dump(numbers,f_obj)
#将列表读取到内存中
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
#保存和读取用户生成的数据
import json
username = input("What's your name ? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back, "+ username + "!")
#向名字被存储的用户发出问候
import json
filename = 'username.json'
with open(filename) as f_obj:
username = json.load(f_obj)
print("Welcome back, "+ username + "!")
import json
#如果以前存储了用户名,就加载它
#否则,就提示用户输入用户名并存储它
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name ? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back, "+username +"!")
else:
print("Welcome back, "+username+"!")
#重构
import json
def greet_user():
'''问候用户,并指出其名字'''
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name ? ")
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back, "+username +"!")
else:
print("Welcome back, "+username+"!")
greet_user()
#重构greet_user()
import json
def get_stored_username():
'''如果存储了用户名,就获取它'''
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
'''问候用户,并指出名字'''
username = get_stored_username()
if username:
print("Welcome back, "+username+"!")
else:
username = input("What is your name ? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back, "+username +"!")
greet_user()
#继续重构greet_user()
import json
def get_stored_username():
'''如果存储了用户名,就获取它'''
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def greet_user():
'''问候用户,并指出名字'''
username = get_stored_username()
if username:
print("Welcome back, "+username+"!")
else:
username = input("What is your name ? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
print("We will remember you when you come back, "+username +"!")
greet_user()
#再次重构
import json
def get_stored_username():
'''如果存储了用户名,就获取它'''
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
'''提示用户输入用户名'''
username = input("What is your name ? ")
filename = 'username.json'
with open(filename,'w') as f_obj:
json.dump(username,f_obj)
return username
def greet_user():
'''问候用户,并指出名字'''
username = get_stored_username()
if username:
print("Welcome back, "+username+"!")
else:
username = get_new_username
print("We will remember you when you come back, "+username +"!")
greet_user()
Python-笔记
于 2021-07-20 22:24:20 首次发布