我试图在python中做一个随机数游戏,在那里计算机必须生成一个介于1到20之间的数字,你必须猜出来。我已经将猜测的数量限制在6。如果用户猜错了,如何打印用户的猜测?这是我的代码:
import random
attempts = 0
name = input("What is your name? ")
random = random.randint(1, 20)
print(name + ",","I'm thinking of a number between 1 and 20, What is it?")
while attempts < 6:
number = int(input("Type your guess: "))
attempts = attempts + 1
int(print(attempts,"attemps left")) #This is the code to tell the user how many attempts left
if number < random:
print("Too low. Try something higher")
if number > random:
print("Too high. Try something lower")
if number == random:
break
if number == random:
if attempts <= 3:
print("Well done,",name + "! It took you only",attempts,"attempts")
if attempts >= 4:
print("Well done,",name + "! It took you",attempts,"attempts. Athough, next time try to get three attempts or lower")
if number != random:
print("Sorry. All your attempts have been used up. The number I was thinking of was",random)谢谢,任何帮助都是非常感谢的!
发布于 2014-05-24 06:51:43
您的attempts变量计算使用的尝试次数。由于6是限制,所以6 - attempts是剩下的尝试数:
print(6 - attempts, "attempts left")(不需要将其封装在int调用中。我不知道你为什么那样做。)
顺便说一句,为尽可能多的尝试编写6可能会模糊6的含义,如果要将限制更改为7,则很难找到需要更改的所有位置。可能值得用描述性名称创建一个变量:
max_attempts = 6
...
while attempts < max_attempts:
...
print(max_attempts - attempts, "attempts left")发布于 2014-05-24 06:50:14
print('attempts left: ', 6 - attempts)发布于 2014-05-24 06:51:41
print(6 - attempts, "attempts left")https://stackoverflow.com/questions/23842115
复制相似问题