笨方法学python
习题29、30、31
29:
if语句:
运行结果:
1.你认为if对他的下一行代码做了什么?
if语句伪代码创建了一个所谓的”分支“,就跟RPG游戏中的情节分支一样。if语句告诉你的脚本:如果这个布尔表达式为真,就运行下一行代码,否则就跳过这一段。
2.为什么if语句的下一行需要四个空格的缩进?
行尾的而冒号的作用是告诉python接下来你要创建一个新的代码块,缩进告诉python这些代码处于该代码块中,这跟你前面创建函数时的冒号一样。
3.如果不缩进会发生什么事情?
如果他没有缩进,你应该会看到Python报错。Python的规则里,只要一行以冒号(:)结尾,他接下来的内容就应该有缩进。
4.把习题27中的其他布尔表达式放到if语句中会不会也可以运行呢?
可以,我在代码中加入了1 != 0的布尔表达式。
5.如果把变量people. cats 和 dogs 的初始值政掉会发生什么事情?
因为你比较的对象是数值,所以,如果把这些数值改掉的话,某些位置的if语句会被求值为 True而它下面的代码块将被运行,
30:
else和if:
运行结果:
1.猜想一下elif和else的功能。
和if一样,创建其他情况的分支。
3.试着写一些复杂的布尔表达式,如cars > people or trunks < cars。
运行结果:
如果多个elif块都是True,Python会怎么处理?
Python只会运行他遇到的时True的第一个快,所以只有第一个为True的块会运行。
31做出决定:
print("""You enter a dark room with two doors.
Do you go through door 1 or door 2?""")
door = input("> ")
if door == "1":
print("There's a giant bear here eating a chese cake.")
print("What do you do?")
print("1. Take the cake.")
print("2. Scream at the bear.")
bear = input("> ")
if bear == "1":
print("The bear eats your face off. Good job!")
elif bear == "2":
print("The bear eats your legs off. Good job!")
else:
print(f"Well, doing {bear} is probably better.")
print("Bear runs away.")
elif door == "2":
print("You star into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")
instanity = input("> ")
if instanity == "1" or instanity == "2":
print("Your body survies powered by a mind of jello.")
print("Good job!")
else:
print("The instanity rots your eyes into a pool of muck.")
print("Good job!")
else:
print("You stumble around and fall on a knife and die. Good job!")
运行结果:
1.为游戏添加新的部分,改变玩家傲决定的位置,尽自己的能力扩展这个游戏,不过别把游戏弄得太怪异了。
2.写一个全新的游戏,也许你不喜欢这个游戏,所以就写个新的吧。这是你的计算机,你想干什么就干什么。
运行结果:
第二问我的回答纯属搞笑,如有冒犯,在此道歉。对不起!