SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:2 | ISBN:978013274719 | Edition: 6

Question

(Repeat additions) Listing 5.4, SubtractionQuizLoop.py, generates five random subtraction questions. Revise the program to generate ten random addition questions for two integers between 1 and 15. Display the correct count and test time.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import time
import random
correctCount = 0  #Count the number of correct answers
count = 0 #Count the number of questions
startTime = time.time()*1000.0
while (count < 5):
    number1 = random.randint(1,16)
    number2 = random.randint(1,16)
    #Prompt the student to answer "what is number1 – number2?"
    print("What is  {}  -  {} ? ".format(number1,number2))
    answer = int(input())
    #Grade the answer and display the result
    if (number1 - number2 == answer):
        print( "You are correct!")
        correctCount=correctCount+1
    else:
        print("Your answer is wrong.\n {} - {}  should be".format(number1,number2), (number1 - number2))
    #Increase the count by incremeting variable called "count"
    count=count+1
print("Correct count is ",correctCount)
endTime = time.time()*1000.0
print("Time spent is  {} seconds".format((endTime - startTime) / 1000))
  

Output:

What is  4  -  14 ? 
-10
You are correct!
What is  4  -  9 ? 
-5
You are correct!
What is  16  -  4 ? 
12
You are correct!
What is  7  -  13 ? 
5
Your answer is wrong.
 7 - 13  should be -6
What is  1  -  6 ? 
4
Your answer is wrong.
 1 - 6  should be -5
Correct count is  3
Time spent is  28.8054658203125 seconds

0 0

Discussions

Post the discussion to improve the above solution.