[Tutor] Challenge

Alan Gauld alan.gauld at btinternet.com
Tue Sep 22 17:00:36 CEST 2009


Ali Sina wrote:
> I wrote this code but I know its wrong. Although it works properly:

Thereis adfference between "works properly" (ie does what it should) and 
"runs without errors" :-)

You need to read up a bit more on boolean expressions

> flips=0
> h='heads'
> t='tails'
> while True:
>     flips+=1
>     if flips>100:
>         break

So far so good, this will loop 100 times.
You could have done the same with a for loop:

for flips in range(100):

>     if True:

if true is meaningless, it is always true so
the next line will always be executed so you can
just miss it out.


>         print(flips,'=',h or t)

h or t is a boolean expression which expands out to

'heads' or 'tails'

Since Python considers a non null string to be True
this is equivalent to True or True which is always
True.

In addition Python knows that for an 'or' test if the first value is 
true then the whole expression is true(this iscalle short circuit 
evaluation) and so it only evaluates h as 'heads' to realize the whole 
is true and it returns the first value h (or 'heads')

> But it prints every number with the string 'heads'. I'm really blank at 
> this. It may have something to do with the 'random' module.

The reason it prints heads is that you have basically written the 
following code:

for flips in range(100):
     print 'heads'

What you are not doing is replicating the flip of the coin
(thats where random comes in) and you are not testing
the result of that flip to determine whether to print
heads/tails.

You will find more examples of boolean expressions in
the Functional Programming topic of my tutor under
the heading "Other Constructs" about  60% of the way
down the page.

HTH,

Alan G.
http://www.alan-g.me.uk



More information about the Tutor mailing list