大家好,小编来为大家解答以下问题,笨办法学python3电子版下载,笨办法学python3 pdf百度云,今天让我们一起来看看吧!
Source code download: 本文相关源码
练习36 设计和调试
知识点:
if语句的规则
1.每一个“if 语句”必须包含一个 else。
2.如果这个 else 永远都不应该被执行到,因为它本身没有任何意义,那你必须在 else 语句后面使用一个叫做 die 的函数,让它打印出错误信息并且死给你看,就像我们上节课做的那样,按照这个思路你可以找到很多错误python如何画九朵花。(满足1.2.更多是python规范,否则if不一定要有else。)
3.if 语句”的嵌套不要超过 2 层,最好尽量保持只有 1 层。
4.把“if 语句”当做段落来对待,其中的每一个 if, elif, else 就跟段落中的句子一样。在每句前后留一个空行以作区分。
5.你的布尔测试应该很简单,如果它们很复杂的话,你需要将它们的运算事先放到一个变量里,并且为变量取一个好名字。
循环的规则
1.只有在循环永不停止时使用“while循环”,这意味着你可能永远都用不到。这条只有 Python 中成立,其他的语言另当别论。
2.其他类型的循环都使用“for循环”,尤其是在循环的对象数量固定或者有限的情况下。
调试建议
1.不要使用调试器(“debugger”)。输出的信息太多,而且大部分没有用,或者只会让你更加困惑。
2.最好的调试程序的方法是用 print 在每个你想要检查的关键环节将关键变量打印出来,从而检查那里是否有错。
3.让程序一部分一部分地运行起来。不要等一个很长的脚本写完后才去运行它。写一点,运行一点,再修改一点。
课后练习
写软件最好的方法就是一点一点来,在整理完地图逻辑之后就可以做以下步骤:
1、列出要完成的任务,画出流程图。
2、从简单的任务入手,写代码。
3、在源代码文件中写注释,注释要完成的任务。
4、在注释下面写代码。
5、写完部分代码后,运行代码,观察是否工作。
6、循环“写代码,运行测试,修改代码”这个过程
7、写完这个简单的任务,开始下一个相对简单的任务,重复上述步骤。
在工作的过程中,通过移除不必要的任务以及添加新任务来更新你的任务列表。
写一个和上节练习类似的游戏,同类的任何题材的游戏都可以。你可以花一个星期时间让它尽可能有趣一些。作为附加练习,你可以尽量多使用列表、函数、以及模组(还记得习题 13 吗?),而且尽量多写一些新的 Python 代码让你的游戏跑起来。
游戏流程图如下:
代码如下:
from sys import exit
def END():
print("Game over, sorry.")
exit(0)
def animal_room():
print("\nwelcome to animal_room.")
print("How much are you willing to pay?")
choice1 = int(input("> "))
if choice1 <= 10:
print("Let's feeding animals.")
END()
else:
animal = ["pig","dog","cat","duck"]
print("open the door. There are many animals .")
print("Which animal do you like? You can input 0-3.")
n = int(input(">>> "))
animal_like = animal.pop(n)
print(f"The animal is {animal_like}")
Garden()
def Garden():
land = ["grass","pond","tree","flower"]
print("\nWelcom to beautiful world!")
for i in range(4):
landscape = land[i]
print(f"you can choice {i},where you can see {landscape}.")
animal_gar =int(input("Do you see animal from animal_room. 0 or 1."))
choice2 = int(input("which number do you choose? 0-3"))
landscape_like = land[choice2]
if animal_gar and landscape_like:
print(f"you can see {landscape_like} here.")
print("Good, you win.")
exit(0)
else:
END()
def ticket():
print("Hi, welcome to the game. ")
print("Now,you have 50 yuan. How much are you willing to give?")
num = int(input("> "))
if num < 20:
animal_room()
elif num >= 20 and num <= 40:
Garden()
else:
print("So good,you win.")
ticket()
简单输出:
Hi, welcome to the game.
Now,you have 50 yuan. How much are you willing to give?
> 10
welcome to animal_room.
How much are you willing to pay?
> 20
open the door. There are many animals .
Which animal do you like? You can input 0-3.
>>> 1
The animal is dog
Welcom to beautiful world!
you can choice 0,where you can see grass.
you can choice 1,where you can see pond.
you can choice 2,where you can see tree.
you can choice 3,where you can see flower.
Do you see animal from animal_room. 0 or 1.1
which number do you choose? 0-30
you can see grass here.
Good, you win.