1
题目:猜数字游戏 输入:一个整数 n,表示答案的范围在 1~n 之间;一个整数 m,表示
玩家最多可以猜 m 次。 输出:如果玩家在 m 次之内猜中了答案,输出"Congratulations!
You guessed the number.“,否则输出"Game over. The number is x.”,其中 x 为答
案。 样例输入: 10 3 样例输出: Please guess a number between 1 and 10: 5 W
rong answer. You have 2 chances left. Please guess a number between 1 and 10
: 8 Wrong answer. You have 1 chances left. Please guess a number between 1 a
nd 10: 7 Congratulations! You guessed the number. 解题思路:
1. 生成一个 1~n 之间的随机整数作为答案。
2. 循环 m 次,每次让玩家输入一个猜测的数字,判断是否猜中。
3. 如果猜中,输出"Congratulations! You guessed the number.“,并结束程序;否则输出
"Wrong answer. You have x chances left.”,其中 x 为剩余的猜测次数。
4. 如果循环结束仍未猜中,输出"Game over. The number is x.",其中 x 为答案。 代码文
件:
import random
n = int(input("Please enter the range of the answer: "))
m = int(input("Please enter the maximum number of guesses: "))
answer = random.randint(1, n)
chances = m
while chances > 0:
guess = int(input("Please guess a number between 1 and {}: ".format(n
)))
if guess == answer:
print("Congratulations! You guessed the number.")
break
else:
chances -= 1
if chances == 0:
print("Game over. The number is {}.".format(answer))
else:
print("Wrong answer. You have {} chances left.".format(chance
s))