python - 如何使此函数中的代码重复?(Python)
问题描述
我正在编写一个游戏,我想要重做代码的某个部分。代码中的注释显示了我想要重做的内容。
import random
def getRandom():
#this is the code I want to rerun (guess code) but I don't want to reset "players" and "lives"
players = 10
lives = 5
myGuess = input("What number do you choose")
compGuess = random.randint(1,5)
compGuess = int(compGuess)
print(f"Computer chose {compGuess}")
if compGuess == myGuess:
players = players - compGuess
print(f"You took out {compGuess} players")
print(f"There are {players} players left")
#run guess code
else:
lives -= 1
print(f"You lost a life! You now have {lives} lives remaining")
#run guess
getRandom()
解决方案
您需要添加一个循环。考虑一下您的循环条件是什么,以及循环内或循环外需要什么。我认为这样的东西是你正在寻找的。
import random
def getRandom():
players = 10
lives = 5
while(lives > 0):
myGuess = input("What number do you choose")
compGuess = random.randint(1,5)
compGuess = int(compGuess)
print(f"Computer chose {compGuess}")
if compGuess == myGuess:
players = players - compGuess
print(f"You took out {compGuess} players")
print(f"There are {players} players left")
else:
lives -= 1
print(f"You lost a life! You now have {lives} lives remaining")
getRandom()
推荐阅读
- laravel - Baum/Node - 从多个 id 获取后代
- c# - ASP.NET 标识 - 简化
- java - 无效令牌不包含资源 id (oauth2-resource)
- c - 如何优化此代码以缩短运行时间?
- mongodb - 用于海量数据的 MongoDB
- c++ - C++ 语法解释中的赋值运算符重载
- javascript - 回调被多次触发,我不知道为什么
- python - pip 已安装模块但 python 给出导入错误
- java - java opencv Features2d.drawMatches - 断言失败或 NullPointerException
- javascript - PHP 和 Vue 集成