python自学项目day2.定时器time和随机数模块random以及while循环

利用定时器time添加2秒间歇停顿

利用随机数模块random添加随机选取

import random
import time

print("You have reached the opening of a cave you decide to arm yourself with an")

time.sleep(2)

quest_item = input("think of an object\n")

print("you look in you backpack for",quest_item)

time.sleep(2)

print("you could not find",quest_item)
print("you select any item that comes to hand from the backpack instead\n")

time.sleep(2)

inventory = ["Torch","Pencil","Rubber band","Capapult","Rope"]

print(random.choice(inventory))

条件判断

import time

print("You are standing on a path at the edge of a jungle.There is a cave to your left and a beach to your right")

time.sleep(0.5)

direction1 = input("Do you want to go left or right?")

if direction1 == "left":
  print("You walk to the cave and notice there is an openning")

elif direction1 == "right":
  print("you walk to the beach but remember you do no have any swimwear.")

else:
  print("you should think for a while")

添加while循环(只要...条件存在,就一直做...)

python自学项目day2.定时器time和随机数模块random以及while循环_第1张图片
python自学项目day2.定时器time和随机数模块random以及while循环_第2张图片

因为在while后面的表达式永远成立,所以print一直会进行下去
在终端中按ctrl+c停止运行

一直循环无中止,无视大小写

#loop until we get a recognised response
while True:
  direction1 = input("Do you want to go left or right?")
  direction1 = direction1.lower() # transform input into lower format
  if direction1 == "left":
    print("you walk to the cave and notice there is an opening.")
  elif direction1 == "right":
    print("you walk to the beach but remember you do not have any swimwear.")
  else:
    print("You think for a while")
python自学项目day2.定时器time和随机数模块random以及while循环_第3张图片
Paste_Image.png

改进添加break并引入hp变量作为生命值

import time

#Define variables
hp = 30

print("you are standing on a path at the edge of a jungle. There is a cave to your")
time.sleep(1)

#loop until we get a recognised response
while True:
  direction1 = input("Do you want to go left or right?")
  direction1 = direction1.lower() # transform input into lower format
  if direction1 == "left":
    print("you walk to the cave and notice there is an opening.")
    print("A small snake bites you,and you lose 20 health points")
    hp -= 30
    if hp <= 0:
       print("You are dead.I am sorry.")
       break
  elif direction1 == "right":
    print("you walk to the beach but remember you do not have any swimwear.")
    print("the cool water revitalizes you. you have never felt more alive, gain 70 HP")
    hp += 70
    print("You've got win")
    break
  else:
    print("You think for a while")
    hp -= 10
    if hp <= 0:
       print("You are dead.I am sorry.")
       break
  print("you now have",hp,"health points")
# check health points after the player has made a move
python自学项目day2.定时器time和随机数模块random以及while循环_第4张图片
Paste_Image.png

你可能感兴趣的:(python自学项目day2.定时器time和随机数模块random以及while循环)