Python Intermediate #3 - Random Multiplication Practice using randint

In our previous example, we used a list with a for loop in Python to print out multiplication tables.  This example allows the user to practice multiplication of two random values.

For this post, we will use an if statement along with the randint function from the random module.  Additionally we will be using a while loop to ask the user if they want to keep playing.  The coding of the randint function can be found at this site:

https://docs.python.org/2/library/random.html

Scrolling down to randint shows the following:



This tells us that this function will produce an random integer from a to b.

If we code the following:

x = randint(0,9)

print("The random integer is ",x)

We would expect to get a message giving us a random number between 0 and 9.  Instead, we get this:



This is because we need to import randint from the random method.  We do this as follows:

from random import randint

x = randint(0,9)

print("The random integer is ",x)

Now, we get the following:



We can use this function to have Python give us two random numbers to multiply.  The user can then input the answer and Python will tell them if they are correct.  It is like a multiplication flashcard.

In this example, I use a while loop with an else statement.  Basically, I want the multiplication flashcard program to run while the object "play" is equal to 1.  I initialize "play" to 1 to get the while loop running.  Inside the while loop, I also have an if loop that is used to test whether or not the answer given by the user is correct.  If it is not correct, the else part of the statement is activated to tell the user it is not correct.  After this is run, we ask the user if they want to play again.  If they enter 1, we go back through the while loop.  If they enter 0, we activate the else statement of the while loop to print "Thanks for playing."

The code is as follows:



The results of this code are shown below:



Comments

  1. How can we give 2 chances for same question?

    ReplyDelete
    Replies
    1. Good question. I would use a while - else loop. So, you can have the user input their first answer and then check it in the while - else loop. While their answer is not correct, print out that it is not correct and then get another answer from them. In the else part (activated when they get the correct answer), print out that their answer is correct. Let me know if that makes sense. If not, I can test it and make another post or video.

      Delete
  2. Write a multiplication game program for kids. The program should give the player ten randomly generated multiplication questions to do. After each,the program should tell them whether they got it right or wrong and what the correct answer is... Pls how can I solve this? Thank you

    ReplyDelete

Post a Comment