如何告诉用户Python中剩余的尝试次数

时间:2014-05-24 06:47:46

标签: python

我正在尝试在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)

谢谢,非常感谢任何帮助!

4 个答案:

答案 0 :(得分:2)

print('attempts left: ', 6 - attempts)

答案 1 :(得分:1)

print(6 - attempts, "attempts left")

答案 2 :(得分:1)

您的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")

答案 3 :(得分:1)

我会提出四条建议,这些建议可以使您的代码更清晰,更简单:

  1. 将&#34;幻数&#34; 6并从中倒数,而不是取而代之;
  2. 使用for而不是while,因此您不必手动增加/减少guesses的数量,并使用else确定是否循环break s(即猜测不到);
  3. 使用if: elif: else:而不是单独if;和
  4. 使用str.format
  5. 这会使代码类似:

    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 guesses