1
| |
i'm trying to teach myself how to do some python and i've run into this problem multiple times, and what better place to ask then LP?
tried googling but maybe i'm just getting old and have a short attention span now or just suck at looking for answers online
def x(y):
if y == 0:
print("Turn on"
y = 1
else:
print("Turn off"
y = 0
when X runs (y = 0 by default), y doesn't update to 1 so the switch stays off.
from my understanding, something about each X being a separate instance or perimeters can't be variables or something something i don't fucking know. how do i fix this
|
|
|
1
|
bigredhoss   Cook Islands. Sep 22 2016 21:26. Posts 8649 | | |
have you tried putting the code in python tutor? http://pythontutor.com/ - i remember it being pretty helpful for visualizing when i was messing around with python.
i could try to guess what the problem might be but i'm sure someone who actually programs will come by with a better answer. |
|
|
|
1
|
Rinny   United States. Sep 22 2016 23:50. Posts 600 | | |
That's not how the whitespace actually is right? Assuming everything is indented correctly the program should print turn on and y should be set to 1 |
|
|
1
|
def_jammer   Germany. Sep 22 2016 23:58. Posts 1227 | | |
I guess because you are changing a local copy of the variable. If you want to do a globally visible change you have to declare y as global in the function body in which case you also have to change the parameter name though |
|
|
1
| |
ok i did this:
y = 0
def x():
global y
if y == 0:
print("hi"
y = 1
else:
print("bye"
y = 0
x()
print(y)
|
|
|
1
| |
LP messing up indents and turning " ) into a smiley |
|
|
1
|
Spitfiree   Bulgaria. Sep 23 2016 00:42. Posts 9634 | | |
Not sure how python executes code, but javascript would never print " turn off " as written, as its being changed locally as the above post said.
Also don't dive too deep into such insignificant tasks learn the scopes of global/local variables and which data type is what, and when to use which ( like when to use arrays, when objects etc. ). I'm learning coding myself and tbh once you grasp the idea of the fundamentals you just have to start reading and learning documentation while doing projects. Took me about 4-5 months to grasp most of the fundamentals and im yet to fully understand some things and im far away from understanding the things behind the code itself, how its being executed and etc.. What I mean is, there are plenty of things to focus on |
|
| Last edit: 23/09/2016 00:50 |
|
|
|