Python: random choice executing all function calls listed
<p>I'm stuck on a probably simple issue:
when using choice with functions, it seems like all of them gets executed while only one should.
Example:</p>

<pre><code>from ordereddict import OrderedDict
from random import choice

def PrintStrings():
    Text = choice(["Gutentag!", "Ni hao!", "Hola!"])
    print "Chosen Text is:", Text
    return Text

class Greeting():
    fields = OrderedDict([
         ("Morning",     "Hi"),
         ("Afternoon",   "Good Afternoon!"),
         ("Evening",     "Good Evening!"),
    ])

    def change(self):
        self.fields["Morning"] = "Good morning!"

    def changerandom(self, n = 1): 
        function=[
                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},
                 ]
        result = {}
        for i in range(n):
            result.update(choice(function))
            print "Updated string:",result
            return result

text = Greeting()
text.change()
text.changerandom()
</code></pre>

<p>When running this script, I get all 3</p>

<pre><code>                    {self.fields["Morning"]: PrintStrings()},
                    {self.fields["Afternoon"]: PrintStrings()},
                    {self.fields["Evening"]: PrintStrings()},
</code></pre>

<p>executed, while it shouldn't.
This script returns:</p>

<pre><code>Chosen Text is: Ni hao!
Chosen Text is: Gutentag!
Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}
</code></pre>

<p>Expected result is:</p>

<pre><code>Chosen Text is: Hola!
Updated string: {'Good morning!': 'Hola!'}
</code></pre>

<p>Putting aside some strange data structures choices, you are calling a function in <code>function</code>. Remove the parenthesis' to just pass the function as an <em>object</em>.</p>

<p><code>PrintStrings()</code> -> <code>PrintStrings</code></p>

<p>Here's a possible solution to get the required output:</p>

<pre><code>def changerandom(self, n = 1): 
    result = {}
    for i in range(n):
        key_choice = Greeting.fields[choice(Greeting.fields.keys())]
        result[key_choice] = PrintStrings()
        print "Updated string:", result
        return result
</code></pre>

<p>With this approach, we grab our random key, and call <code>PrintStrings()</code> all in the same iteration.</p>

python random choice