Test sum function

2

Hello everyone, how are you? First of all 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 did not understand correctly the syntax of the command. I'd like to do something simple, implement a sum function and a function to test the sum, just for didactic purposes. But my code does not display anything on the screen, it follows:

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

def testa_soma():
    if (soma(10, 20) == 30):
        print ('correto')
    
asked by anonymous 13.06.2018 / 14:20

3 answers

4

You defined two functions a testa_soma and the sum , but did not call any of them, it should look like this:

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

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

testa_soma()

See that in the last line I placed the call.

    
13.06.2018 / 14:32
3

For a function to run, you have to call it:

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

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

testa_soma()
    
13.06.2018 / 14:31
0

You can also use the doctest module. With it you can create tests directly in the docstring of the function, which centralizes the tests along with the function and assists in 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's because all tests were successful.

    
13.06.2018 / 15:10