[Tutor] coin toss program without using the for/range loop
Luke Paireepinart
rabidpoobear at gmail.com
Fri Jan 5 01:41:57 CET 2007
Kent Johnson wrote:
> David wrote:
>
>> How to write the coin toss program without using the for/range loop program.
>>
>> Program flips a coin 100 times and then tells you the number of heads
>> and tails.
>>
>>
>>
>> I can only solve it using the for/range loop
>>
>>
>>
>> Import random
>>
>> Heads=0
>>
>> For 1 in range (100):
>>
>> Heads+=random.randrange(2)
>>
>>
>>
>> print “Hit heads”+” “+str(heads)+” “+”times”+” “ + “hit tails” + “
>> “+str(100-heads)+” “ + “times”
>>
>>
>>
>> I don’t see how you solve this program just using the while loop program
>> and if/else statement.
>>
>
> This sounds a lot like homework so I won't give you the whole answer,
> but you can write a for loop using while and a counter variable.
>
>
In fact, in most languages a for loop and a while loop are very similar:
for(int i =0; i < 100; i++)
{
//do something
}
is the same as
int i = 0
while (i < 100)
{
// do something
i++;
}
The difference in Python comes from the fact that the 'for' loop
iterates over a list of objects,
rather than incrementing a variable.
If you're using a for-range loop in Python you're using it in the
old-style that C and C++ programs use (other languages too)
in which case you could easily use a while loop as well.
But if you're indexing into a specific list,
it becomes much more clear why we use python's 'for',
to index directly into that list without having to deal with an index
variable.
for x in some_list:
// do something with x
rather than
index = 0
while index < len(some_list):
x = some_list[index]
// do something with x
index += 1
HTH,
-Luke
> Kent
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More information about the Tutor
mailing list