[Tutor] Risk Dice Program

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Jan 28 01:09:31 CET 2015


On 27/01/2015 23:09, Alan Gauld wrote:
> On 27/01/15 19:12, Dillon Cortez wrote:
>> problem is that if any of the offensive dice is bigger
>  > than only one of the defensive dice,
>> the program shows the offense as the winner,
>
>> def winner():
>>      if o_die1 > d_die1 or d_die2:
>>          print "The offense has won"
>
> The problem is that the computer reads that differently to you.
>
> It sees it as
>
>       if (o_die1 > d_die1) or d_die2:
>
> Now, due to how Python evaluates logical 'or' expressions,
> it knows that if the first part is True it doesn't need to evaluate
> the second part so, if d_die1 is less that o_die1 then it returns True
> and all is well.
>
> But if d_die1 is greater that o_die1 it then returns the value
> of the second expression in the 'or', namely d_die2. Which is not
> what you want in this case.
>
> To get round that you need to explicitly compare o_die1
> to both values:
>
>       if (o_die1 > d_die1) or (o_die1 > d_die2):
>
> You don't strictly need the parens but I prefer to keep them there
> to remind me of what's going on.
>

I consider the chained comparisons shown here 
https://docs.python.org/3/reference/expressions.html#not-in to be far 
more Pythonic.  It also avoids the superfluous brackets which always 
drive me around the bend.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list