[Tutor] guess-my-number programme

Wayne Werner waynejwerner at gmail.com
Fri Sep 23 22:28:40 CEST 2011

On Fri, Sep 23, 2011 at 2:25 PM, ADRIAN KELLY <kellyadrian at hotmail.com>wrote:

> <snip>
can anyone explain the *tries* part of this programme to me i know its meant
> to count the number of guesses made by the user by adding 1 but i just cant
> figure out how it does this..........can someone explain??  i.e. tries = 1,
> tries +1 etc.... cant get my head around it...

The concept that's confusing you here is something called order of
evaluation, or evaluation strategy:

The best way to understand these things is to try it out, and the
interactive interpreter is extremely handy.

I presume you understand the concept of assignment, correct? For example:

>>> tries = 1

Now tries contains 1:

>>> tries = 1
>>> tries

The variable 'tries' now contains the value 1 (In Python this is not
technically true, but it's useful to describe it that way).

>>> tries = 4

Now 'tries' contains 4. Of course, just like your standard algebra
variables, you can use your variables in python:

>>> tries * 4
>>> tries + tries
>>> tries / 1

when these expressions are /evaluated/ they produce the mathematical
expression you probably expect. But you can do more than just evaluate
expressions, you can store their results:

>>> lots_of_tries = tries * 100
>>> lots_of_tries

So what about the expression that confuses you?

>>> tries = tries + 1
>>> tries

Well, the first thing that happens when python sees the equals sign is that
the right hand side of the expression is evaluated, so python takes:

    tries = tries + 1

and turns it into

    tries = 4 + 1
    tries = 5

So each time your program sees 'tries = tries + 1' python evaluates the
right side first, then assigns its value to the variable on the left.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110923/77ec4463/attachment-0001.html>

More information about the Tutor mailing list