newbie: Syntax error

John Machin sjmachin at lexicon.net
Fri Feb 4 15:25:46 EST 2005


Chad Everett wrote:
> Hi Everyone,
>
> I am new to Python and programming in general.  I bought the book
"Python
> Programming for the Absolute Beginner" by michael Dawson.
>
> I have been working through it but am having trouble.
> I am trying to make a coin flip program and keep geting a Synax Error
> "invalid syntax".
>
> If anyone has a moment could you please look at it and tell me what I
am
> doing wrong.
>
> thanks for your time and patience.
>
> Chad
>
> # Coin Flip Program
> # This program flips a coin 100 times and tells the number of heads
and
> tails.

Oh, no, it doesn't! Once you fix the few things that stop it from
running at all, it will flip the coin ONCE and tell you the one
then-fixed answer *99* times.

> # Chad Everett 2/3/2005
>
>
> print "\t\t********Coin Flip Game*********\n"
> import random
>
> # heads = 1
> # tails = 2
>
> tries = random.randrange(2) + 1

Better move the above line _after_ the "while" statement.

> count = 1

Try 0; think about it this way: you are counting the number of times
something has happened, and you want to stop after 100 somethings have
happened. At this stage you ain't hatched no chickens :)

>
You also need to initialise the 'heads' and 'tails' counters.

> while count != 100:

Defensive programming hint #1: while count <= 100, if starting at 1; <
100 if starting from 0

Tip: Python takes the drudgery out of programming. Less typing, less
scope for error. To do something 100 times:

!for count in range(100):
!    do_something()

>     if tries == 1:
>         heads = 1

I think you meant:
!heads += 1

>         count += 1
Do this in only one place; it doesn't/shouldn't depend on the coin toss
result.

>
>     else tries == 2:  # I AM GETTING THE SYNTAX ERROR HERE
>         tails = 1

and
!tails += 1

>         count += 1
>

Others have answered your syntax error question; I'll just round off
with Defensive Programming hint #2:

Get into this habit early:

!if tries == 1:
!    blah_blah()
!elif tries == 2:
!    yadda_yadda()
!else:
!    raise Exception, "Can't happen :-) tries has unexpected value
(%r)" % tries

> print "heads: " + heads

Ugh; did you get that out of the book?

Try:
!print "heads:", heads

> print "tails: " + tails
> 
> raw_input("Press enter to quit")

HTH,
John




More information about the Python-list mailing list