《Python编程:从入门到实践》答案

快乐又不要钱,为什么不呢?

【注】本文中所有的代码本人全部测试通过后才写在下面。考虑到夹杂结果图片太乱,所以没加。大家复制代码拿去运行即可。

前面章节的答案后续会补上。

【注】所有包含中文的代码都必须把编码设置成UTF-8才能正常运行。我用的是Geany,设置方法为:文档——设置文件编码——Unicode-——UTF-8

持续更新……

第二章

print("Hello my new life,\nhllo ,the technology world.\nplese be gentle to me.")

2-2

message="Hello my new life,\nhllo ,the technology world.\nplese be gentle to me."
print(message)

 2-3

name = 'Eric'
print('Hello '+name+', would you like to learn some pyghon today?')

2-4

name = 'eric'
print(name.title())
print(name.upper())
print(name.lower())

name = 'albert einstein'
saying="A person who never made a mistake never tried anything new."
print(name.title()+"once said"+": "+'\n\t"'+saying+'"')

name = ' albert einstein '
saying="A person who never made a mistake never tried anything new."
print(name.title())
print(name.title().lstrip().rstrip()+"once said"+": "+'\n\t"'+saying+'"')
print(name.strip())

print(80/10)
print(2*4)
print(10-2)
number=4
print("my favorite number is "+str(number))

 

  第三章 

names=['王辰','王杰','许博文','肖嘉良','田家铭','徐汉章']
for name in names:
	print(name)
names=['王辰','王杰','许博文','肖嘉良','田家铭','徐汉章']
for name in names:
	print('Hello '+name+" it's good to see you !")
names=['car','bicycle','shared bikes','motorcycle','bus']
for name in names:
	print('To be the truth ,my favorite vehicle is '+name+'.')

names=['泽东','和珅','胡雪岩','华罗庚','王羲之']
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

 

names=['泽东','和珅','胡雪岩','华罗庚','王羲之']
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('\n\nSorry the '+names[-2]+' has no time these days ,please call someone else.')
names[-2]='张三丰'
print(names)

for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

 

names=['泽东','和珅','胡雪岩','华罗庚','王羲之']
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('\n\nSorry the '+names[-2]+' has no time these days ,please call someone else.')
names[-2]='张三丰'
print(names)

for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('My lovely friends ,i have find a bigger desk and now we can invite more friends')
print(names)
print('\n')
names.append('老子')
names.insert(0,'水阡陌')
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

 

names=['泽东','和珅','胡雪岩','华罗庚','王羲之']
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('\n\nSorry the '+names[-2]+' has no time these days ,please call someone else.')
names[-2]='张三丰'
print(names)

for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('My lovely friends ,i have find a bigger desk and now we can invite more friends')
print(names)
print('\n')
names.append('老子')
names.insert(0,'水阡陌')
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print(names)
print('Oh my God ,now i have to pick two of you \n')
for index in range(2,len(names)):
	pop_name=names.pop()
	print("sorry "+pop_name+" i can't help it ,because the book says.")
for name in names:
	print('Dear '+name+ ' everything went according to plan.')
del names[-1]
del names[0]
print(names)

tourist_attractions=['shenzhen','guangzhou','shanghai','jinlinqu']
print(tourist_attractions)
print(sorted(tourist_attractions))
print(tourist_attractions)
print(sorted(tourist_attractions,reverse=True))

 

tourist_attractions=['shenzhen','guangzhou','shanghai','jinlinqu']
print(tourist_attractions)
print(sorted(tourist_attractions))
print(tourist_attractions)
print(sorted(tourist_attractions,reverse=True))
print(tourist_attractions)
tourist_attractions.reverse()
print(tourist_attractions)
tourist_attractions.reverse()
print(tourist_attractions)
tourist_attractions.sort()
print(tourist_attractions)
tourist_attractions.sort(reverse=True)
print(tourist_attractions)

names=['毛泽东','和珅','胡雪岩','华罗庚','王羲之']
for name in names:
	print('Dear '+name+' ,i respectfully invite you to join me for dinner.')

print('\n\nSorry the '+names[-2]+' has no time these days ,please call someone else.')
names[-2]='张三丰'
print(names)
print(len(names))

 

第四章

pizzas=['zebra','peacock','panda']
for pizza in pizzas:
	print('My favorite pizza is '+pizza+'.')
print('I really like pizza.')

animals=['zebra','peacock','panda']
for animal in animals:
	print(animal+' in China is the protected-animals.')
