Search code examples
pythonmachine-learningartificial-intelligence

WAP that takes an integer N from keyboard, computes and display the sum of the numbers from N to (2*N) if N is nonnegative. If N is negative then


WAP that reads an integer N from keyboard, computes and display the sum of the numbers from N to (2N) if N is nonnegative. If N is negative number, then it is the sum of the number from (2n) to n. The starting and ending points are included in the sum.


Solution

  • def myfunc(n):
    ls=[]
    
    #we are going to append all the number from n to 2n
    #and return their sum
    #since 2n is also included, therefore end point of loop must be 2n+1
    
    if n<0:
        for i in range(n,2*n-1,-1):
           ls.append(i)
    else:
        for i in range (n,2*n+1):
            ls.append(i)
    return sum(ls)