Generating random

This is the place for queries that don't fit in any of the other categories.

Generating random

Postby Halfbiscuit » Fri Dec 06, 2013 6:39 pm

Hello, I'm trying to figure out how to be able to print something along the lines of this but randomly
Let's say i have these that i want to print, displayed below.

A = int(input("What's 4+5?"))
B = int(input("What's 60*10?"))
C = int(input("What's 50/10?"))

How would i be able randomize which one appears? For example, when it's run it might print A First, or C first.
Thanks in advance
Last edited by Yoriz on Fri Dec 06, 2013 6:45 pm, edited 1 time in total.
Reason: First post lock
Halfbiscuit
 
Posts: 1
Joined: Fri Dec 06, 2013 6:36 pm

Re: Generating random

Postby Yoriz » Fri Dec 06, 2013 7:47 pm

You could store a question along with its answer in a tuple, and store each (question, answer) tuple in a list.
Then you can use random.shuffle to get them in a random order.
Then just loop through each question.

Code: Select all
import random

QUESTION = "What's {}?"
CORRECT = "Well done you answered correctly"
WRONG = "Incorrect, the answer is {}"
questions = [("4+5", 9),
             ("60*10", 600),
             ("50/10", 5)]

random.shuffle(questions)

for question, answer in questions:
    your_answer = int(input(QUESTION.format(question)))
    if your_answer == answer:
        print(CORRECT)
    else:
        print(WRONG.format(answer))
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 721
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 5 guests