? ? ? ?最近开始学习python语言,看了一些视频,选择了《python编程:从入门到实践》这本书。看书跟着学,书前文推荐是每天看一章,但实际做下来,没课的时候一天可以看四章,上课的时候基本一上上半天,所以一天看两章问题不大。
? ? ? 本来打算配合小甲鱼的python视频一起学习,但由于实在没时间所以放弃了。现在学到书的第七章,感觉还不错。
? ? ? 分享一些我的学习笔记和这本书的一些课后习题答案给大家。为自己的学习生活也做一个简单的记录。
? ? ? ? 总的说来,这本书是本非常好的书,对于有C语言基础的人来说学习起来上手会很快很轻松。
常用命令
- Spyder清屏
????????在IPython中输入reset命令,得到提示输入y确认即可
????????在控制台输入clear即可
????????使用快捷键Ctrl + L
报错汇总
- 1.EOL while scanning string literal
- ????????Print少打了一个双引号/打成了中文双引号
- 2.invalid character in identifier
????????????????意思是:标志符中的无效字符
- ????????if后面的冒号打成了中文输入法下的冒号
- 3.invalid syntax
????????????????语法错误
- ? ? ? ?字典中键值对之间忘记加逗号了
- 字典嵌套字典时,被嵌套的字典大括号前应为:写成了=。
- 字典嵌套字典时,被嵌套的字典和字典大括号之间也要有,。
- 访问字典中某一键值时[]后面加了.。
- 在函数这一章,如果形参/实参是字符串的话,形参不需要加双引号,实参需要
????????4.f-string expression part cannot include a backslash
????????????????意思是f字符串中不能出现反斜杠
? ? ? ? 5.'function' object is not subscriptable
? ? ? ? ? ? ? ? ??“函数”对象不可下标
? ? ? ? ? ? ? ? ? 出现原因:一是调用自定义函数时要用圆括号()而不是方括号[ ]。二是自定义函数名不能与已有变量重名
???????PY
第二章学习笔记
1. print(name.title());此时不需要引号
2. print(f"hello,{name.title()}"):注意此时需要引号,并且函数内的东西要用大括号括起来
练习答案
##2-5
name='albert einsetin'
message='a person who never made a mistake never tried anythiing new'
print(name.title())
print(f"{name.title()} once said {message}")
##2-9
fav_num=8
msg="my favorite number is "+str(fav_num)+"."
print(msg)
第三章学习笔记
1.注意if和while后都有一个冒号:
2.true+true=2
3.
??转换为整型,python会截断处理,不会四舍五入。
4.获得类型的信息一般有两种函数:type 和 isinstance
5. Python 中 / 与 // 的区别
在Python中“/”表示浮点数除法,返回浮点结果,也就是结果为浮点数,而“//”在Python中表示整数除法,返回不大于结果的一个最大的整数,意思就是除法结果向下取整。
6.sorted的参数可以没有,也可以有两个。
???????? 例如打印与字母顺序相反的顺序时:print(sorted(travels,reverse=True))
7.但如果是sort的话,只有一个参数
???????? travels.sort(reverse=True)
print(travels)
且注意sorted不能采用这种方法
练习答案
#3-8放眼世界
travels=['newyork','thailand','japan','london','singpore']
print(travels)
print(sorted(travels))
print(travels)
print("按照相反字母顺序打印")
print(sorted(travels,reverse=True))
print("核实一下是否是原来的顺序")
print(travels)
print("反转顺序")
travels.reverse()
print(travels)
print("再次反转")
travels.reverse()
print(travels)
print("使用sort")
travels.sort()
print(travels)
print("sort反顺序")
travels.sort(reverse=True)
print(travels)
第四章 ?操作列表-学习笔记
1.for语句后一定要记得带冒号,不然会报错!
练习答案
#4-1披萨
pizzas=['pianapple','peigen','potato']
for pizza in pizzas:
??? print("i like "+pizza+' pizza')
print("i really love pizza")
#4-2
con_animals=['rabbit','cat','dog']
for animal in con_animals:
??? print('A '+animal+' would make a great pet')
print('Any of these animals would make a great pet')
#4-3数到20
numbers=[num for num in range(1,21)]
print(numbers)
4-4数到一百万
numbers=[]
for num in range(101):
??? numbers.append(num)
print(numbers)
print(min(numbers))
#4-7奇数
numbers=[]
for num in range(1,21,2):
??? numbers.append(num)
??? print(num)
#4-9立方解析
numbers=[]
for num in range(1,11):
??? numbers.append(num**3)
print(numbers)
print("采用立体解析的方法如下")
numbers=[num**3 for num in range(1,11)]
print(numbers)
#4-10切片
con_animals=['rabbit','cat','dog','panda','bird','lion']
print(con_animals[0:3])
print(con_animals[1:5])
print(con_animals[3:])
#4-11你的披萨我的披萨
pizzas=['pianapple','peigen','potato']
friends_pizza=pizzas[:]
pizzas.append('tomato')
friends_pizza.append('banana')
print("My favorite pizzas are:")
for pizza in pizzas[:]:
??? print(pizza)
for pizza in friends_pizza[:]:
??? print(pizza)
#4-13自助餐
foods=('potato','hundu','vegetables','pizza','humberger')
for food in foods:
??? print(food)
foods=('potato','hulatang','buttonsope','pizza','humberger')
for food in foods:
??? print(food)
第五章 if语句
练习
#5-1
car='subaru'
print("Is car == 'subaru'?I predict True")
print(car=='subaru')
#5-5外星人颜色3
alien_color='red'
if alien_color == 'green':
??? print("你得到了五分")
elif alien_color=='yellow':
??? print("你得到了十分")
else:
??? print("你得到了十五分")
#5-6人生的不同阶段
age=1
if age<2:
??? print("这个人是个婴儿")
elif age>2 and age<4:
??? print("这个人是个幼儿")
elif age>4 and age<13:
??? print("这个人是个儿童")
elif age>13 and age<20:
??? print("这个人是个青少年")
elif age>20 and age<65:
??? print("这个人是个成年人")
elif age>65:
??? print("这个人是个老年人")
???
#5-7喜欢的水果
favorite_fruits=['pineapple','dragon','mihoutao']
if 'pineapple' in favorite_fruits:
??? print("you really like pineapple")
#5-8-9以特殊方式跟管理员打招呼
name_list=['admin','acky','boubou','chick','kevin']
name=input()
if name:
??? if name == 'admin':
??????? print("hello admin,would you like to see a status report?")
??? else:
??????? print("hello jaden,thank you for logging in again")
else:
???? print("we need to find some users")
???
#5-10检查用户名
current_users=['admin','acky','boubou','chick','kevin']
new_users=['acky','nelson','kaka','momoco','kenken']
#print("请输入您的用户名:")
#name=input()
for name in new_users:
??? if name in current_users:
??????? print("用户名已被使用")
??? else:
??????? print("用户名未被使用")
#5-11序数
numbers=[1,2,3,4,5,6,7,8,9,10]
for number in numbers:
??? if number == 1:
??????? print(f"{number}st")
??? elif number == 2:
??????? print(f"{number}nd")
??? else:
??????? print(f"{number}th")
第六章 字典
练习
#6-1人
person={'名':'kk',
??????? '姓':'朴',
??????? '年龄':'22',
??????? '居住城市':'上海',
??????? }
print(f"我姓{person['姓']}")
#6-7人们
person_kk={'名':'kk',
??????? '姓':'朴',
??????? '年龄':'22',
??????? '居住城市':'上海',
????????? }
person_cc={'名':'cc',
??????? '姓':'杨',
??????? '年龄':'32',
??????? '居住城市':'北京',
????????? }
person_aa={'名':'aa',
??????? '姓':'r',
??????? '年龄':'27',
??????? '居住城市':'巴黎',
????????? }
people=[person_kk,person_cc,person_aa]
for person in people:
??? print(person)
#6-8宠物
pet_dog={
?? ??????'name':'dog',
???????? 'owner':'cc',
??????? }
pet_cat={
???????? 'name':'cat',
???????? 'owner':'kk',
??????? }
pet_fish={
???????? 'name':'fish',
???????? 'owner':'aa',
??????? }
pets=[pet_dog,pet_cat,pet_fish]
for pet in pets:
??? print(pet)
#6-9喜欢的地方(字典中嵌套列表)
favorite_places={
????????????????? 'kk':['london','tokyo','korea'],
????????????????? 'aa':['paris','nepol','africa'],
????????????????? 'cc':['shangahai','kaifeng','hangzhou'],
??????????????? }
for name,places in favorite_places.items():
??? print(f"{name.title()}'s favorite places are:")
??? for place in places:
??????? print(place.title())
#6-11 城市(字典嵌套字典)
cities={
??????? 'shanghai':{
??????????????????? 'country':'china',
??????????????????? 'population':'1kw',
??????????????????? 'fact':'beauty',
??????????????????? },
??????? 'tokyo':{
??????????????? 'country':'japan',
??????????????? 'population':'50w',
??????????????? 'fact':'far',
??????????????? },
??????? 'london':{
???????????????? 'country':'england',
???????????????? 'population':'100w',
???????????????? 'fact':'wet',
???????????????? },
???????
???? ???}
for city_name,city_info in cities.items():
??? print(f"city's name is {city_name.title()}")
??? print(f"他属于{city_info['country']}")
??? print(f"它拥有人口{city_info['population']}")
??? print(f"它最大的特点是{city_info['fact']}")
??? 第七章 用户输入和while循环
练习
#7-1汽车租赁
car=input("let me see if i can find you subaru? ")
print(car)
#7-2餐馆定位
number=input('有多少人来吃饭? ')
number=int(number)
if number >8:
??? print("没有空桌")
else:
??? print("有空座")
#7-4披萨配料
prompt="\n please input a series of pizzas adding"
prompt += '\n(Enter the quit when you finished)'
while True:
??? adding=input(prompt)
??? if adding == 'quit':
??????? break
??? else:
??????? print(f"我们将在披萨中加入配料{adding}")
#7-5电影票
prompt='请输入你的年龄'
while True:
??? age=input(prompt)
??? age=int(age)
??? if age < 3:
??????? print('你免费')
??????? break
??? elif age >3 and? age < 12:
??????? print('你需要支付十美元')
??????? break
??? elif age > 12:
??????? print('你需要支付十五美元')
??????? break
#7-8 熟食店
sandwich_orders=['tunnayu','niuyouguo','peigen']
finished_sandwiches=[]
while sandwich_orders:
??? finished_sandwich=sandwich_orders.pop()
??? print(f'i made your {finished_sandwich} sandwich')
???
??? finished_sandwiches.append(finished_sandwich)
print("接下来是做好的列表")
for finished_sandwich in finished_sandwiches:
??? print(finished_sandwich.title())
???
???
#7-9 五香烟熏牛肉卖完了
sandwich_orders=['tunnayu','pastrami','niuyouguo','pastrami','peigen','pastrami']
finished_sandwiches=[]
while 'pastrami' in sandwich_orders:
??? sandwich_orders.remove('pastrami')
print(sandwich_orders)
第八章 函数
练习
#8-1消息
def display_message():
"""指出你在本章学的是什么的信息"""
print("我在本章学的是函数")
display_message()
#8-2喜欢的图书
def favorite_book(title):
print(f"One of my favorite books is {title}")
favorite_book("Alice in Wonderland")
#8-3T恤
def make_shirt(size,word):
print(f"这个T恤的尺寸是{size},印在上面的字样是{word}")
print("这种调用方法是位置实参调用:")
make_shirt('m','makabaka')
print("下面这种是关键字实参调用:")
make_shirt(word='yigubigu',size='xs')
#8-4大号T恤
"""使用默认值"""
def make_shirt(size,word='i love python'):
print(f"这个T恤的尺寸是{size},印在上面的字样是{word}")
make_shirt('L')
make_shirt('M')
make_shirt('s','i love c')
#8-5 城市
def describe_city(city_name,city_country='china'):
print(f"{city_name} in {city_country}")
describe_city('shanghai')
describe_city('kaifeng')
describe_city('london','england')
#8-6城市名
def city_country(city_name,city_country):
"""打印城市的名字和所属国家"""
print(city_name,city_country)
name_of_city=input("请输入城市名字:")
name_of_country=input("请输入国家的名字:")
city_country(name_of_city,name_of_country)
#8-7专辑
def make_album(singer,name,number=None):
music={
'singer':singer,
'name':name,
}
if number:
music={
'singer':singer,
'name':name,
'number':number,
}
return music
music_1=make_album('xusong','yasugongshang')
music_2=make_album('yizhiliulian','haidi')
music_3=make_album('dazhangwei','huluwa','3')
print(music_1)
print(music_2)
print(music_3)
#8-8用户的专辑
def make_album(singer,name,number=None):
music={
'singer':singer,
'name':name,
}
if number:
music={
'singer':singer,
'name':name,
'number':number,
}
return music
while True:
print("\n 接下来请输入你喜欢的歌手相关信息。\n输入q可以退出")
name_of_music=input('请输入你喜欢的专辑名字:')
if name_of_music =='q':
break
name_of_singer=input('请输入你喜欢的歌手名字:')
if name_of_singer=='q':
break
print(name_of_music,name_of_singer)
|