Question

(For Python program)   Write a program that fulfills the functionalities of a mathematical quiz with the...

(For Python program)  

Write a program that fulfills the functionalities of a mathematical quiz with the four basic arithmetic
operations, i.e., addition, subtraction, multiplication and integer division. A sample partial output of the
math quiz program is shown below.

The user can select the type of math operations that he/she would like to proceed with. Once a choice
(i.e., menu option index) is entered, the program generates a question and asks the user for an answer. A
sample partial output is shown below. Note that user inputs are denoted in bold and blue in the examples.

After receiving an answer, the program then checks whether the user’s answer is correct or not, according
to the result of the acual computation. The program continues with asking the user to choose another
math operation for the quiz. A sample partial output is shown below.
************************
** A Simple Math Quiz **
************************
1. Addition
2. Subtraction
3. Multiplication
4. Integer Division
5. Exit
------------------------
Enter your choice:

************************
** A Simple Math Quiz **
************************
1. Addition
2. Subtraction
3. Multiplication
4. Integer Division
5. Exit
------------------------
Enter your choice: 1
Enter your answer
15 + 2 =

************************
** A Simple Math Quiz **
************************
1. Addition
2. Subtraction
3. Multiplication
4. Integer Division
5. Exit
------------------------
Enter your choice: 1
Enter your answer
15 + 2 = 17
Correct.
Enter your choice: 7
Invalid menu option.
Please try again: 3
Enter your answer
20 * 19 = 280
Correct.
Enter your choice: 3
Enter your answer
13 - 17 = -5
Incorrect.
Enter your choice:

Note that if the user enters an invalid menu option index, the program responds with an error message
and prompts the user to enter a correct menu option (until it obtains one), as shown in the above example.
The program will continue running with more questions to answer until the user selects the “Exit” option
on the menu. Once the exit option (i.e., index 5) is entered, the program stops and prints out the result of
the quiz, in terms of the total number of questions answered, the number of questions that are correct and
the score in a percentage form. A sample output is shown below.
************************
** A Simple Math Quiz **
************************
1. Addition
2. Subtraction
3. Multiplication
4. Integer Division
5. Exit
------------------------
Enter your choice: 1
Enter your answer
12 + 13 = 25
Correct.
Enter your choice: 2
Enter your answer
9 - 8 = 1
Correct.
Enter your choice: 3
Enter your answer
7 * 17 = 119
Correct.
Enter your choice: 4
Enter your answer
8 // 12 = 0
Correct.
Enter your choice: 2
Enter your answer
13 - 17 = -4
Correct.
Enter your choice: 3
Enter your answer
2 * 11 = 22
Correct.
Enter your choice: 4
Enter your answer
2 // 18 = 1
Incorrect.
Enter your choice: 1
Enter your answer
8 + 15 = 23
Correct.
Enter your choice: 5
Exit the quiz.
------------------------
You answered 8 questions with 7 correct.
Your score is 87.5%. Thank you.

Your program must give the correct output in the same format as the outputs in the the above examples.
There are two assumptions made for the above simple math quiz program, i.e.,
• The numbers in the questions are randomly generated between 1 and 20 (both inclusive);
• The calculation on division is an integer division, which the result is truncated to the integer value
only, e.g., 25//7=3.
The main() function is given below and it should NOT be changed in any way. Copy this code into your
program.
def main():
display_intro()
display_menu()
display_separator()
option = get_user_input()
total = 0
correct = 0
while option != 5:
total = total + 1
correct = menu_option(option, correct)
option = get_user_input()
print("Exit the quiz.")
display_separator()
display_result(total, correct)
main()
Complete the following eight functions so that the completed program runs as described above:
• def display_intro():
This function prints out the heading part of the menu , i.e., the line of stars, the name of the quiz
program and another line of stars. There are 24 star symbols in one line of stars. Note that the string
repeat operator “*” might be useful to repeat the same symbol a number of times.
• def display_menu():
This function prints out the actual menu options with associated index values.
• def display_separator():
This function prints out the separation line which consists of 24 “-“ symbols.
• def get_user_input():
This function obtains an integer from the user as the selection of the menu index. You can assume that
the user is always going to enter a positive integer value. However, you do need to check whether the
integer value entered by the user is a valid menu option index. If the input is outside the range of 1-5

