笨办法学python 习题35(分支和函数)
from sys import exit#这行就是把sys模块中的exit函数引用进来,sys.exit()是一个比较纯粹的程序退出函数def gold_room():# 定义函数 gold_room print("This room is full of gold. How much do you take?")choice = input(">")# 输出提示信息">",接收输入内容,并将输入的内容赋值给变量 choiceif "0" in choice or "1" in choice:# 如果变量 choice 的值为 0 或者 1how_much = int(choice)# 调用 int()函数,将变量 choice 的值转换为整型,并赋值给变量 how_muchelse:# 如果变量 choice 的值不是 0 或 1dead("Man,learn to type a number.")# 调用 dead() 函数,打印字符串 if how_much < 50:print("Nice,you're not greedy,you win!")exit(0) # 程序正常退出else:dead("You greedy bastard!") # 调用 dead() 函数,打印字符串 def bear_room():print("There is a bear here.")print("The bear has a bunch of honey.")print("The fat bear is in front of another door.")print("How are you going to move the bear?")bear_moved = False# 将布尔值 False 赋值给变量 bear_moved while True: # 判断布尔表达式的真假,如果为 True,则一直循环直到表达式为False为止choice = input(">")if choice == "take honey":dead("The bear looks at you then slaps your face off.")elif choice == "taunt bear" and not bear_moved:print("The bear has moved from the door.")print("You can go through it now.")bear_moved = Trueelif choice == "taunt bear" and bear_moved:dead("The bear gets pissed off and chews your leg off.")elif choice == "open door" and bear_moved:gold_room()else:print("I got no idea what that means.")def cthulhu_room():print("Here you see the great evil Cthulhu.")print("He,it,whatever stares at you and you go insane.")print("Do you flee for your life or eat your head?")choice = input(">")if "flee" in choice:start()# 调用 start() 函数elif "head" in choice:# 如果变量 choice 的值为 headdead("Well that was tasty!")else:# 如果两者都不是则调用 cthulhu_room 函数cthulhu_room()def dead(why):# 定义函数 dead() ,位置参数为 whyprint(why,"Good job!")exit(0)def start():print("You are in a dark room.")print("There is a door to your right and left.")print("Which one do you take?")choice = input(">")if choice == "left":bear_room()elif choice == "right":cthulhu_room()else:dead("You stumble around the room until you starve.")start()
运行结果
(base) PS D:\pythonProject\the_stupid_way_to_learn_python> python ex35.py
You are in a dark room.
There is a door to your right and left.
Which one do you take?
>left
There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
>taunt bear
The bear has moved from the door.
You can go through it now.
>open door
This room is full of gold. How much do you take?
>1000
You greedy bastard! Good job!
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
