AP CSP - Write a program that takes 10 random numbers from 1 to 12 inclusively and averages them together.

Here is the code I wrote: (Python)

print(random() * 12 + 1)

1. What is the code supposed to be?

2. What is wrong with my code?

Respuesta :

Answer:

follows are the correct python code to this question:

import random as r#import random package as r

import statistics as s #import statistics package as s

l= r.sample(range(0,12),10)#defining l variable that use random function to store 10 random numbers

avg= s.mean(l)#defining avg variable for calculate average of l

print('List of random number are: ', l)#print list of random numbers

print("The random number Average is: ", avg)#print average value

Output:

List of random number are:  [4, 10, 6, 0, 3, 5, 1, 7, 11, 2]

The random number Average is:   4.9

Explanation:

In question 1:

In the given code, two packages are imported, which are "random and statistics", in which "random" is used to generate a random number, and "statistics" is used to calculate the average value.

In the code, the "l" variable is used, which uses a random function and store 10 random numbers, and an "avg" variable is defined that calculates the average value. In the last step, the print method is used that print number and its average value.

In question 2:

The given code is wrong because it only calls the "random" method, which is not defined.

The program illustrates the use of random module.

Your program is wrong in the following ways

  • You didn't import the random module
  • Wrong usage of random
  • The required mean is neither calculated , nor printed

The correction program in Python where comments are used for explanation is as follows:

#This imports the random module

import random

#This initializes an empty list

myList = []

#This initializes total (i.e. sum) to 0

total = 0

#This iterates through the list

for i in range(0,10):

   #This generates a random number

   num = random.randint(0,12)

   #The number is then appended to the list

   myList.append(num)

   #This calculates the sum of all random numbers

   total += num

#This calculates and prints the average

print("The random number Average is: ", total/12.0)

At the end of the program, the mean of all random numbers is. calculated and printed

See attachment for complete program and sample run

Read more about Python programs at:

https://brainly.com/question/22841107

Ver imagen MrRoyal