[Tutor] Help - Using Sort and Join

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Oct 22 22:18:51 CEST 2012

On 22 October 2012 20:57, Daniel Gulko <dangulko at hotmail.com> wrote:
> Hi Python Tutor,

Hi Daniel,

> I have an issue trying to figure out how to print out final answers using
> sort and join functions.

Do you know how to use sort and join to print a list of strings in
alphabetical order?

> Assignment Specification:
> make a function that is a magic eight ball emulator. emulator will be a
> function that returns one of the possible answers. Make another function
> that runs the emulator over and over again until user wants to quit,
> printing answer each time. When user quits, present all answers that the
> user got again, but present them in alphabetical order. Use the join()
> function available for strings for this.
> As my code is written when user presses enter I simply break and print this
> current output:
> Have a nice day
> What I want is when user exits for my code to take all previous answers,
> joining them and sorting them like below:
> ask a question (or press 'enter' to quit):
> You may rely on it. It is decidedly so. Better not tell you now.

The problem is that your not saving the answers so at the point where
your program ends they aren't available for you to print them. You
should use a list to collect the answers as they are generated. Then
you can think about how to use the sort and join functions

> My code works right now but I am missing the final part in how to join and
> sort all answers. Any suggestions or examples is helpful as I
> am very new with Python.
> Current code is attached for viewing.

Your code is not too long to be pasted directly into the email:

import random

def AskMagicEightBall():

    answers = ("As I see it, yes.",
               "It is certain.",
               "It is decidedly so.",
               "Most likely.",
               "Outlook good.",
               "Signs point to yes.",
               "Without a doubt.",
               "Yes – definitely.",
               "You may rely on it.",
               "Reply hazy, try again.",
               "Ask again later.",
               "Better not tell you now.",
               "Do not count on it.",
               "My reply is no.",
               "My sources say no.",
               "Outlook not so good.",
               "Very doubtful.")

    return random.choice(answers)

def RunEmulator():

    while True:
        question = raw_input("ask a question (or press 'enter' to quit): ")
        if question:
            print answers
        elif not question:
            print "Have a nice day"



More information about the Tutor mailing list