《python从入门到实践》部分答案

学到游戏部分,突然发现有些知识点不是很熟悉,出现了对照着书才能把代码写好的状况,所以决定把前面的习题重新做一遍,算是对知识的复习,没有做的部分和我挑的题目大相庭径,基本算是重复,所以放弃了部分习题。
2-1

a = 1
print(a)

3-1

names = ['linger','huangdui','junainai']
for name in names:
    print(name)

3-2

names = ['linger','huangdui','junainai']
for name in names:
    print('welcome,'+name)

3-8

places = ['taiwan','hanguo','meiguo','beijin']
places.sort()# 按字母顺序排列
for place in places:
    print(place)
places.reverse()# 按照原有相反的顺序排列
for place in places:
    print(place)

3-9

places = ['taiwan','hanguo','meiguo','beijin']
print(len(places))

4-3

for value in range(1,21):
    print(value)

4-4

list = []     #为了可以使用sum等的函数,要将数字输入进去
for value in range(1,1000001):
    list.append(value)
sum(list)
print(sum(list))      #只能打印字符

4-6

for value in range(1,21,2): #最后一个2表示步长
    print(value)

4-7

for value in range(3,31):
    if value%3 == 0:   #其中的%是取余函数
        print(value)

4-8

for value in range(3,31):
    print(str(value**3))#    print只能打印字符串,所以要强制把结果变为字符

4-9

#列表解析就是要用好* for * in *
list = [value**2 for value in range(1,11)]
print(list)

4-10

list = [value**2 for value in range(1,11)]
print(list)
print('The first three items in the list are:')
print(list[0:3])
print('Three items from the middle of the list are:')
print(list[3:6])
print('The last items of the list are:')
print(list[6:])

元组中要注意的地方是,元组中的元素不能随便修改,比如

yuanzu = (200,50)
yuanzu[0] = 250
#这一步是在尝试修改元组中的第一个元素
这一步执行的结果就是会报错,要修改只能成对修改

4-13

wjwd = ('mnzwr','xhnrg','ggbc','ymdx','ky')
for cai in wjwd:
    print(cai)
wjwd[1]= 'hahayu'
print(wjwd)

5-6

age = int(input('Please input your age:'))
if age < 2:
    print('You are a baby!')
elif 2 <= age < 4:
    print('You are learning to walk!')
elif 4 <= age < 13:
    print('You are a child!')
elif age >= 13:
    print('You are a young man!')

5-8

current_users = ['admin','lizixuan','jiangweijie','lichao','juran']
for current_user in current_users:
    if current_user == 'admin':
        print('Hello admin,would you like to see a status report?')
    else:
        print('Hello '+current_user+',thank you for logging in again.')

5-9

current_users = ['admin','lizixuan','jiangweijie','lichao','juran']
for current_user in current_users:
    if current_user == 'admin':
        print('Hello admin,would you like to see a status report?')
    else:
        print('Hello '+current_user+',thank you for logging in again.')
current_users = []
if current_user:
    print('we need to find some users!')

6-1

msw ={"first_name":"ma","last_name":"suowen","age":"24","city":"yangzhou"}
for key,value in msw.items():
	print("my friend's "+key+" is "+value)

运行结果:

my friend's first_name is ma
my friend's last_name is suowen
my friend's age is 24
my friend's city is yangzhou
[Finished in 0.1s]

6-7

嵌套()这一题是列表里有字典

peoples = [{'msw':{"first_name":"ma","last_name":"suowen","age":"24","city":"yangzhou"}},{'wp':{"first_name":"wang","last_name":"pei","age":"24","city":"danyang"}}]
for people in peoples:
	for key,value in people.items():
		for key1,valu in value.items():
			print("my friend "+key+"'s"+key1+'is'+valu)

运行结果
my friend msw’sfirst_nameisma
my friend msw’slast_nameissuowen
my friend msw’sageis24
my friend msw’scityisyangzhou
my friend wp’sfirst_nameiswang
my friend wp’slast_nameispei
my friend wp’sageis24
my friend wp’scityisdanyang
[Finished in 0.2s]
7-4

ingredients = []
mark = True
while mark:
	ingredient = input("please input your ingredients:")
	if ingredient != 'quit':
		ingredients.append(ingredient)
	else:
		break
print(ingredients)

运行结果:

jurandeMacBook-Pro:~ juran$ cd python
jurandeMacBook-Pro:python juran$ python3 7-4.py
please input your ingredients:happy
please input your ingredients:hahah
please input your ingredients:nidene
please input your ingredients:cheer up
please input your ingredients:quit
['happy', 'hahah', 'nidene', 'cheer up']
jurandeMacBook-Pro:python juran$ 

9-1

class Restaurant():
	def __init__(self,restuarant_name,restaurant_cisine_type):
		self.name = restuarant_name
		self.cuisinetype = restaurant_cisine_type
	def describe_restaurant(self):
		print("This restuarant's name is "+self.name+" and this restuarant has "+ self.cuisinetype+" cuisine type!")
	def open_restaurant(self):
		print("this restuarant is opening now!")
