Help with simple program of function and sum

Asked

Viewed 103 times

0

Gentlemen,

I’m trying to solve the following exercise:

Exercise 2: Write a Python function, called soma_n, that takes an integer number, n, and computes the sum 1 + 2 + ... + n, if n > 0, or -1 + -2 + ... + -n, if n < 0. If n = 0, the sum is zero.

Your function should check whether the argument you receive is a number integer, through the isinstance(n, int) function, where n is the argument received. Otherwise the function should generate an error of the type Valueerror, through the raise statement Valueerror('soma_n: The limit must be an integer. '). For example,

soma_n(3) 6 soma_n(-3) -6 soma_n(0) 0 soma_n('anc') Traceback (Most recent call last): ... builtins.Valueerror: soma_n: The limit has to be an integer.

I don’t understand what should be done to adapt the isinstance(n, int) function to my code which is as follows:

def soma_n (n):

    soma = 0

    while (n != 0):
        if n > 0:
            soma = soma + n
            n = n - 1

        else:
            soma = soma + n
            n = n + 1          
    return (soma)

I do not understand this function isinstance, could help me how to use it next to my code?

Thanks in advance.

1 answer

2

Just add the isinstance(n, int) in the first line of its function. The isinstance checks if the value is an instance of a specific type and returns a boolean value. So you can use a conditional where, if the value n not be an integer, an error will be thrown:

def soma_n(n):
    if not isinstance(n,int):
        raise TypeError('Passe para o parâmetro "n" um número inteiro.')
    soma = 0

    while n != 0:
        if n > 0:
            soma += n
            n += -1

        else:
            soma += n
            n += 1         
    return soma

Detail: This type of error must be a TypeError. If you wanted for example that the value was not 10, you could use the ValueError, but we are talking about value types. How do you want the value passed in the parameter to be only one int and not a str, bool or float, you must launch a TypeError

Browser other questions tagged

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