(inclusive), the function will print an error message and ask for the correct input, and it will continue to
do so until a valid menu index is obtained. Finally, the function returns the user input choice.
• def get_user_solution(problem):
This function instructs the user to enter an answer for the math question which is stored in the
parameter variable ‘problem’. The function returns the input value as the user’s answer.
• def check_solution(user_solution, solution, count):
This function checks whether the user answer (in the parameter variable ‘user_solution’) is the same as
the actual solution of the question (in the parameter variable ‘solution’). The parameter variable
‘count’ stores the total number of questions correctly answered by the user so far in the quiz. Based on
the correctness of the user answer, the function prints out a corresponding message (i.e., either correct
or incorrect). If the user answer is correct, the function also increases the total number of correct
answers by 1. Finally, the function returns the total number of correctly answered questions so far.
• def menu_option(index, count):
This function handles a specific menu option choice, which consists of the following steps.
o Generate two random numbers between 1 and 20 (both inclusive);
o Generate the math question and its actual solution according to the user selected menu
option (value in the parameter variable ‘index’);
o Obtain the user answer by calling the ‘get_user_solution’ function and passing the problem
as a parameter;
o Check the correctness of the user answer by calling the ‘check_solution’ function (where the
parameter variable ‘count’ stores the number of questions correctly answered so far and it
should be passed to the function call);
o Finally, the function returns the total number of correctly answered questions so far which
was obtained from the ‘check_solution’ function.
• def display_result(total, correct):
This function displays the result of the quiz. The parameter variable ‘total’ stores the total number of
questions, and the variable ‘correct’ stores the number of questions answered correctly. Based on
these two values, the function works out the percentage score (in two decimal places) and prints out
the result.

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

PYTHON CODE:

import random

# function to print the header
def display_intro():
    print('*' * 24)
    print('** A Saimple Math Quiz**')
    print('*' * 24)

# function to display the menu
def display_menu():
    print('1.Addition')
    print('2.Subtraction')
    print('3.Multiplication')
    print('4.Integer Division')
    print('5.Exit')

# function to display the separator
def display_separator():
    print('-' * 24)

# function to get the user input of menu choice
def get_user_input():

    choice=int(input('Enter your choice: '))

    # infinite loop to get the correct input choice
    while True:      

        if choice in [1,2,3,4,5]:
            return choice
        else:
            print('Invalid menu option.')
            choice=int(input('Please try again: '))
          
# function to get the user answer for the question
def get_user_solution(problem):
  
    print('Enter your answer')
    user_solution=int(input(problem+" = "))
    return user_solution

# function to check the user solution
def check_solution(user_solution,solution,count):

    # if the user answer is correct, increment the counter
    if user_solution == solution:
        print('Correct.')
        count+=1
    else:
        print('Incorrect.')

    return count

# function to generate question  
def menu_option(index,count):

    # generating 2 random numbers
    random1=random.randint(1,20)
    random2=random.randint(1,20)

    # variable to store the answer and problem
    answer=0
    problem=''

    # depends on the user choice, question is generated
    if index == 1:
        problem = str(random1)+' + '+str(random2)
        answer= random1+ random2
    elif index ==2:
        problem = str(random1)+' - '+str(random2)
        answer = random1 -random2
    elif index == 3:
        problem = str(random1)+' * '+str(random2)
        answer = random1 * random2
    elif index == 4:
        problem = str(random1)+' / '+str(random2)
        answer = random1//random2
    else:
        pass

    # getting the user input of answer for the given problem
    user_solution=get_user_solution(problem)

    # checking the user answer
    count=check_solution(user_solution,answer,count)

    return count

# displaying the final output
def display_result(total,correct):

    print('You answered {0} questions with {1} correct.'.format(total,correct))
    avg=(correct/total)*100
    print('Your score is {0:.2f}%. Thank you.'.format(avg))
  
# main function
def main():
  
    display_intro()
    display_menu()
    display_separator()
    option = get_user_input()
    total = 0
    correct = 0
    while option != 5:
        total = total + 1
        correct = menu_option(option, correct)
        option = get_user_input()
    print("Exit the quiz.")
    display_separator()
    display_result(total, correct)

# calling the main function
main()

SCREENSHOT FOR CODING:

SCREENSHOT FOR OUTPUT:

