Need help with 'unexpected expression syntax error'; Games of Chance

Hi everyone,
I’m having some serious trouble trying to work out why a syntax error continues to pop up for me, when I’m writing my Games of Chance script. If anyone could help, it would be greatly appreciated!

The code and error picture is attached below:

File “script.py”, line 19
elif (flip == 2) and (guess == tails):
^
SyntaxError: invalid syntax

import random

money = 100

#Write your game of chance functions here

def coin_flip(coinbet, h_or_t):
  flip = 0
  if (h_or_t == "H"):
    guess = heads
  elif (h_or_t == "T"):
    guess = tails
  else:
    print("Please write in correct format")
  flip = random.randit(1, 2)
  if (flip == 1) and (guess == heads):
    print("You flipped heads! Nice job!")
    print("You won " + str(coinbet*2) + "!" 
  elif (flip == 2) and (guess == tails):
    print("You flipped tails! Nice job!")
    print("You won " + str(coinbet*2) + "!")
 
  
  


You can temporarily remove things until it goes away to find what it is

Thank you! I tried to isolate the issue, and ended up fixing the issue with the ‘elif’ but then this cropped up:

  if (flip == 2) and (guess == tails):
    print("You flipped tails! Nice job!")
    print("You won " + str(coinbet*2) + "!")
  elif (flip == 1) and (guess == heads):
    print("You flipped heads! Nice job!")
    print("You won " + str(coinbet*2) + "!" 
  else:
    print "test"


File "script.py", line 23
    else:
       ^
SyntaxError: invalid syntax

I’m pretty sure it has something to do with how I’ve structured my “if,elif and else” statement. Not sure how to fix it though.

pretty sure?
so if you remove them, you wouldn’t have a syntax error?

you can remove things until the error goes away, and when it does, it was the last thing you removed.

you can also write your code incrementally, running it each time you’ve added a small part to see if it’s still okay. if a syntax error appears then it was the last thing you added

you will most definitely need to identify the problem before you can start thinking about how to fix it

Yes, if I remove the second set of if and elif, the error is gone.
I’ve isolated to work out that the problem is that whenever I try to close my if statement, it comes up with an ‘unexpected expression syntax error.’
The error specifically pops up, whenever I add an ‘else’ statement at the end of my code.

Thanks for your help!

Well, does this have a syntax error in it?

if True:
    pass
elif True:
    pass
else:
    pass

I removed everything except the if-statement itself.

Maybe you removed a really big chunk of code all at once, but if there were many things in what you removed then you can’t say which one of them it was.

Since this contains only the if-statement, and it is valid syntax, you can then conclude that the problem is with something else.

1 Like

Okay, thanks for your help!