print('They are the part of this world ,in other words ,it is our friends.')

 

#4-3
for number in range(1,21):
	print(number)
print('\n'+'=====================')

#4-4
#for num in range(1,1000001):
#	print(num)
#4-5
number=list(range(1,1000001))
print(min(number))
print(max(number))
print(sum(number))
print('\n'+'=====================')

#4-6
odds=list(range(1,21,2))
for odd in odds:
	print(odd)
print('\n'+'=====================')
#4-7
three_multiple=[num*3 for num in range(1,31)]
for number in three_multiple:
	print(number)
print('\n'+'=====================')
#4-8
cubes=[num**3 for num in range(1,11)]
for cube in cubes:
	print(cube)
print('\n'+'=====================')
#4-9同4-8

 

pizzas=['zebra','peacock','panda','shark','dolphin','eagle']
print('The first three items in this list is: ')
print(pizzas[:3])
print('The items from the middle of list is: ')
print(pizzas[1:4])
print('The last three items in this list is: ')
print(pizzas[-3:])

pizzas=['zebra','peacock','panda','shark','dolphin','eagle']
print('The first three items in this list is: ')
print(pizzas[:3])
print('The items from the middle of list is: ')
print(pizzas[1:4])
print('The last three items in this list is: ')
print(pizzas[-3:])
#4-10
friend_pizzas=pizzas[:]
friend_pizzas.append('bear')
print("My favorite pizza is:\n")
for pizza in pizzas:
	print(pizza)
print('++++++++++++++')
print("My friend favorite pizza is :\n")
for pizza in friend_pizzas:
	print(pizza)

 

foods=('steamed stuffed bun','steamed bun','dumplings','congee','rice')
for food in foods:
	print(food)
print('\n')
#foods[0]='rice'
foods=('noodle','hot pot','dumplings','congee','rice')
for food in foods:
	print(food)

第五章

 

car='subaru'
print("Is car=='subaru'? I predict True.")
print(car=='subaru')

print("\nIs car =='audi'? Ipredict False.")
print(car=='audi')

animal='peacock'
print(animal=='zebra')

 

yesterday_you_said="you are my only lover forever."
Today_you_say="you can't control who I really love."
print(yesterday_you_said==Today_you_say)
print('\n')
your_dream="Success"
situation="success"
print(your_dream.lower()==situation)
print(34<=4)
if 34<45 and 100*2<=400:
	print("the computer is better than child.")
new_words=['peacock','cube','eagle']
if 'peacock' in new_words:
	print("you can figure it!")
if 'bear' not in new_words:
	print("take care yur eyes!")

 

alien_color='green'
if alien_color=='green':
	print("you get 5 points")

alien_color='red'
if alien_color=='green':
	print("you get 5 points")

 

alien_color='red'
if alien_color=='green':
	print("you get 5 points")
else:
	print("you get 10 points")

 

alien_color='green'
if alien_color=='greaen':
	print("you get 5 points")
elif alien_color=='red':
	print("you get 10 points")
else :
	print("you get 15 points")
	

 

age=23
if age<2:
	print("U are an infant.")
elif age<4:
	print("U are a baby")
elif age<13:
	print("U are a child.")
elif age<20:
	print("U are a youngth.")
elif age<65:
	print("U are an adult.")
else :
	print("U are an elder.")

 

fruit=['orange','apple','graph','banana']
if 'apple' in fruit:
	print("you like apple.")
if 'graph' in fruit:
	print("you like graph.")
if 'watermellion' not in fruit:
	print('you do not like watermallion')

 

guests=['admin','A','W','L','Z']
for guest in guests:
	if guest=='admin' :
		print("love you my admin~~")
	else :
		print("welcome home "+guest +".")

guests=[]

if guests:
	for guest in guests:
		if guest=='admin' :
			print("love you my admin~~")
		else :
			print("welcome home "+guest +".")
else:
	print("We need to find some users!")

 

 

current_users=['A','B','C','D','E']
new_users=['A','B','X','Y','S']
for new_user in new_users:
	if new_user in current_users:
		print('Sorry ,you need to change your name!')
	else:
		print('This name has never been used!')

 【做这一问时遇到了问题,我先把正解写在下面再把我错误那个 拿出来分析】

#这是正解 
current_users=['A','B','C','D','E']
curren_users=[x.swapcase() for x in current_users]

new_users=['A','B','X','S','Y']

