python - 如何在 python 中重置 while 循环,以使所有条件都与启动时相同?
问题描述
我正在尝试编写一个游戏:
- 抽取一个随机数
- 要求用户输入猜测
- 如果猜测太低或太高,它将相应地打印一条语句
- 如果它需要用户超过 3 次猜测它会打印(“三击你出局”)
- 如果用户猜到了它会打印(“你猜到了”)
- 在这两种情况下,它都会询问用户是否想再次播放。
- 如果是,程序应该生成新的数字并且罢工应该回到零
- 如果没有,打破
我遇到的问题是,当用户猜到数字或丢失时,我无法弄清楚如何生成新的随机数并将罢工重置为零。
import random
game_stop = False
strikes = 0
random_list = [1,2,3,4,5,6,7,8,9,]
random_number = random.choice(random_list)
def play_again():
play_again = input("play again?: ")
if play_again == "yes":
strikes = 0
game_stop = False
return random.choice(random_list)
while not game_stop:
strikes = strikes + 1
guess = input("enter guess: ")
if guess == "exit":
break
if int(guess) > random_number:
print("too high")
elif int(guess) < random_number:
print("too low")
else:
print("you guessed it!")
print("It took you " + str(strikes) + " tries!")
play_again()
if strikes > 2:
print("three strikes your out!")
play_again() '''
解决方案
修改你的 play_again() 函数,使用raw_input
代替input
:
def play_again():
play_again = raw_input("play again?: ")
if play_again == "yes":
strikes = 0
game_stop = False
return random.choice(random_list)
推荐阅读
- javascript - 仅限 ES5:在遍历数组中的各种值后找到匹配项时返回值
- python - 从文件中读取不同长度的数字
- kubernetes - 如果 https 流量,我如何将入口转发到 ssl 端口(443)
- android - 使用导航编辑器从登录活动导航到主要活动
- fortran - 如何从 Fortran 中元素或纯子例程中的错误中获取回溯
- sap-gui - 脚本录制和播放,以及excel
- c# - C#队列一个任务,当它将从队列中执行时返回结果
- django - celery 任务触发后,如何授予对两个 mongodb 数据库的访问权限,以同步写入记录?
- apache-spark - GBTClassifier 如何处理二进制分类的不平衡数据?
- python - TypeError: 'float' 对象不能用 apply lambda 迭代