0

I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.

import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
    print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
    sys.exit("goodbye") 
if answer == "y":
    print ("your balance is",money)
    guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
    print("heads")
if flip == 1:
    print("tails")
if guess == flip:
    print("you win")
    money = money + 250000
else:
    print("you lose")
    money = money - 250000
print ("your balance is",money)
if money == 0:
    sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
   game()
if replay == "n":
    sys.exit("goodbye")

This is the output:

do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
  • 1
    The rest of the code needs to be indented properly to make it part of the function. – porrrwal Nov 21 '21 at 23:27
  • you need to add a looping construct like `for` or `while` – Chris Doyle Nov 21 '21 at 23:29
  • Were you getting this error: "UnboundLocalError: local variable 'money' referenced before assignment"? – Ansjovis86 Nov 22 '21 at 01:15
  • Does this answer your question? [How to make program go back to the top of the code instead of closing](https://stackoverflow.com/questions/18791882/how-to-make-program-go-back-to-the-top-of-the-code-instead-of-closing) – Gino Mempin Nov 22 '21 at 03:14

2 Answers2

0

you need to call game() at the end of the code once more.

import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
 print ("welcome to the coin flip")
 answer=input("do you want to play the coin flip? y/n")
 answer = str(answer)
 if answer == "n":
  sys.exit("goodbye") 
 if answer == "y":
   print ("your balance is",money)
 guess = input("heads or tails? 0 for heads 1 for tails")
 guess = int(guess)
 if flip == 0:
    print("heads")
 if flip == 1:
    print("tails")
 if guess == flip:
    print("you win")
    fact=1
 else:
    print("you lose")
    fact=-1
 print ("your balance is",money+fact*step)
 if money == 0:
  sys.exit("you are bankrupt")
 replay = input("play again? y/n")
 if replay == "y":
  print("welcome again")
  game()
 if replay == "n":
  sys.exit("goodbye")
game()
0

Add this up in your game function:

global money, flip
Ansjovis86
  • 1,506
  • 5
  • 17
  • 48