my_restuarant = Restaurant("ryker",'18')
my_restuarant.describe_restaurant()
my_restuarant.open_restaurant()

运行结果:

jurandeMacBook-Pro:python juran$ python3 review.py
This restuarant's name is ryker and this restuarant has 18 cuisine type!
this restuarant is opening now!

Car.py

class Car():
	def __init__(self,make,model,year):
		self.make = make
		self.model = model
		self.year = year
		self.odometer_reading = 0
	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)+" mile on it.")
	def update_odometer(self,value):
		if value >= self.odometer_reading:
			self.odometer_reading = value
		else:
			print("you can't roll back an odometer!")     #设定里程数是不能修改的
	def increment_odometer(self,meter):
		self.odometer_reading += meter
class Battery():
	def __init__(self, battery_size = 70):
		self.battery_size = battery_size
	def describe_battery(self):
		print("This car has a "+ str(self.battery_size)+"-kwh battery.")		
my_new_car = Car('audi','a4','2016')
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.increment_odometer(10)
my_new_car.read_odometer()
class ElectricCar(Car):
	def __init__(self,make,model,year):
		super().__init__(make,model,year)
		self.battery = Battery()
my_tesla = ElectricCar('tesla','model\'s','2016')
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()

运行结果:

jurandeMacBook-Pro:python juran$ python3 Car.py
2016 Audi A4
This car has 33 mile on it.

9-5

class User():
	def __init__(self,login_attempts):
		self.login_attempts = login_attempts
	def increment_login_attempts(self):
		self.login_attempts += 1
	def reset_login_attempts(self):
		self.login_attempts = 0
First_user = User(3)
First_user.increment_login_attempts()
print(First_user.login_attempts)
First_user.increment_login_attempts()
print(First_user.login_attempts)
First_user.reset_login_attempts()
print(First_user.login_attempts)

运行结果:

jurandeMacBook-Pro:python juran$ python3 Car.py
4
5
0

12-2 游戏角色
找一副你喜欢的图,转化为位图,创建一个类将其绘制到屏幕中央

practice.py

import sys
import pygame
from like_image import Like_image
def display_build():
	pygame.init()
	screen = pygame.display.set_mode((800,800))
	pygame.display.set_caption('a new display')
	bg_color = (0,0,255)
	while True:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				sys.exit()
		screen.fill(bg_color)
		my_like_image = Like_image(screen)
		my_like_image.blitme()
		pygame.display.flip()
display_build()

like_image.py

import pygame
class Like_image():
	def __init__(self,screen):
		self.screen = screen
		self.image = pygame.image.load('images/ship.bmp')
		self.rect = self.image.get_rect()
		self.screen_rect = screen.get_rect()
		self.rect.centerx = self.screen_rect.centerx
		self.rect.bottom = self.screen_rect.bottom
	def blitme(self):
		self.screen.blit(self.image,self.rect)

12-3
编写一个程序,开始时屏幕中央有一个小火箭,而玩家可使用四个方向键上下左右移动火箭,务必确保火箭不会移到屏幕外面

import sys 
import pygame
from pygame.sprite import Group
pygame.init()
screen = pygame.display.set_mode((1000,1000))
pygame.display.set_caption('12-2')
image = pygame.image.load('images/my_love_dog.bmp')
bullet_image = pygame.image.load('images/bullet.bmp')
update_image=pygame.transform.scale(image,(150,100))
update_bullet_image=pygame.transform.scale(bullet_image,(20,40))
position_x = 400
position_y = 500
position = (position_x,position_y)
position_bullet_x = position_x + 65
position_bullet_y = position_y - 40
flag_right = False
flag_left = False
flag_up = False
flag_down = False
while True:
	position = (position_x,position_y)
	position_bullet = (position_bullet_x,position_bullet_y)
	position_bullet_y = position_bullet_y - 10
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_RIGHT:
				flag_right = True
			elif event.key == pygame.K_LEFT:
				flag_left = True
			elif event.key == pygame.K_UP:
				flag_up = True
			elif event.key == pygame.K_DOWN:
				flag_down = True
		elif event.type == pygame.KEYUP:
			if event.key == pygame.K_RIGHT:
				flag_right = False
			elif event.key == pygame.K_LEFT:
				flag_left = False
			elif event.key == pygame.K_UP:
				flag_up = False
			elif event.key == pygame.K_DOWN:
				flag_down = False
	if position_x == 0:
		flag_left = False
	if position_x ==850:
		flag_right = False
	if position_y == 0:
		flag_up = False
	if position_y == 900:
		flag_down = False
	if flag_right:
		position_x = position_x + 10
	if flag_left:
		position_x = position_x - 10
	if flag_up:
		position_y = position_y - 10
	if flag_down:
		position_y = position_y + 10
						
	screen.fill((130,130,130))
	screen.blit(update_image,position)
	screen.blit(update_bullet_image,position_bullet)
	pygame.display.flip()


运行结果在这里插入图片描述
实现了图片上下左右移动,速度是10个像素。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值