Python 输出中的计数不正确

Python 输出中的计数不正确,python,Python,我做了一个简单的猜谜游戏来练习。程序正常运行,但给出的输出值错误 代码如下: import random welcome_phrase = "Hi there. What's your name?" print("{:s}".format(welcome_phrase)) user_name = input("Name: ") print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1

我做了一个简单的猜谜游戏来练习。程序正常运行,但给出的输出值错误

代码如下:

import random

welcome_phrase = "Hi there. What's your name?"
print("{:s}".format(welcome_phrase))

user_name = input("Name: ")
print("Hey {:s}, I am Crash. Let's play a game. I am thinking of a number between 1 and 20. Can you guess the number?".format(user_name))

attempts = 5
secret_num = random.randint(1,20)

for attempt in range (attempts):
    guess = int(input("Guess the number: "))
    if guess > secret_num:
        print("Your guess is higher than the number. Try again")
    elif guess < secret_num:
        print("Your guess is lower than the number. Try again.")
    else:
        print("Well done! {:d} is the right number.".format(guess))
        print("It took you {:d} attempts.".format(attempt))
        break

if guess != secret_num:
    print("Sorry, you have used up all your chances.")
    print("The number was {:d}".format(secret_num))
随机导入
欢迎您,您好,您叫什么名字
打印(“{:s}”。格式(欢迎短语))
用户名=输入(“名称:”)
print(“嘿{:s},我是Crash。让我们玩一个游戏。我想到了一个介于1和20之间的数字。你能猜出这个数字吗?”.format(用户名))
尝试次数=5次
secret_num=random.randint(1,20)
对于范围内的尝试(尝试次数):
猜测=int(输入(“猜测数字:”)
如果猜测>秘密数量:
打印(“您的猜测高于数字。请重试”)
elif guess
以下是输出:

正如您在上图中所看到的,尽管有3次尝试猜测正确的数字是显而易见的,但Python只计算了2次尝试。有人能告诉我如何解决这个问题吗?

您可以更改

for attempt in range (attempts):


要解决此问题,as范围从0开始。

请在此处复制并粘贴控制台输出。还要注意,Python是一种0索引语言,因此尝试0、1和2总共是3次尝试
range
从0开始。在这种情况下,最好使用while循环和break语句
for attempt in range (1,attempts+1):