Below is the my table.I use MySQL for the database queries.
Structure of the table
I want to print questions randomly by taking the questions from the table. How can I do that using Python?
from random import randint
num = randint(1,5)
Then db query:
SELECT question FROM your_table WHERE ques_id = num;
Alternatively:
SELECT question FROM your_table LIMIT num-1, 1;
num would be a random number between 1 and 5, replace num
in the query and it only returns 1 row. Be aware it is starting from index 0, therefore the first argument should be num-1
other than num
, second argument is always 1 because you only want to get one row per query.
If all the Ids are in order, get the max one and use the random library to get a random number from 1 to the max id in database.
from random import randint
random_id = randint(1,my_max_id)
then use random_id
to get the item from the database.
If you have not setup your python mysql connection, you can refer this How do I connect to a MySQL Database in Python?.
You could do it at the database level (in MySQL) and thus you would gain an extra speed (by doing the calculations in a lower level of software).
In MySQL, you could get all the questions that you are going to show in a random way.
SELECT qus_id, question FROM your_table ORDER BY RAND();
And then, in python show them by sequentially obtaining the records previously out of order in MySQL.
for question in rows:
show_question(question)
Any "Random" operation is costly to process, so the lower the software level at which it is calculated, the more optimal your program will be.