0

I am new to Python.

How can I accomplish something like this:

def gameon():
  currentNum = 0
  for x in range(100):
    currentNum+=1
    otherfunc()

def otherfunc(maybe a possible parameter...):
  for y in range(500):
    #check for some condition is true and if it is... 
    #currentNumFROMgameon+=1

My actual code that used global variables:

def gameon():
  global currentNum
  currentNum = 0
  for x in range(100):
    currentNum+=1
    otherfunc()

def otherfunc():
  global currentNum
  for y in range(500):
    if(...):
      currentNum+=1
global currentNum

How can I accomplish this(accessing and changing currentNum from otherfunc) without making currentNum global?

2
  • Have you tried passing currentNum to the function and let the function return the modified version of currentNum? Commented Sep 6, 2017 at 9:57
  • @araknoid ahh that works, thanks. But what if it should go through a function with a purpose of returning true or false based on some conditions but it would also have to increment "currentNum"? Commented Sep 6, 2017 at 10:06

1 Answer 1

1

If you want to have access to currentNum in otherfunc you should pass it to that function. If you want otherfunc to change it, simply have it return an updated version. Try this code:

def gameon():
  currentNum = 0
  for x in range(100):
    currentNum+=1
    currentNum = otherfunc(currentNum)

def otherfunc(currentNumFROMgameon):
  for y in range(500):
    if True: # check your condition here, right now it's always true
      currentNumFROMgameon+=1
  return currentNumFROMgameon
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! But what if it should go through a function with a purpose of returning true or false based on some conditions but it would also have to increment "currentNum"?
@overso You could write a separate function that returns True or False. That function will have to receive whatever it needs as input variables. Though generally if such a check is simple enough, it's easier to just check it in an if statement rather than write a separate function for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.