dimanche 3 mars 2019

Math Random Quiz Python Beginner

I'm new to Python and I want to learn on how to generate with random numbers from between 1 to 100. I want to each of 10 questions should be randomly decide between asking for product, sum or difference. First I tried to test with product with If statement from U is an user input but I couldn't figure how to random include with product, sum or difference (if (u == x * y):)... Seperate the question asking into a function, as well as the validating user input.

My Work Code:

import random

def askNum():
  while(1):
    try:
      userInput = int(input("Enter a number: "))
      break
    except ValueError:
      print("Incorrect Input!")

  return userInput

def askQuestion():

  x = random.randint(1, 100)
  y = random.randint(1, 100)

  print("What is " + str(x) + " x " +str(y))

  u = askNum()

  if (u == x * y):
    return 1
  else:
    return 0

amount = 10
correct = 0
for i in range(amount):
  correct += askQuestion()

print("You got %d correct out of %d" % (correct, amount))

OUTPUT I tested with product on Linux terminal:

What is 58 x 75
Enter a number: 4350
What is 78 x 99
Enter a number: 7722
What is 5 x 19
Enter a number: 95
What is 7 x 80
Enter a number: 560
What is 47 x 21
Enter a number: 987
What is 14 x 49
Enter a number: 686
What is 1 x 90
Enter a number: 90
What is 80 x 37
Enter a number: 2960
What is 69 x 65
Enter a number: 4485
What is 50 x 67
Enter a number:
Incorrect Input!
Enter a number: 4
You got 9 correct out of 10




Aucun commentaire:

Enregistrer un commentaire