for user in new_users:
    if user.lower() in current_users:
        print('Sorry ,this name has been used ')
    else :
        print('Ok ,you have a new name')
#这是有问题的代码 

current_users=['A','B','C','D','E']
#我主要错在这个for 循环,我想把列表中所有元素变小写。
for current_user in current_users:
	store=current_user.lower()
	current_users.append(store)
	current_users.remove(store)
	
print(current_users)

new_users=['a','B','X','Y','S']
for user in new_users:
	if user.lower() in current_users:
		print('Sorry ,you need to change your name!')
	else:
		print('This name has never been used!')

错误分析:
就是,for 循环是始终按索引+1去遍历,在删除了第一个元素之后,我想要遍历的第二个元素变成了第一个元素,
但此时for 循环认为已经遍历完了第一个,开始遍历第二个。此时的第二个就是没删除元素时的第三个元素。所以我看到的是跳了一个的结果 

nums=[1,2,3,4,5,6,7,8,9]
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')
	

 

 第六章

acquaintance={
	'first_name':'zhang',
	'last_name':'shuyu',
	'city':'heilongjiang',
	}
print(acquaintance['first_name'])
print(acquaintance['last_name'])
print(acquaintance['city'])

 

favorate_num={
	'me':'2',
	'she':'3',
	'he':'8',
	}
print(favorate_num['she'])

 


words={
	'str':'change the number to string',
	'list':'to form a list',
	'lstrip':'delete the left blank in the string',
	'range':'to form a series of number between '+
	'the first number and the end number',
	'swapcase':'change the upper to lower or reverse',
	}
print('str'+': '+words['str']+'\n')
print('list'+': '+words['list']+'\n')
print('lstrip'+': '+words['lstrip']+'\n')
print('range'+': '+words['range']+'\n')
print('swapcase'+': ' +words['swapcase']+'\n')

 

rivers={
	'Rhine':'Switzerland',
	'changJiang':'china',
	'nile':'egypt',
	}
for river,country in rivers.items():
	print('The '+river.title()+'runs through the '+country.title()+'.')

#这道题需要注意的地方是 for 循环的用法,其中,rivers.items()不要忘了items()

favorate_languages={
	'A':'english',
	'C':'chinese',
	'D':'python',
	'X':'ahahha',
	}
inquiry_list=['A','C','D','W']
for name in inquiry_list:
	if name in favorate_languages.keys():
		print('you need to have a life you like and meet the lover one for you')
	else:
		print('if there is a mess, change it')
		

acquaintance_1={
	'first_name':'zhang',
	'last_name':'shuyu',
	'city':'heilongjiang',
	}
acquaintance_1={
	'first_name':'zhang',
	'last_name':'shuyu',
	'city':'heilongjiang',
	}
acquaintance_2={
	'first_name':'liu',
	'last_name':'fang',
	'city':'dalian',
	}
acquaintance_3={
	'first_name':'cui',
	'last_name':'shijie',
	'city':'hubei',
	}
people=[acquaintance_1,acquaintance_2,acquaintance_3]
for person in people:
	print(person)

cat={
	'category':'bosi',
	'lord':'fangfang'
	}
dog={
	'category':'dubin',
	'lord':'haha',
	}
rabbit={
	'category':'white',
	'lord':'dadada'
	}
pets=[cat,dog,rabbit]
for pet in pets:
	print(pet)

	

 

favorate_places={
	'me':['changjiang','huanghe','shaolinsi'],
	'she':['harBin','jilin','nanjing'],
	'he':['beside his home a yard']
	}
for man,places in favorate_places.items():
	print(man+': ')
	for place in places:
		print(place)
	print('\n')

favorate_num={
	'me':['2','5','8'],
	'she':['3','6','9'],
	'he':['7','4','1'],
	}
for name,number in favorate_num.items():
	print(name+'\'s favorate number are :')
	for num in number:
		print(num)
	print('\n')

cities={
	'luoyang':{
		'belong':'china',
		'population':'1000000',
		'fact':'the peony\'s hometown',
	},
	'paris':{
		'belong':'france',
		'population':'2000',
		'fact':'Notre Dame de Paris was set on fire'
	},
	'moscow':{
		'belong':'Russia',
		'population':'34000',
		'fact':'fierce fighting people',
	}
}
for city,info in cities.items():
	print(city.title()+':'+'\n')
	for attribute,detail in info.items():
		print(attribute.title()+': '+detail.title())

 

  • 114
    点赞
  • 602
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 15
    评论
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纸城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值