我试图在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 07:06:15
我将提出四个建议,这些建议旨在使您的代码更简洁和更简单:
6,然后从它中进行计数,而不是根据它来计算;for而不是while,这样您就不必手动增加/减少guesses的数量,并使用else来确定循环break的值(即猜测之外);if: elif: else:而不是单独的if;以及str.format。这将使代码类似于:
attempts = 6
for attempt in range(attempts, 0, -1):
print("You have {0} attempts left.".format(attempt))
number = int(input(...))
if number < random:
# too low
elif number > random:
# too high
else:
if attempt > (attempts // 2):
# great
else:
# OK
break
else:
# out of guesseshttps://stackoverflow.com/questions/23842115
复制相似问题