[Tutor] Advice needed on Python Programming Third Ed. Challenge on P85 No.2

Alan Gauld alan.gauld at yahoo.co.uk
Sun Apr 19 09:15:57 EDT 2020


On 19/04/2020 11:19, Helen Warren wrote:

> My name is Helen Warren and I am new to programming.

Hi Helen. Just for future reference, the list server doesn't like
attachments and usually strips them off if they are non text
(although this time its OK sometimes .py files are seen as non text
because they could potentially be executed - dangerous.)

As a result its better to simply paste your code into the body of the
mail. That does mean you need to set the format to plain text, since
html will strip out spaces and other formatting.

I've pasted your code at the end for reference.

> import random
> print ("\tThe Heads of Tails game")
>
>count = 100
>tries = 1
>flip =random.randint(1, 2)

Note, you only set flip once. It will never change
again throughout the while loop so you will always
follow the same route through the loop..
You probably want to put it inside the while loop,
just after the while statement.

>heads = 0
>tails = 0
>
>while count > 0:
>    if flip == 1:
>        heads += 1
>        count -= tries
>    else:
>        flip == 2

You are comparing flip to 2 but throwing away the result.
You maybe meant to use

elif flip == 2:

But you don't need to compare flip here because you
know it can only ever be 1 or 2, and the if test proved
it was not 1, so you can just assume that if you are
inside the else clause it must be 2.

>        tails += 2

Why do you increase tails by 2? Surely you only want
to increase by 1?

>        count -= tries

Notice you do this whether flip is 1 or 2. You could
save some typing by putting this before the if/else

If you make those changes it should work.
Although for testing purposes I suggest you set the
number of loops to a lower number than 100! I'd
suggest somewhere between 5-10.

Original code:
# Heads and Tails

# Tests while loop 100 time.

import random

print ("\tThe Heads of Tails game")

count = 100
tries = 1
flip =random.randint(1, 2)
heads = 0
tails = 0

while count > 0:
    if flip == 1:
        heads += 1
        count -= tries
    else:
        flip == 2
        tails += 2
        count -= tries

print ("Your have had:, ", count,
           "you have", tries, "left.\n")

print ("You have flipped", heads, "heads and", tails, "tails." )


input ("\n\nPress the Enter key to exit")



HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list