Computer Science Canada Trouble with variables |
Author: | asdfasdf123 [ Thu Dec 11, 2014 1:49 pm ] | ||
Post subject: | Trouble with variables | ||
What is it you are trying to achieve? I'm trying to make a slot machine game. What is the problem you are having? I can't use certain variables outside of a for loop, but I need them to make the game work. Describe what you have tried to solve this problem I've tried copy-pasting the rest of the program that uses those variables inside the for loop, but it didn't work. Post any relevant code (You may choose to attach the file instead of posting the code if it is too long) Here's the part of the code I'm having trouble with:
The "put left2" is just there to see if it works. Without it, the code runs normally, but with it, it says that "left2 has not been declared". I added left2, middle2, and right2 after seeing that left, right, and middle didn't work. I have previously declared CENTREX and CENTREY as maxx div 2 and maxy div 2 respectively. Please specify what version of Turing you are using 4.1 version 1.0.1 |
Author: | DemonWasp [ Thu Dec 11, 2014 2:08 pm ] | ||||||||
Post subject: | RE:Trouble with variables | ||||||||
It looks like you haven't learned about variable scope yet. The basic idea is that variables are only defined for some parts of the program, not for the program as a whole. For example, this doesn't work:
But this does work:
You might have noticed that this actually applies to the for-loop counter variable too:
This also works for other "blocks", like if blocks:
This is deliberate, because it lets the programmer choose where variables are accessible, which makes it easier to write clean, organized code. This feature also makes it easier to understand a program a little bit at a time, by understanding which information can "leave" a loop-end loop or if-end if. You could consider variables declared inside a block (for-loop, if, etc) to be like "temporary variables" that disappear when you are done the loop. When you get to learning about procedures and functions, the use of these temporary variables will be even more important. So to solve your current problem, just make sure that you declare your variables outside the loop. You can still assign them inside the loop, you just have to declare them outside the loop. |