Ask Question

Write a function called sum_first_integers that takes a single positive integer parameter. The function should also return a positive integer. In particular, it should return the sum of the positive integers from 1 to the value passed into the function. For example, if 5 is passed into the function, it should return 15 because that is the number you get when you add 1 + 2 + 3 + 4 + 5. Hint: We recommend using the range function and a for loop.

+4
Answers (1)
  1. 12 April, 22:43
    0
    def sum_first_integers (n):

    if n < = 0 or type (n) ! = int:

    raise ValueError ('Value must be a positive integer greater than 0')

    total = 0

    for num in range (1, n+1):

    total + = num

    return total

    Explanation:

    The above function was written in Python, the first if statement is for validation purposes and it ensures that the argument passed is a positive integer. If it is not, a ValueError is raised

    We leveraged on Python's range function, which accepts three arguments although we passed in two arguments. The first argument is where the range function will start from and the second is where it will end. If we want the range function to stop at value n, then the argument has to be n+1 (This is because machine starts counting numbers from 0) and the last argument is the step in which the increment is done. If no value is passed to this argument, Python assumes the value to be 1 which is what is done in this case.

    Hence range (1, 5) = (1,2,3,4) and range (2, 10, 2) = 2,4,6,8
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a function called sum_first_integers that takes a single positive integer parameter. The function should also return a positive ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers