I am new to programming and I have recently started learning Python (through a udemy course). The latest project was building a Blackjack card game and I have been trying to add other features, such as a win/loss tracker. For that purpose, I am trying to increment a variable (b_count) as win counter. However I can't figure out how to pass it from module1 to module2 (the former being called from the later).
Here is a boiled down code: I want b_count printed from module2 to increment by 1 each time the player wins (represented below by a == 2). It should start at 0 and increment when the player decides to replay the game (when module2 is called by itself).
import random
b_count = 0
game_count = 1
def module1(b_count):
a = random.randint(1,3)
print(f"a = {a}")
if a == 2:
b_count = 1
def module2(b_count, game_count):
print(f"b_count: {b_count}")
print(f"game_count: {game_count}")
module1(b_count)
replay = input("replay? y/n: ")
if replay == "y":
game_count = 1
module2(b_count, game_count)
module2(b_count, game_count)
I have tried adding the parameters to the functions, but b_count as printed in module2 never increments, even when a == 2.The game counter works though. I have read about passing variables, but I am a bit stuck. Is there a way to specifically pass to module2 the value of b_count from module1?
return b_count
in module1 did not help. I also tried something like:
print(f"\nb_count: {module1(b_count)}")
but that did not help either.
It seems like an easy thing to do and it is probably a beginner's mistake. I also keep reading that using global variables is frown upon, so I am trying to figure a way around that.
Could someone shed some light on this? Many thanks!
CodePudding user response:
def module1(b_count):
a = random.randint(1,3)
print(f"a = {a}")
if a == 2:
b_count = 1
Incrementing b_count
is purely a local change here; it has no effect on the variable that was passed in.
You'll need to either return the variable back to the caller and handle it appropriately there, or make it a global.