mercredi 7 février 2018

How to print a number of lines randomly from a text file (using python)

I want to be able to print a number of lines from my file randomly.

This is my file:

1. What date did World War II start? 
A. 20th October 1939
B. 1st September 1939

2. Which was a youth organisation group set up by Hitler during WWII for    German youth?
A. Hitler Youth 
B. Edelweiss Pirates 

3. Who succeeded Elizabeth I on the English throne? 
A. Henry VIII
B. James VI 

4. Did Ireland take part in WWII?
A. No
B. Yes 

5.  Who was the Prime Minister of Britain at the start of WWII?
A. Neville Chamberlain 
B. Winston Churchill 

This is my current code:

#Q1
with open ("hisEasyQ.txt") as hisEasyQFile:
    for line in itertools.islice(hisEasyQFile, 0, 3):
        print line
hisEasyA1 = raw_input("Enter your choice (A or B): ").lower()
print "\n"

#Q2
with open ("hisEasyQ.txt") as hisEasyQFile:
    for line in itertools.islice(hisEasyQFile, 4, 7):
        print line
hisEasyA2 = raw_input("Enter your choice (A or B): ").lower()
print "\n"

#Q3
with open ("hisEasyQ.txt") as hisEasyQFile:
    for line in itertools.islice(hisEasyQFile, 8, 11):
        print line
hisEasyA3 = raw_input("Enter your choice (A or B): ").lower()
print "\n"

#Q4
with open ("hisEasyQ.txt") as hisEasyQFile:
    for line in itertools.islice(hisEasyQFile, 12, 15):
        print line
hisEasyA4 = raw_input("Enter your choice (A or B): ").lower()
print "\n"

#Q5
with open ("hisEasyQ.txt") as hisEasyQFile:
    for line in itertools.islice(hisEasyQFile, 16, 19):
        print line
hisEasyA5 = raw_input("Enter your choice (A or B): ").lower()
print "\n"

Currently, it prints the file in sequential order, i.e:

1. What date did World War II start? 

A. 20th October 1939

B. 1st September 1939

Enter your choice (A or B): 


2. Which was a youth organisation group set up by Hitler during WWII for German  youth?

A. Hitler Youth 

B. Edelweiss Pirates 

Enter your choice (A or B): 


3. Who succeeded Elizabeth I on the English throne? 

A. Henry VIII

B. James VI 


Enter your choice (A or B): 


4. Did Ireland take part in WWII?

A. No

B. Yes 

Enter your choice (A or B): 


5.  Who was the Prime Minister of Britain at the start of WWII?

A. Neville Chamberlain 

B. Winston Churchill 

Enter your choice (A or B): 

However, I would like it to randomly print the lines each time it opens, like this:

1. Who was the Prime Minister of Britain at the start of WWII?

A. Neville Chamberlain 

B. Winston Churchill 

Enter your choice (A or B): 

2. Who succeeded Elizabeth I on the English throne? 

A. Henry VIII

B. James VI 


Enter your choice (A or B):

#...etc...

And then the next time the user runs it the questions are in a different order.

Any idea how would go about doing this using the random function?

(I am using Python 2.7)




Aucun commentaire:

Enregistrer un commentaire