当我第五次猜中数字也会出现“很遗憾”
[Python] 纯文本查看 复制代码 import random
class GuessGame:
def __init__(self, min_num, max_num, choice):
self.min_num = min_num
self.max_num = max_num
self.target = random.randint(min_num, max_num)
self.choice = choice
def guess(self):
choice = self.choice
min_num = self.min_num
max_num = self.max_num
while choice > 0:
choice -= 1
try:
num = int(input("请输入%d - %d之间的幸运数字:" % (min_num, max_num)))
if num < min_num or num >max_num:
raise ValueError(e)
except ValueError as e:
print("请输入有效数字:")
continue
if num == self.target:
print("恭喜你猜中了!")
game = GuessGame(1, 100, 5)
game.guess()
elif num < self.target:
min_num = num
print("你猜小了,还剩%d次机会, 幸运数字区间在%d — %d。" % (choice, min_num, max_num))
else:
max_num = num
print("你猜大了,,还剩%d次机会, 幸运数字区间在%d — %d。" % (choice, min_num, max_num))
else:
print("很遗憾,%d次机会都用完了,正确答案是%d。" % (self.choice, self.target))
game = GuessGame(1, 100, 5)
game.guess()
if __name__ == "__main__":
game = GuessGame(1, 100, 5)
game.guess() |