简体   繁体   English

如何在 for 循环后打印平均值?

[英]How do I print the average value after the for loop?

I am new to Python and I am making a program in which the computer generates a random number within a certain range and then tries to guess the number it picked.我是 Python 的新手,我正在制作一个程序,其中计算机在一定范围内生成一个随机数,然后尝试猜测它选择的数字。 I am making the computer guess multiple numbers (in this case 2) by using a for loop.我通过使用 for 循环让计算机猜测多个数字(在本例中为 2)。 I am also keeping track of the number of guesses it took after each iteration of the loop.我还跟踪每次循环迭代后的猜测次数。 After that, I am going to take average of those guesses after the loop has finished.之后,我将在循环完成后取这些猜测的平均值。 However, when I try to get the average it doesn't print.但是,当我尝试获得平均值时,它不会打印。 I don't know what's wrong with the code.我不知道代码有什么问题。 Can someone help me with this issue?有人可以帮我解决这个问题吗?

import random

def guess():
        the_num = random.randint(1, 100)
        print('The number to guess is',the_num)
        comp_guess = random.randint(1, 100)
        print('The computer guesses ', comp_guess)
        tries = 1

        while comp_guess != the_num:
            print('The computer guesses ', comp_guess)
            tries += 1
            if comp_guess == the_num:
                break
            else:
                comp_guess = random.randint(1, 100)

        for i in range(2):
            guess()

        print('The computer took',tries,'guesses')
        print('The computer guessed it right!')
        print('The computer guessed',(tries/2),'times on average') 
        # Trying to calculate the average number of guesses after the loop is finished

By calling guess inside itself you are creating a recursive function that has no base case, hence it will never end.通过在其内部调用 guess ,您正在创建一个没有基本情况的递归函数,因此它永远不会结束。 A better approach is to make the loop occur in the actual code.更好的方法是让循环发生在实际代码中。 In the following code, I also took the liberty to make the function flexible by allowing it to be called any number of times dependent on input.在下面的代码中,我还允许根据输入调用任意次数,从而使函数变得灵活。

import random

def guess(num_loops):
    total_tries = 0
    for i in range(num_loops):
        the_num = random.randint(1, 100)
        print('The number to guess is',the_num)
        comp_guess = random.randint(1, 100)
        print('The computer guesses ', comp_guess)
        tries = 1

        while comp_guess != the_num:
           # print('The computer guesses ', comp_guess)
            tries += 1
            print(tries)
            if comp_guess == the_num:
                break
            else:
                comp_guess = random.randint(1, 100)
        total_tries += tries
        print('The computer took',tries,'guesses')
        print('The computer guessed it right!')
    print('The computer guessed',(total_tries/num_loops),'times on average') 
    # Trying to calculate the average number of guesses after the loop is finished

guess(2)

What you have there is recursion which is when a function calls itself.您拥有的是递归,即函数调用自身时。

In your case you do not need recursion, just one function and code that calls it.在您的情况下,您不需要递归,只需一个函数和调用它的代码。

Your function should do one thing and do it well.你的函数应该做一件事并且做得很好。 In this case your function is for the computer to guess a number it generated.在这种情况下,您的功能是让计算机猜测它生成的数字。

def guess():
    the_num = random.randint(1, 100)
    print('The number to guess is',the_num)
    comp_guess = random.randint(1, 100)
    print('The computer guesses ', comp_guess)
    tries = 1

    while comp_guess != the_num:
        print('The computer guesses ', comp_guess)
        tries += 1
        if comp_guess == the_num:
            break
        else:
            comp_guess = random.randint(1, 100)

Now it seems you want this code to run twice.现在看来您希望这段代码运行两次。 So the computer guesses multiple numbers and has many tries for each number it's trying to guess.因此,计算机会猜测多个数字,并针对它尝试猜测的每个数字进行多次尝试。

In this case you just need to call the function multiple times outside the function.在这种情况下,您只需要在函数外多次调用该函数。

for i in range(2):
    guess()

This code isn't indented and isn't part of the function.这段代码没有缩进,也不是函数的一部分。

To learn more about functions you can go to the Python Docs: https://docs.python.org/3/tutorial/controlflow.html#defining-functions要了解有关函数的更多信息,您可以访问 Python 文档: https : //docs.python.org/3/tutorial/controlflow.html#defining-functions

I'll also link to a book I highly recommend: http://inventwithpython.com/chapter6.html我还将链接到我强烈推荐的一本书: http : //inventwithpython.com/chapter6.html

These resources will help you learn more about functions.这些资源将帮助您了解有关函数的更多信息。

Hope this answer helped you!希望这个回答对你有帮助! If you have any further questions please post a comment below!如果您还有其他问题,请在下面发表评论!

You don't need or want the guess() function to call itself like that because the way it's currently coded it will never return.您不需要或不希望guess()函数像这样调用自己,因为它当前的编码方式永远不会返回。

Here's how I would reorganize your code to avoid the need to do that:以下是我将如何重新组织您的代码以避免需要这样做:

import random

NUM_GUESSES = 2

def guess():
    the_num = random.randint(1, 100)
    print('The number to guess is', the_num)

    tries = 0
    comp_guess = None
    while comp_guess != the_num:
        comp_guess = random.randint(1, 100)
        print('The computer guesses', comp_guess)
        tries += 1

    return tries

total_tries = 0
for i in range(NUM_GUESSES):
    tries = guess()
    total_tries += tries
    print('The computer took', tries, 'guesses')
    print('The computer guessed it right!')

average = total_tries / NUM_GUESSES
print('The computer guessed', average, 'times on average')

Sample output:示例输出:

The number to guess is 88
The computer guesses 58
The computer guesses 19
The computer guesses 55
The computer guesses 16
The computer guesses 85
The computer guesses 24
The computer guesses 76
The computer guesses 36
The computer guesses 18
The computer guesses 58
The computer guesses 27
The computer guesses 1
The computer guesses 2
The computer guesses 100
The computer guesses 74
The computer guesses 49
The computer guesses 26
The computer guesses 76
The computer guesses 28
The computer guesses 38
The computer guesses 27
The computer guesses 100
The computer guesses 7
The computer guesses 50
The computer guesses 54
The computer guesses 80
The computer guesses 36
The computer guesses 39
The computer guesses 61
The computer guesses 28
The computer guesses 11
The computer guesses 38
The computer guesses 27
The computer guesses 29
The computer guesses 70
The computer guesses 45
The computer guesses 18
The computer guesses 65
The computer guesses 40
The computer guesses 88
The computer took 40 guesses
The computer guessed it right!
The number to guess is 99
The computer guesses 73
The computer guesses 99
The computer took 2 guesses
The computer guessed it right!
The computer guessed 21.0 times on average

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM