Try and except statement in coin flip

Hey guys, I am trying to create a try and except statement for the coin flip game of chance however everytime I try to run the program it is coming up with a syntax error as follows:

File "script.py", line 12
    Try:
       ^
SyntaxError: invalid syntax

Here is the function I am trying to implement it into:

def coin_flip(guess, bet):
  global money
  coin_flip = random.choice(['Heads', 'Tails']) 

#randomly generates heads or tails choice.
  
if coin_flip == 'Heads':

    for entry in guess:
      Try:
      bet = 'Heads!'
      break
    except:
      print("Whoops! you haved typed the choice in incorrectly, try either heads or tails")

    money = money + bet
    return "Congratulations, you guessed correctly! You have won £" + str(bet) +"!\n" + "You now have £" + str(money) + " in your account."

  else:
    money = money - bet
    return "Unfortunately you have lost £" + str(bet) + " better luck next time\n" + "You now have £" + str(money) + " in your account."

If anybody can help on this it would be really appreciated.

Thankyou.

Hi,

The syntax for try/except statements is the following:

try:
   #some code
except: #you can actually specify the error here
   #some other code

In the code you provide, you have to check for case-sensitivity and indentation.

Check documentation for more examples and context here: https://docs.python.org/3/tutorial/errors.html

1 Like

Thankyou for your response.

My syntax is now correct, however everytime I now run the program it is not returning the except statement.

try:
      guess == 'Heads!' or 'Tails!'

  except NameError:
      return "Whoops! you have entered the choice incorrectly, try either Heads or Tails"

Is there a way around this?

Thankyou.

You might want to print the string instead of returning (usually better way for error messages).

When returning a string, you’d need to do it inside a function. If you were to do it that way, it would behave something like this:

Example:

def hello():
  return "Hello"

hello()
#nothing happens
print(hello())
#Output: Hello

The other thing is you when you specify except NameError, it really has to be a NameError for it to trigger. It might be ok in this case, but just for future reference…

2 Likes

try except isn’t the same as if. While NameError is the only error that can get thrown in your try except, it will only get thrown if the variable guess doesn’t exist, which isn’t what you’re intending from how I’m reading the code.

Also I don’t think your guess == 'Heads!' or 'Tails!' is doing what you think either. It will either evaluate to True or Tails!.

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.