-5

I want to make a function work like an on off switch in python. I know how to do it in Javascript, but I don't understand how indenting works with Python, can someone help point me in the right direction?

<p id="demo">test</p>
<button onClick="myFunction()">change</button>

<script>
var onoff = 1;

function myFunction() {
    if(onoff == 1){
        document.getElementById("demo").innerHTML = "one";
        onoff = 2;
    }
    else if(onoff == 2){
        document.getElementById("demo").innerHTML = "two";
        onoff = 1;
    }
}
</script>
onoff = 1

def test():
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1


test()
test()
test()
test()

1 Answers1

0

This is about scope as @jonrsharpe commented.

Did you run and notice the error below?

UnboundLocalError: local variable 'onoff' referenced before assignment

There are many solutions. Here is an example.

onoff = 1

def test():
  global onoff
  if onoff == 1:
    print("on")
    onoff = 2
  elif onoff == 2:
    print("off")
    onoff = 1


test()
test()
test()
test()

see:

shingo.nakanishi
  • 2,045
  • 2
  • 21
  • 55