Basic HTML Version

|  | Table of Contents |  | View Full Version

Page 162 - CodePilot V5.0 C8
P. 162

    RANDOM MODULE
                      Python’s built-in random module is used to generate random numbers and perform random
                      operations.  This includes selecting  random elements from a list or string, shuffling  sequences

                      and more.
                      The following are some commonly used methods from the random module:
                          randint(): It returns a random integer between two numbers, both limits inclusive.

                          choice(): It returns a random element from a list, tuple or string.
                          sample(): It returns a particular length list of elements chosen from the sequence.

                          shuffle(): It is used to randomly reorder the elements of a sequence.
                          uniform(): It returns a random floating-point number between two numbers (upper limit may
                         not be included).
                      This program uses the random module to create a five-question quiz for practicing addition,
                      subtraction and multiplication. The score increases for each correct answer.

                       Program 21 A program to generate a random maths quiz using the random module.

                          Program21.py

                       File  Edit  Format   Run    Options   Window    Help

                       import random
                       opr = '+-*'     #Operators to be used in the quiz
                       score = 0
                       print("Welcome to the Random Math Quiz!")
                       print("Type 'q' anytime to quit.")

                       # Loop to ask 5 questions
                       for i in range(5):
                           a = random.randint(1, 10)
                           b = random.randint(1, 10)
                           op = random.choice(opr)
                           print("Question",i+1, ":", a, op, b, "=?")
                           if op == "+":
                               res = a + b
                           elif op == "-":
                               res = a - b
                           elif op == "*":
                               res = a * b
                           ans = input("Enter your answer (or 'q' to quit):")
                           if ans.lower() == "q":
                               print("You choose to exit from the quiz.")
                               break
                           if res == float(ans):
                               score += 1

                       # Display the final score after all questions
                       print("\nYour final score is:", score)

                      160
                            CodePilot (V5.0)-VIII

| 157 158 159 160 161 162 163 164 165 166 167 |