8.6 Code Practice: Question 2

Instructions

Copy and paste your code from the previous code practice. If you did not successfully complete it yet, please do that first before completing this code practice.


After your program has prompted the user for how many values should be in the array, generated those values, and printed the whole list, create and call a new function named sumArray. In this method, accept the array as the parameter. Inside, you should sum together all values and then return that value back to the original method call. Finally, print that sum of values.


Sample Run

How many values to add to the array:

8

[17, 99, 54, 88, 55, 47, 11, 97]

Total 468

Respuesta :

Answer:

import random

def buildArray(a, n):

   for i in range (n):

      a.append(random.randint(10,99))

     

arr = []

def sumArray(a):

   tot = 0

   for i in range(len(a)):

       tot = tot + a [i]

   return tot

       

   

arr = []

numbers = int(input("How many values to add to the array:\n"))

buildArray(arr, numbers)

print(arr)

print("Total " + str(sumArray(arr)) )

Explanation:

The program is an illustration of lists

Lists

Lists are variables that are used to hold multiple values in one variable name

Python Program

The program in Python, where comments are used to explain each line is as follows:

#This gets the number of inputs to the array

n = int(input("How many values to add to the array: "))

#This initializes the sum to 0

sumArray = 0

#This initializes a list

myList = []

#This iterates through n

for i in range(n):

   #This gets input for the list elements

   num = int(input())

   #This appends the input to the list

   myList.Append(num)

   #This calculates the sum

   sumArray+=num

#This prints the list elements

print(myList)

#This prints the sum of the list elements

print("Total",sumArray)

Read more about lists at:

https://brainly.com/question/24941798