1

I defined the 'timesUsrPlayed' variable outside of the funcion so it does not reset it. When I add 1 to the variable I get yellow wiggle lines under the times I call the var 'timesUsrPlayed' in the function 'randomPartOfGame'. when i hover over the lines it says '"timesUsrPlayed" is not defined Pylance(reportUndefinedVariable)'. I really hope I said that clearly:

import os
import random

# a funcion to clear the console
clear = lambda: os.system('cls')

# counts the plays
timesUsrPlayed = 0

def randomPartOfGame():    
    n = random.randint(0,6)
    p = random.randint(0,6)
    print(str(n) + " and " + str(p))

    if n != p:
        print("im sorry try again")
        randomPartOfGame()
        timesUsrPlayed += 1
    elif n == p:
        print("yay you did, it took you "+ str(timesUsrPlayed) +" times to get a double")
    


def mainGameFunction():
    print('game starting...')
    time.sleep(2)
    clear()
    print('welcome you need to get a double in dice (is means get the same number)')
    randomPartOfGame()
Maximo.Wiki
  • 631
  • 5
  • 17
jacob
  • 25
  • 1
  • 9

2 Answers2

1

I change your code, add global timesUsrPlayed first of your recursion function (for more details that why you need global variables in the recursion function read this link).

Then print(f"{n} and {p}") and print(f"yay you did, it took you {timesUsrPlayed} times to get a double").

Try this:

import os
import random
import time


# a funcion to clear the console
clear = lambda: os.system('cls')

# counts the plays
timesUsrPlayed = 0

def randomPartOfGame():    
    global timesUsrPlayed
    n = random.randint(0,6)
    p = random.randint(0,6)
    print(f"{n} and {p}")

    if n != p:
        print("im sorry try again")
        randomPartOfGame()
        timesUsrPlayed += 1
    elif n == p:
        print(f"yay you did, it took you {timesUsrPlayed} times to get a double")
    


def mainGameFunction():
    print('game starting...')
    time.sleep(2)
    clear()
    print('welcome you need to get a double in dice (is means get the same number)')
    randomPartOfGame()
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • ahh thanks, i also realized that i had the adding part after i recalled 'randomPartOfGame' so it was restarting before it added. – jacob Sep 11 '21 at 10:49
0

You have to use global keyword before timesUsrPlayed to access the global scope variable that's what you are missing example

  if n != p:
        global timesUsrPlayed
         print("im sorry try again")
         randomPartOfGame()
         timesUsrPlayed += 1

    elif n == p:
   print("yay you did, it took you "+ str(timesUsrPlayed) +" times to get a double")
    
SCouto
  • 7,808
  • 5
  • 32
  • 49