Question

Python 3.7 to be used. Just a simple design a program that depends on its own. You should also not need to import anything. No code outside of a function!

Median List Traversal and Exception Handling Create a menu-driven program that will accept a collection of non-negative integ

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Below is the complete program as per the requirements. It is well explained inside the code using comments.

# function will display the menu
def menu():
    print('\n1. Add a number to the list/array')
    print('2. Display the mean')
    print('3. Display the median')
    print('4. Print the list/array to the screen')
    print('5. Print the list/array in reverse order')
    print('6. Quit')

# function adds a number to list
def add(lst):
    # keep asking until user enters a valid number
    while(True):
        try:
            # ask and read for a number
            num = int(input('Enter the number: '))
            # add the number to list
            lst.append(num)
            # return
            return
        except ValueError:
            # print error message to user and ask to enter again
            print('Invalid Number. Try Again.')
            num = int(input('Enter the number: '))


# function displays the mean
def display(lst):
    # initialize total
    total = 0
    # iterate through each number and add to total
    for n in lst:
        total += n

    # calcualte mean
    mean = total/len(lst)

    # print the mean
    print('Mean:',mean)

# function displays the median
def displayMedian(lst):
    median = 0
    # get sorted list
    lst.sort()

    # size of list
    size = len(lst)

    # median index
    mid = int(size/2)

    # if there are even numbers
    if size % 2 == 0:
        # calculate median by taking average of 2 middle elements
        median = (lst[mid] + lst[mid-1])/2
    else:
        median = lst[mid]

    # print the median
    print('Median:',median)
      
# function prints list to the screen
def printList(lst):
    print(lst)

# function prints list in reverse order
def printReverse(lst):
    # get reverse sorted list
    reverse = sorted(lst, reverse=True)

    # print reverse sorted list
    print(reverse)

# main function
def main():
    # initialize the choice
    choice = 0

    # declare a list
    lst = []

    # read menu choice
    # keep asking until user enters a valid choice
    while(True):
        try:
            # display the menu
            menu()
            # ask and read for a number
            choice = int(input('Enter your choice [1-6]: '))

            if choice == 1:
                add(lst)
            elif choice == 2:
                display(lst)
            elif choice == 3:
                displayMedian(lst)
            elif choice == 4:
                printList(lst)
            elif choice == 5:
                printReverse(lst)
            elif choice == 6:
                break;
            else:
                print('Invalid Choice. Try Again.')
          
       
except ValueError:
            # print error message to the user and ask to enter again
            print('Invalid Choice. Try Again.')
          
# call the main function
main()

Below is the screenshot of code, in case if indentation is an issue:

function will display the menu def menu (): print \nl. Add a number to the list/array) print 2. Display the mean) print(3.

function displays the median def displayMedian (lst) median 0 get sorted list 1st.sort () # size of list len (1st) size= #med

#main function def main () initialize the choice choice 0 # declare a list lst # read menu choice # keep asking until user en

Below is the sample output:

1. Add a number to the list/array 2. Display the mean 3. Display the median 4. Print the list/array to the screen 5. Print th

1. Add a number to the list/array 2. Display the mean 3. Display the median 4. Print the list/array to the screen 5. Print th

This completes the requirement. Let me know if you have any queries.

Thanks!

Add a comment
Know the answer?
Add Answer to:
Python 3.7 to be used. Just a simple design a program that depends on its own. You should also not need to import anythi...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • Write a c++ complete program to meet the specifications. The program should prompt the user for...

    Write a c++ complete program to meet the specifications. The program should prompt the user for a positive integer. The program should print a message whether the integer is even or odd. The looping should end when the user enters a negative number. The negative number will not be tested for even or odd. The program will print out a message of how many numbers were entered (not counting the negative number) and how many even and odd numbers were...

  • (+30) Provide a python program which will Populate an array(list) of size 25 with integers in...

    (+30) Provide a python program which will Populate an array(list) of size 25 with integers in the range -100 (negative 100)   to +100 inclusive Display the array and its length (use the len function) Display the average of all the integers in the array Display the number of even integers (how many) Display the number of odd integers (how many) Display the number of integers > 0   (how many) Display the number of integers < 0   (how many) Display the...

  • MATLAB homework assignment (HW6), but this time using a "vectorized" approach. Write a script that prompts...

    MATLAB homework assignment (HW6), but this time using a "vectorized" approach. Write a script that prompts the user for N integers (set N-6), one at a time, using a while loop. Error-check to ensure that each number entered is an integer, displaying an error message if it is not. If it is an integer, store it in an array variable nums. Continue prompting until N integers have been successfully entered. (You may copy and paste your code from the previous...

  • python language Problem Description: In this program we are going to explore a list or an...

    python language Problem Description: In this program we are going to explore a list or an array of integers using Python. Your program should read a set of integers from the user and store them in a list. Read numbers from the user until the user enters 0 to quit. Then store them in a list. Your program should them compute the sum of all the numbers in the list and output to the user. You will use lists and...

  • extra credit 1 Write a program that will display the following menu and prompt the user...

    extra credit 1 Write a program that will display the following menu and prompt the user for a selection: A) Add two numbers B) Subtract two numbers C) Multiply two numbers D) Divide two numbers X) Exit program The program should: display a hello message before presenting the menu accept both lower-case and upper-case selections for each of the menu choices display an error message if an invalid selection was entered (e.g. user enters E) prompt user for two numbers...

  • A Simple Calculator Summary: Write a console program (character based) to do simple calculations (addition, subtraction,...

    A Simple Calculator Summary: Write a console program (character based) to do simple calculations (addition, subtraction, multiplication and division) of two numbers, using your understanding of Java. Description: You need to write a program that will display a menu when it is run. The menu gives five choices of operation: addition, subtraction, multiplication, division, and a last choice to exit the program. It then prompts the user to make a choice of the calculation they want to do. Once the...

  • Creating a Calculator Program

    Design a calculator program that will add, subtract, multiply, or divide two numbers input by a user.Your program should contain the following:-The main menu of your program is to continue to prompt the user for an arithmetic choice until the user enters a sentinel value to quit the calculatorprogram.-When the user chooses an arithmetic operation (i.e. addition) the operation is to continue to be performed (i.e. prompting the user for each number, displayingthe result, prompting the user to add two...

  • Write a program in C++. You need everything everythihng given You will create a function that...

    Write a program in C++. You need everything everythihng given You will create a function that validates input. It should accept only non-negative integers. If the input is incorrect the function should throw an exception. The exception will not be caught in the function. You will create a function that reads in 2 integer values. One is a number that will be raised to the power of the second. So if 5 and 6 are entered the result would be...

  • C++ programming For this assignment, write a program that will act as a geometry calculator. The...

    C++ programming For this assignment, write a program that will act as a geometry calculator. The program will be menu-driven and should continue to execute as long as the user wants to continue. Basic Program Logic The program should start by displaying a menu similar to the following: Geometry Calculator 1. Calculate the area of a circle 2. Calculate the area of a triangle 3. Quit Enter your choice(1-3): and get the user's choice as an integer. After the choice...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT