[Tutor] New programmer, need some help getting started on my first project
Alan Gauld
alan.gauld at freenet.co.uk
Fri May 19 12:54:19 CEST 2006
Chris,
> I do like the way you simplified using the random function,
> I need to start thinking like that.
It is quite clever but quite a subtle twist for a beginner to think
of.
However even in your version there is a pattern you should look
out for:
>> coin = random.randrange(2)
>> if coin == 0:
>> heads += 1
>> else:
>> tails += 1
If you assign a value to a variable (ie coin) and then only ever
use that variable in the test of a simple if/else construct then
you can always eliminate the assignment:
if random.randrange(2):
tails += 1:
else: heads += 1
Bob's trick works because you always get 0 or 1 back, but this
shortcut works for any two way check, even ranges:
if somefunc() > keyvalue:
# do greater than action
else:
# do other action
The caveat is where you need to use the test value inside
the if/else and then you do need to explicitly make the
assignment.
>> print "The coin was flipped 100 times and it was heads "
>> +str(heads)+
>> " times and tails " + str(tails) + " times!"
Also you don't need to use str() in. Python to proint things because
print implicitly calls the string conversion for you.
>>> print 5,'+',4,'=',5+4
5 + 4 = 9
Note that it also inserts spaces between the valiues. For more
control
use the string formatting technique that Bob demonstrated.
Looking for these common shortcuts or idioms is a big part of gaining
experience with any language.
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list