Python shuffle help?

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

Python shuffle help?

Postby aa1511 » Wed Mar 26, 2014 12:33 pm

Hey guys this may seem a bit stupid but I've just started to code and am learning the shuffle button. I'm making a sort of quiz and randomising what order the answers come in. All that works but when I print it, they all come in one line :(.

Code: Select all
import random
x = [randAns2,realAns,randAns3]
random.shuffle(x)
print (x) 

When I enter this code, the answers are random but they all end up in one line, anyway to fix this?
Thanks for any suggestions recieved! :D
Last edited by Yoriz on Wed Mar 26, 2014 1:02 pm, edited 1 time in total.
Reason: First post lock, Added code tags
aa1511
 
Posts: 4
Joined: Wed Mar 26, 2014 12:30 pm

Re: Python shuffle help?

Postby Yoriz » Wed Mar 26, 2014 1:06 pm

Hi welcome to the forum, if you have not already, please read the new users read this link in my signature.

The answers are all on one line because x is a list, if you want to print each answer from the list on a seperate line you can loop over the list printing each answer.
Code: Select all
import random
answers = [randAns2, realAns, randAns3]
random.shuffle(answers)
for answer in answers:
    print(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: 724
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Python shuffle help?

Postby aa1511 » Wed Mar 26, 2014 1:13 pm

Hi, thank you very much! I understand why it wouldn't work now haha. May I ask why 'for answer in answers:' changed the list into seperate lines?
Is it because the answer in answers is just selecting every individual answer at a time then printing it? Sorry I'm extremely slow at learning all of this!
aa1511
 
Posts: 4
Joined: Wed Mar 26, 2014 12:30 pm

Re: Python shuffle help?

Postby Yoriz » Wed Mar 26, 2014 1:23 pm

Yes thats it, that peice of code makes it loop over the list of items in answers and makes answer equal each item as it loops through them. The following indented code is called at each loop and the value of answer at that point in the loop is printed.
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: 724
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: Python shuffle help?

Postby Marbelous » Thu Apr 03, 2014 3:41 pm

Marbelous
 
Posts: 97
Joined: Fri May 31, 2013 8:12 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 4 guests