Test sum function

Asked

Viewed 465 times

2

Hello everybody all right? First I want to say that it is a pleasure to be part of this community. I’m studying python on my own, I found a course per application, I’m already in the functions part but I didn’t understand the syntax of the command correctly. I would like to do something simple, implement a summation function and a function to test the sum, just for didactic purposes. But my code shows nothing on the screen, follows:

def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

3 answers

4

You have defined two functions one testa_soma and the summing up, but you didn’t call any of them, it should be like this:

def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

testa_soma()

See that on the last line I put the call.

3

For a function to be executed, you have to call it:

def soma (x, y):
    return (x + y)

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')

testa_soma()
  • Thank you very much, guys!!

0

You can also use the module doctest. With it you can create the direct tests on docstring of the function, which centralizes the tests together with the function and assists the documentation of the function.

def soma(x, y):
    """ Retorna a soma de dois números.

    Parâmetros:
        x, y: números a serem somados.

    Retorno:
        Resultado da soma dos números de entrada.

    Exemplos:

    >>> soma(10, 20)
    30
    >>> soma(0, 5)
    5
    >>> soma(-1, -3)
    -4
    >>> soma(-2, 3)
    1
    """
    return x + y

So, in the file, just include:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

And when you run the file, the tests will be checked. If it does not produce any output, it is because all the tests have been successful.

  • and if I want to call the function testa_soma inside the function sum? is possible? type for her already pull the test alone

  • @Leandrosargi this is not good to do, because when calling the sum function you expect it to be just summed the numbers and not test the function; generates side effects.

  • It’s okay, thanks buddy.

  • I asked that because in my class, there’s an exercise to play a game. The name is NIM game, will be used 6 functions, and as it ends one, it passes to another function and performs. I don’t know if I missed any part of the theory, but I have no idea how to make that passage

Browser other questions tagged

You are not signed in. Login or sign up in order to post.