Add a comment
Know the answer?
Add Answer to:
(For Python program)   Write a program that fulfills the functionalities of a mathematical quiz with the...
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
  • Write a Python Program that displays repeatedly a menu as shown in the sample run below....

    Write a Python Program that displays repeatedly a menu as shown in the sample run below. The user will enter 1, 2, 3, 4 or 5 for choosing addition, substation, multiplication, division or exit respectively. Then the user will be asked to enter the two numbers and the result for the operation selected will be displayed. After an operation is finished and output is displayed the menu is redisplayed, you may choose another operation or enter 5 to exit the...

  • This week we looked at an example math program that would display the answer to a...

    This week we looked at an example math program that would display the answer to a random math problem. Enhance this assignment to prompt the user to enter the solution to the displayed problem. After the user has entered their answer, the program should display a message indicating if the answer is correct or incorrect. If the answer is incorrect, it should display the correct answer. The division section should use Real data types instead of Integer data types. Keep...

  • Python please Create a menu-driven modular program so user can take a 10-question math quiz, Addition...

    Python please Create a menu-driven modular program so user can take a 10-question math quiz, Addition or subtraction, at specified difficulty level. Easy(1-digit), Intermediate(2-digit), and Hard(3-digit). After a quiz, display the quiz type and level, and number of correct questions user answered.

  • IN JAVA: Write a program that displays a menu as shown in the sample run. You...

    IN JAVA: Write a program that displays a menu as shown in the sample run. You can enter 1, 2, 3, or 4 for choosing an addition, subtraction, multiplication, or division test. After a test is finished, the menu is redisplayed. You may choose another test or enter 5 to exit the system. Each test generates two random single-digit numbers to form a question for addition, subtraction, multiplication, or division. For a subtraction such as number1 – number2, number1 is...

  • PLease IN C not in C++ or JAVA, Lab3. Write a computer program in C which...

    PLease IN C not in C++ or JAVA, Lab3. Write a computer program in C which will simulate a calculator. Your calculator needs to support the five basic operations (addition, subtraction, multiplication, division and modulus) plus primality testing (natural number is prime if it has no non-trivial divisors). : Rewrite your lab 3 calculator program using functions. Each mathematical operation in the menu should be represented by a separate function. In addition to all operations your calculator had to support...

  • This is a quick little assignment I have to do, but I missed alot of class...

    This is a quick little assignment I have to do, but I missed alot of class due to the Hurricane and no one here knows what theyre doing. please help! this is Java with intelli-J Overview In this project students will build a four-function one-run calculator on the command line. The program will first prompt the user for two numbers, then display a menu with five operations. It will allow the user to select an option by reading input using...

  • Read description carefully. Needs to catch exceptions and still be able to keep the program going...

    Read description carefully. Needs to catch exceptions and still be able to keep the program going on past the error. Program should allow user to keep going until he or she quits Math tutor) Write a program that displays a menu as shown in the sample run. You can enter 1, 2. 3, or 4 for choosing an addition. subtraction, multiplication, or division test. After a test is finished, the menu is redisplayed. You may choose another test or enter...

  • Write a MIPS math quiz program in MARS. The program should start with a friendly user...

    Write a MIPS math quiz program in MARS. The program should start with a friendly user greeting. From there, it should generate a random arithmetic problem. Your program will need to generate three random things: the first and second operand and the operator to use. Your program should generate random positive integers no greater than 20 for the operands. The possible operators are +, -, * and / (division). The user should be prompted for an answer to the problem....

  • In Python, write a program that asks the user for a positive integer number. If the...

    In Python, write a program that asks the user for a positive integer number. If the user enters anything else, the program would ask the user to re-enter a number or enter -1 to quit. If it is a positive number, the program then prints out a multiplication table that goes up to that number. For example, if the user enters 10, the output would look something like this. https://www.vectorstock.com/royalty-free-vector/multiplication-table-on-white-background-vector-2721686

  • Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================")...

    Need help writing this code in python. This what I have so far. def display_menu(): print("======================================================================") print(" Baseball Team Manager") print("MENU OPTIONS") print("1 - Calculate batting average") print("2 - Exit program") print("=====================================================================")    def convert_bat(): option = int(input("Menu option: ")) while option!=2: if option ==1: print("Calculate batting average...") num_at_bats = int(input("Enter official number of at bats: ")) num_hits = int(input("Enter number of hits: ")) average = num_hits/num_at_bats print("batting average: ", average) elif option !=1 and option !=2: print("Not a valid...

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
ADVERTISEMENT