1
from random import randrange

on = ''

max_number = 0
random_number = 0

def start():
    max_number = int(input('Enter max generated number: '))
    random_number = randrange(max_number)
    print(random_number)
    on = True

start()

print(on) # returns false??

for a school project, i need to make a number guessing game. This is the start code i have. I declared "on" before the start function but the function wont change the value of the boolean to true

Aidan
  • 13
  • 4
  • on = False. I was trying new methods and copied the wrong one. it should not be on = ' ' – Aidan Apr 04 '21 at 16:42
  • 1
    Using global values is a bad habit to get into; it will end up slowing you down later when you have to unlearn it (and you *will* have to unlearn it). Use `return` to return the values from the function to the caller, and have the caller assign them. I.e. end your function with `return max_number, random_number` and then call it like `max_number, random_number = start()`. I doubt that you need the `on` variable at all. – Samwise Apr 04 '21 at 16:44

1 Answers1

1

Right now, on is a "local" variable, only seen and used inside the scope of the function. To change the value of any variable inside and outside the function, you need to type the command global {variable}, usually at the top of a function. In your case, add this to your function:

def start():
    global on <-- Right Here
    max_number = int(input('Enter max generated number: '))

You can research more about global and nonlocal variables online. Acknowledging @Samwise comment, global and nonlocal variables aren't always the best option, but I think that it's best to learn it anyway (the more you know!). He is correct, that you will likely not even need the on variable, and also that using a return statement is the best option.

Dugbug
  • 454
  • 2
  • 11