发现自己对于python的基础掌握的并不是很牢实,利用几天时间把重点写下来,并打算把(《Python编程从入门到实践》试一试)的代码全部敲一遍,如果有不对的地方,请不吝赐教。
目录
第1章 起步
第2章 变量和简单数据类型
第3章 列表简介
第4章 操作列表
第5章 if语句
第6章 字典
第7章 用户输入和while循环
第8章 函数
第9章 类
第10章 文件和异常
第11章 测试代码
我的建议是安装anaconda+pycharm
变量名只能包含字母、数字、下划线,不能以数字开头。变量名不能包含空格,不要将python关键字和函数名用作变量名。
title() upper() lower()[用于末尾]
python使用+来合并字符串
\t 制表符 \n 换行符
删除空白 rstrip()后 lstrip()前 strip()全[用于末尾]
str() 将非字符串值表示为字符串
注释为#
习题答案
# 2-1
message = "hello"
print(message)
# 2-2
message = "nihao1"
print(message)
message = "nihao2"
print(message)
# 2-3
name = "lihua"
print("Hello "+name+",would you like to learn some Python today")
# 2-4
name = "hua Li"
print(name+"\n"+name.title()+"\n"+name.upper()+"\n"+name.lower())
# 2-5
print('Albert Einstein once said,"A person who never made a mistake never tried angthing new"')
# 2-6
famous_person = "Albert Einstein"
message = '"A person who never made a mistake never tried angthing new"'
print(famous_person+" once said,"+message)
# 2-7
person = "\tli hua\t"
print(person+person.rstrip()+person.lstrip()+person.strip())
num=312
# 2-8
print(5+3)
print(10-2)
print(2*4)
print(16/2)
# 2-9
number = 7
print("I like "+str(number))
# 2-10
# 向大家问好
print("hello")
# 2-11
import this
通过将索引指定为-1,可让python返回最后一个列表元素
列表末尾添加新元素 append('')
insert(index,'')
删除 del variable[index]
pop(index) 删除,可接着使用
不知位置,只知道值,删除 remove('')
sort()用于排序 [用于末尾] 可改变顺序 通过sort(reverse=True)
sorted(variable) 临时排序
reverse() 翻转列表元素
len(variable) 获取变量长度
习题答案
# 3-1
names = ['liuda','wanger','zhangsan','lisi']
print(names[0])
print(names[1])
print(names[2])
print(names[3])
# 3-2
message = "hello,"
print(message+names[0])
print(message+names[1])
print(message+names[2])
print(message+names[3])
# 3-3
ty = ['bicycle','car','motorcycle']
sth = "I would like to own a "
print(sth+ty[0])
print(sth+ty[1])
print(sth+ty[2])
# 3-4
person = ['sunyanzi','wuenda','dafenqi','tuling']
print("welcome to my party "+person[0])
print("welcome to my party "+person[1])
print("welcome to my party "+person[2])
print("welcome to my party "+person[3])
# 3-5
print(person[2]+" not go to my party");
person[2]="yaoqizhi"
print("welcome to my party "+person[0])
print("welcome to my party "+person[1])
print("welcome to my party "+person[2])
print("welcome to my party "+person[3])
# 3-6
print("I find a big dining-table")
person.insert(0,'wangfei')
person.insert(2,'jiaying')
person.append('dilireba')
print("welcome to my party "+person[0])
print("welcome to my party "+person[1])
print("welcome to my party "+person[2])
print("welcome to my party "+person[3])
print("welcome to my party "+person[4])
print("welcome to my party "+person[5])
print("welcome to my party "+person[6])
# 3-7
print("I am sorry,I just invite two people")
print("sorry I can't invite you,"+person.pop())
print("sorry I can't invite you,"+person.pop())
print("sorry I can't invite you,"+person.pop())
print("sorry I can't invite you,"+person.pop())
print("sorry I can't invite you,"+person.pop())
print("welcome to my party "+person[0])
print("welcome to my party "+person[1])
del person
# 3-8
travel = ['xinjiang','maerdaifu','weinisi','xianggelila','sanya']
print(travel)
print(sorted(travel))
print(travel)
print(sorted(travel,reverse=True))
print(travel)
travel.reverse()
print(travel)
travel.reverse()
print(travel)
travel.sort()
print(travel)
travel.sort(reverse=True)
print(travel)
# 3-9
print(len(person))
# 3-10
like = ['sunyazi','xiaolongxia','xinjiang','yuedu']
print(like)
print(sorted(like))
like.sort(reverse=True)
print(like)
like.insert(2,'sanbu')
like.append('green')
del like[2]
print(like)
like.pop()
print(like)
# 3-11
error = ['sd','s1']
print(error[2])
for n in ns: for循环 记得缩进
range(i,j,n) 生成i到j,步长为n的值(不包含j)
list(range(1,6))可将转换成列表
min(),max(),sum()
切片 list[1:3] 表示取出第二个元素到第三个元素
习题答案
# 4-1
pizzas = ['p1','p2','p3','p4','p5']
for pizza in pizzas:
print("I like "+pizza+" pizzas")
print("I really love pizza!")
# 4-2
animals = ['cat','dog','bird','Hamster','rabbit']
for animal in animals:
print("A "+animal+" would make a great pet")
print("any of these animals would make a great pet!")
# 4-3
values=list(range(1,21))
for value in values:
print(value)
# 4-4
values=list(range(1,1000001))
for value in values:
print(value)
# 4-5
values=list(range(1,1000001))
for value in values:
print(value)
print(min(values))
print(max(values))
print(sum(values))
# 4-6
values=list(range(1,20,2))
for value in values:
print(value)
# 4-7
values=list(range(3,31,3))
for value in values:
print(value)
# 4-8
sq=[]
for value in range(1,11):
value=value**3
sq.append(value)
print(sq)
# 4-9
sq = [value**3 for value in range(1,11)]
print(sq)
# 4-10
animals = ['cat','dog','bird','Hamster','rabbit']
print("The first three items in the list are:")
print(animals[0:3])
print("three items from the middle of the list are:")
print(animals[1:4])
print("The last three items in the list are:")
print(animals[2:5])
# 4-11
friend_pizzas=pizzas[:]
pizzas.append('p6')
friend_pizzas.append('f6')
print("My favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("My friend's favorite pizzas are:")
for friend_pizza in friend_pizzas:
print(friend_pizza)
# 4-12
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for my_food in my_foods:
print(my_food)
print("My friend's favorite foods are:")
for friend_food in friend_foods:
print(friend_food)
# 4-13
foods=('fd1','fd2','fd3','fd4','fd5')
for food in foods:
print(food)
# foods[0]='fd6'
foods=('fd1','fd2','fd3','fdd4','fdd5')
for food in foods:
print(food)
# 4-14
# https://www.python.org/dev/peps/pep-0008/
用and,or (区别于&&和||)
要判断特定的值是否包含在列表中,可使用关键字in,不在not in
if-elif-else结构
习题答案
# 5-1
car = 'subaru'
print("\ncar == 'subaru'? I predict True.")
print(car == 'subaru')
print("car == 'audi'?I predict Flase.")
print(car == 'audi')
car = 'bwm'
print("\ncar == 'bwm'? I predict True.")
print(car == 'bwm')
print("car == 'luhu'?I predict Flase.")
print(car == 'luhu')
car = 'benchi'
print("\ncar == 'benchi'? I predict True.")
print(car == 'benchi')
print("car == 'fengtian'?I predict Flase.")
print(car == 'fengtian')
car = 'xiandai'
print("\ncar == 'xiandai'? I predict True.")
print(car == 'xiandai')
print("car == 'sangtana'?I predict Flase.")
print(car == 'sangtana')
car = 'byd'
print("\ncar == 'byd'? I predict True.")
print(car == 'byd')
print("car == 'qq'?I predict Flase.")
print(car == 'qq')
# 5-2
print("'Car'=='car'?")
print('Car'=='car')
t='Car'
print(t.lower() == 'car')
print(7<8)
print(7<=8)
print(7==8)
print(7>8)
print(7>=8)
print('car' == 'Car'or'li'=='li')
print('car' == 'Car'and'li'=='li')
cat=['a','b','c']
print('a' in cat)
print('c' not in cat)
# 5-3
alien_color = 'green'
if alien_color == 'green':
print("you get 5 points")
alien_color = 'red'
if alien_color == 'green':
print("you get 5 points")
# 5-4
alien_color = 'green'#可换'yellow'
if alien_color == 'green':
print("you get 5 points")
else:
print("you get 10 points")
# 5-5
alien_color = 'green'#可换'yellow','red',
if alien_color == 'green':
print("you get 5 points")
elif alien_color == 'yellow':
print("you get 10 points")
else:
print("you get 15 points")
# 5-6
age = 16
if age<2 and age>0:
print("you are a baby")
elif age>=2 and age<4:
print("You are toddler")
elif age>=4 and age<13:
print("you are a child")
elif age>=13 and age<20:
print("you are a teenager")
elif age>=20 and age<65:
print("you are an adult")
else:
print("you are an elder person")
# 5-7
favorite_fruits=['apple','pear','bananas']
if 'apple' in favorite_fruits:
print("you really like apple")
if 'pear' in favorite_fruits:
print("you really like pear")
if 'strawberry' in favorite_fruits:
print("you really like strawberry")
if 'bananas' in favorite_fruits:
print("you really like bananas")
if 'orange' in favorite_fruits:
print("you really like orange")
# 5-8
users = ['admin','s1','s2','s3','s4']
for user in users:
if user == 'admin':
print("Hello admin,would you like to see a status report")
else:
print("hello "+user+",thank you for logging in again")
# 5-9
users = []
if users:
print("we need to find some users!")
# 5-10
current_users=['a1','A2','a3','D4','a5']
new_users=['a1','b2','c3','d4','E5']
for new_user in new_users:
for current_user in current_users:
if new_user.lower()==current_user.lower():
print(new_user+" has already been used")
print("please input new username")
break
elif current_user=='a5':
print(new_user+" is not being used")
# 5-11
nums = list(range(1,10))
for num in nums:
if num==1:
print(str(num)+"st")
elif num==2:
print(str(num)+"nd")
elif num==3:
print(str(num)+"rd")
else:
print(str(num)+"th")
字典{} 键-值对
python不关心键-值对的添加顺序,而只关心键和值之间的关联关系
del dist['键']即可删除此键-值对
.items()返回键-值对列表 .keys()返回键(默认) .values()返回值
set()去除重复的
习题答案
# 6-1
people1={'first_name':'zhang','last_name':'san','age':18,'city':'beijing'}
print(people1)
# 6-2
pn={'p1':6,'p2':1,'p3':7,'p4':13,'p5':3}
for key,value in pn.items():
print(str(key)+",your favorite number is "+str(value))
# 6-3
bc={'for':'xunhuan','list':'liebiao','array':'shuzu','dist':'zidian','print':'shuchu'}
for key,value in bc.items():
print(str(key)+":"+str(value))
# 6-4
# 见6-3
# 6-5
hg={'nile':'egypt','changjiang':'china','mississippi':'american'}
for key,value in hg.items():
print("The "+key.title()+" runs through "+value.title())
for key in hg.keys():
print(key.title())
for value in hg.values():
print(value.title())
# 6-6
favorite_languages={'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
people=['jen','sarah','ruby','phil']
for key,value in favorite_languages.items():
if key in people:
print(key+",thank your welcome")
else:
print(key+",please take our poil")
# 6-7
people1={'first_name':'zhang','last_name':'san','age':18,'city':'beijing'}
people2={'first_name':'wang','last_name':'er','age':33,'city':'shanghai'}
people3={'first_name':'li','last_name':'si','age':18,'city':'hongkong'}
people=[people1,people2,people3]
for pp in people:
for key,value in pp.items():
print(key+":"+str(value))
print()
# 6-8
cat={'name':'cat','type':'t1','owner':'p1'}
dog={'name':'dog','type':'t2','owner':'p2'}
pig={'name':'pig','type':'t3','owner':'p3'}
bird={'name':'bird','type':'t4','owner':'p4'}
pets=[cat,dog,pig,bird]
for pet in pets:
for key,value in pet.items():
print(key+":"+str(value))
print()
# 6-9
x=['changsha','chengdu','hangzhou']
y=['xinjiang','wuhan']
z=['beijing','hongkong']
favorite_places={'x':x,'y':y,'z':z}
for fpk,fpv in favorite_places.items():
print(fpk+"'s favorite places:")
for v in fpv:
print(v)
print()
# 6-10
p1=[2,5]
p2=[3,13]
p3=[1,8,9]
pn={'p1':p1,'p2':p2,'p3':p3}
for pk,pv in pn.items():
print(pk+"'s favorite number:")
for v in pv:
print(v)
print()
# 6-11
city1={'country':'c1','population':'pl1','fact':'f1'}
city2={'country':'c2','population':'pl2','fact':'f2'}
city3={'country':'c3','population':'pl3','fact':'f3'}
cities={'city1':city1,'city2':city2,'city3':city3}
for ck,cv in cities.items():
print(ck)
for cvk,cvv in cv.items():
print(cvk+":"+cvv)
print()
# 6-12
# 略
用户输入函数input("提示信息")
求摸运算符%
使用break语句立即退出while循环 continue语句返回循环开头,并根据条件测试结果决定是否继续执行循环
ctrl+c 可立马退出循环 pycharm默认为ctrl+f2
习题答案
# 7-1
message=input("What car do you need to rent?")
print("Let me see if I can find you a "+message)
# 7-2
message=input("How many people are there to eat?")
if int(message)>8:
print("No empty table")
else:
print("There is a table for you to dine")
# 7-3
message=input("please input a number")
if int(message)%10==0:
print("This number is an integer multiple of ten")
else:
print("This number isn't an integer multiple of ten")
# 7-4
pr="Please enter pizza ingredients\nEnter 'quit' to end"
flag=True
while flag:
message=input(pr)
if message=='quit':
break
else:
print("We have added ingredients "+message)
# 7-5
pr="Please enter your age\nEnter 'quit' to end"
flag=True
while flag:
message=input(pr)
if message=='quit':
break
else:
if int(message)<3:
print("You watch the movie for free")
elif int(message)>=3 and int(message)<=12:
print("It costs $10 to watch a movie")
else:
print("It costs $15 to watch a movie.")
# 7-6
# 如上
# 7-7
while True:
print("gogogogogo")
# 7-8
sandwich_orders=['s1','s2','s3']
finish_sandwiches=[]
while sandwich_orders:
tt=sandwich_orders.pop()
print("I make your "+tt+" sandwich")
finish_sandwiches.append(tt)
print("finish_sandwiches:")
for t in finish_sandwiches:
print(t)
# 7-9
sandwich_orders=['s1','pastrami','s2','pastrami','s3','pastrami']
print(sandwich_orders)
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print("The pastrami is sold out")
print(sandwich_orders)
# 7-10
responses={}
flag=True
while flag:
name=input("what's your name?")
response=input("If you could visit one place in the world,where would you go?")
responses[name]=response
repeat=input("would you like to let another person respond?(yes/no)")
if repeat=="no":
flag=False
print("\n--Result--")
for name,response in responses.items():
print(name+" want go to "+response)
使用关键字实参时,务必准确地指定函数定义中的形参名
使用return语句将值返回到调用函数的代码行
切片表示法[:]创建列表的副本
*array中星号让Python创建一个名为array的空元组
**dir中两个星号让Python创建一个名为dir的空字典
from...import...导入模块的特定函数
as给模块指定别名
习题答案
# 8-1
def display_message():
print("I am learning function")
display_message()
# 8-2
def favorite_book(book):
print("One of my favorite book is "+book)
favorite_book("Alice in wonderland")
8-3
def make_shirt(size,words):
print("The T-shirt\nsize:"+size+"\nwords:"+words)
make_shirt(size="s",words="hello")
# 8-4
def make_shirt(size='T',words='I love python'):
print("The T-shirt\nsize:"+size+"\nwords:"+words)
make_shirt()
make_shirt('M')
make_shirt(words='I love Java')
# 8-5
def describe_city(city,country='China'):
print(city+" is in "+country)
describe_city('shanghai')
describe_city('beijing')
describe_city('London','English')
# 8-6
def city_country(city,country):
return city+","+country
c1=city_country("shanghai","China")
c2=city_country("paris","France")
c3=city_country("new York","American")
print(c1)
print(c2)
print(c3)
# 8-7
def make_album(singer,album,song=''):
albums={'singer':singer,'ablum':album}
if song:
albums['song']=song
return albums
al1=make_album('jay','shuohaobuku')
al2=make_album('jason','It is love')
al3=make_album('sunyanzi','meet','9')
print(al1)
print(al2)
print(al3)
# 8-8
flag=True
while flag:
singer=input("please input a singer")
album=input("please input the album")
alb=make_album(singer,album)
print(alb)
tt=input("Do you want to quit(yes/no)")
if tt=="yes":
flag=False
# 8-9
def show_magician(magician):
for n in magician:
print(n)
magician=['liuqian','xiaom','nos']
show_magician(magician)
# 8-10
def make_magician(magician):
n=len(magician)
i=0
while i