Cumulative Totals outside of a Function: Q from Python Challenge Project - Games of Chance

Hello,

I’m brand new to learning to code, and I’m up to the first Challenge Project in the Python course: Games of Chance: Coin Toss. Below is the code I wrote to call a coin toss and return the money won or lost. It works as assigned, but there is one thing I wanted to do that I’m not finding an answer to:

  1. Can the money won/lost be added to a new total that carries over to the next coin toss? I understand that every call reverts to the original money amount. What would I need to add to make this a game where you can keep winning/losing?

Thanks for any advice!

import random
side = random.randint(1,2)
money = 100

#Write your game of chance functions here
def coin_flip(bet, wage):
  side = random.randint(1,2)
  if bet == "Heads" and side == 1:
    new_total = money + wage
    print(int(wage))
    print("Heads -- You won! Your total is now " + str(money + wage) + ".")
    return new_total
  if bet == "Tails" and side == 2:
    new_total = money + wage
    print(int(wage))
    print("Tails -- You won! Your total is now " + str(money + wage) + ".")
    return new_total
  else:
    new_total = money - wage
    print(int(-wage))
    print("You lost! Your total is now " + str(money - wage) + ".")
    return new_total

    

#Call your game of chance functions here
coin_flip("Heads", 20)
coin_flip("Tails", 20)
coin_flip("Tails", 40)

Which returns:

20
Heads -- You won! Your total is now 120.
-20
You lost! Your total is now 80.
40
Tails -- You won! Your total is now 140.

Games of Chance Project

You’ll need to write another function, one that will run (execute) this and the other three functions you will code for this project. This run_game() function can keep track of your winnings, and let you replay the game(s) of your choice as many times as you like.

The usual technique is to keep the function “alive” with a while loop that prints “play again? (y/n)” or something like that after every game. The scores can then be maintained in a list or (better) a dictionary.

2 Likes

Thank you, @patrickd314. I see that loops and lists are in my next Python lesson, so now I’m looking forward to learning those!

1 Like