fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • sum

    To compute a sum we can use the + operator and add values together. Yet, it would be excessively difficult to do that for large lists (imagine if there are 100 values).
    Python has a built-in function sum which given a list computes the sum of its elements.
    l = [1, 2, -2, 5, 10, -1]
    print(l[0] + l[1] + l[2] + l[3] + l[4] + l[5])   # 15
    print(sum(l))                                    # 15

    Challenge

    Having 8 floating-point numbers in the input, your task is to print the sum of 8, then the sum of the first 7 elements, then the sum of the first 6, the sum of 5, 4, ..., up to one element.
    Input
    Output
    1 2 3 4 5 6 7 8
    36 28 21 15 10 6 3 1
    Tip 1
    You can use del to remove the last element after each sum calculation
    Tip 2
    You can use slices + sum
     
    To check your solution you need to sign in
    Sign in to continue