Coding with Variables and Functions in Python
In this Live Session, Alaina introduces coding with variables and functions in Python in VEXcode. Through intentionally simple examples, she will help you understand now just how to write a variable or function in a project, but also what variables and functions are and why they are useful when coding. This session will leave you with a foundation of where variables and functions can help make a project more efficient and organized by reusing values and/or code. Alaina uses VEXcode VR in this session, but the concepts apply to all VEX platforms that can be coded with Python.
Hello and welcome to the VEX Classroom. My name is Alaina and I am going to be here today taking you through our Coding with Python in VEXcode Live Session. Tonight, we're going to be talking all about functions and variables, how to create them, what they are, and we're going to be doing that inside of VEXcode VR.
The reason why we're doing this inside of VEXcode VR and why I chose this particular platform for tonight is because of the ease of using a virtual robot to iterate on your code and illustrate these features. It allows you to connect robot behaviors to the actual text-based commands. It's really helpful to use something like VEXcode VR because you have a chance to go through these rapid iterations and cycles without having to worry about picking up your robot, placing it into the exact right position, or ensuring that your build is 100% correct. It gives you the opportunity to stay completely focused on our code so we can move forward that way.
As we go through tonight, if you have any questions, please put them in the chat. Matt is here and will do his best to answer, or if not, we can also answer any questions in the community thread for this particular Live Session as well.
So let's go ahead and talk about variables and functions in VEXcode VR. I'm going to pull up my slides. Really, all of what we are doing tonight is going to be drawing shapes—a lot of squares, rectangles, or other types of shapes using variables and functions. The pen tool on the VR robot is such a valuable tool to make your code visible as part of that.
First, we need to talk about variables. Variables are used to store information. I like to think of variables as a bucket for different information. It's used to store a value. There are different types of values: integers, floats, booleans, and strings. Integers are whole numbers like 500, 2, or 34. A float is a number that uses a decimal point, such as 5.14. Although they function the same when you're looking at them in the code, there are also boolean variables based on boolean values, which are true or false. String values are generally sets of code inside of quotations. We are going to focus solely on integer variables because that's the easiest way to get started. However, I wanted to let you know that there are different types of variables available. This is useful when you have different repeating values, as it can make the code more readable.
Let's go ahead and start looking at variables in context. As we code in VEXcode VR, there are a couple of things to keep in mind. One, in order to code in Python with VEXcode VR, you need to have an enhanced or a premium subscription. I have my own class code pulled up right now, but you do need that. You can also code in Python on IQ second generation, EXP, or V5, and you can use the same principles that we talk about tonight to code on any of those platforms.
The main difference you will see between VEXcode VR and any of those physical robot platforms is the beginning code that you get. You see here: add project code in main, define main, drive for section, VR threads, and then VR thread main. This is just because of how VR works. If you're going to go into another platform, this would not be here, and all you would need is to just start typing in here. I'm going to go ahead and undo that because I do want to code in VR. I need all of these pieces, and all of my code tonight is going to be inside of here.
The first thing I want to do is drive forward, and I want to go ahead and turn right. This is going to become the base of what we are doing for all of our projects.
Thank you for joining us in this session. We hope you found it informative and engaging. If you have any further questions, feel free to reach out through the community thread. Happy coding!
And we need our pen down so we can see. So by this, you should know that when I press play, my robot's going to drive forward and turn right 90 degrees. So it draws a line and turns. It's a very basic program in Python.
Now, if I wanted my robot to drive in a square, I can copy this down and do this four times. Now my robot's going to drive in a square with 200 millimeters as the length of each side.
Let's say my teacher comes back and wants me to code a square that is now 400 millimeters on each side. I could go through and hard code and change every number as I go, or I have the option to create a variable so I only have to change it in one place. The first thing we need to do is define our variable. What's really nice about Python is it is very simple to define a variable.
So this is going to be my drive distance. Ooh, if I can spell that, my drive distance is going to be equal to 400 because that's what my teacher asked me to look for. So now what I can do is I can copy drive distance in everywhere where I have this 200 parameter. Let me move this over. And now if we run this, every time drive distance is referenced, you can see it even has a highlight here. It's gonna call back to this variable. At the very beginning, it's saying, oh, every time I see the word drive_distance, it's gonna be equal to 400. So it's storing that value for us. It's that bucket that we're carrying with us of values.
So now I can run this project and it drives in a square that is 400 millimeters on each side. I can do the same thing again with any other distance here, could do 800, any distance I could do as part of that. Now you can also set multiple variables. So in this case, I have just the drive distance set, but I also can set my angle.
So this can be a cool angle and this can be whatever you want to name it as long as it doesn't match a keyword inside of VEXcode VR. So my cool angle is gonna be, we're gonna start with 45 degrees. So now I'm gonna copy over cool angle. You could just type this too, but this is how I make sure I don't misspell anything. That's my tips and tricks: copy and pasting is a lot easier to prevent any potential spelling errors or syntax errors in your Python project.
So now if I run this, this is probably gonna run off the field. Yep, there we go, goodbye. Because 800 was way too far. So now instead of changing it in four places, I can go back, change that to 200 in one smaller place. And now I have the beginning of an octagon.
Let's say I wanted to continue this project, but I wanted to change these angles more often. So I wanted to do the first two at 45, but I wanted to do the last two at 75. I can do that. So you can actually change the variable in the midst of your project as well. So I can set cool angle to 75 degrees here.
What this is gonna do, let's walk through this together. Let me erase this. My robot's gonna drive forward for 200, turn right for 45, drive forward for 200, turn right for 45. Then it will drive forward for 200 because we haven't changed our drive distance, but it will turn for 75 degrees for the last two. So let's see that run as it goes through.
Now we're seeing how as you go through, you can reassign those variables at any time as you go through for this. Now you can have it do the reassignment or we could just set it to do some sort of calculation as well. So if I go back here, let me make sure all of this is correct. I can do cool angle times two, cool angle plus 40. Now this is not changing it for anyone else, this is just doing some sort of calculation on that first variable or on that specific instance. I'm not saying cool angle is now equal to 90 degrees. I am saying that just for this one instance, I wanna take whatever the value of cool angle is and multiply it by two.
So I should see this go a 90-degree turn first, something like an 85-degree turn, and then two 45-degree turns because we didn't manipulate or do any calculations with these ones. So that was a lot with those variables. I want to kind of go over and go through it again as we go through this.
With all of this, with learning about variables and functions, there's a lot of common misconceptions that can happen. Part of the benefit of doing something slow or doing something in VEXcode VR or both is that doing something slowly in VEXcode VR gives you an opportunity to do that testing to make sure that you and/or your students understand the fundamentals before you start to apply this to larger projects. That's also why we're just drawing simple shapes or wonky shapes as we go through because we want to understand the basics.
So with variables, we talked about how they can be used as a placeholder for a value. They're my bucket of information. You can name your variable whatever you want, as long as it doesn't recognize it as a keyword. So you can't call it something like the I sensor variable unless you wanted to type out i_sensor_variable because then you would have that modifier on the end. But when you name your variables very well, it makes the code a lot more readable. You noticed I named my variables their driving distance because that tells me exactly what that variable is used for.
Here you can see these are the exact same bits of code, but it makes it a lot more usable when it's time to change something. You can use it to store any kind of repeated value. On the left, that's driving a simple square; on the right, you're also driving a square, but in this case, you're using variables to store the driving distance and the turning distance. In this case, your driving is set to 200, and your turning is set to 90. You have those opportunities to go slowly through changing small values as you carry around those buckets, as I will continue to reference variables as. You also can reassign those values at any time.
Some other option that we didn't quite go through, I can show you real quick, is that you can continuously change the variable as well between each iteration. This could be a really cool thing to use as a spiral, or you could do that so it's constantly incrementing. Let's actually take a look at that because I have an idea for something that could be really cool to look at that's a little bit different than my wonky shape. I'm gonna get rid of my things here, and what I wanna do is after every iteration, we're gonna make this 90 degrees, we're gonna go right back to our square. After every side of our square is drawn, I want my drive distance. See, this is why I copy-paste because otherwise, you end up with issues. I want my drive distance to be equal to the previous value of my drive distance plus 200. So now every time it runs into this, it's going to count up by 200. The first time it would be 200, the second time it would be 400. If I ran this, we'd have 400, 400, and 400 because I've changed the value here.
You can tell the difference from what we did before where we just had the drive distance plus a number or multiplied by something. In this case, we're using our equal sign to reassign that value. The really important part here is if you are reassigning a value, you're gonna be using that equal sign. If I wanted to do this incrementally, I could copy this and put it in between each one, but I also could use a for loop in order to make this a little bit smarter and make my code a little cleaner.
Now we talked about for loops in the last session actually, but just as a recap, for those of you who may not have been here, a for loop functions just like a repeat loop in VEX in blocks. So what it's doing is for everything that's inside or indented within. You can see this indentation here.
Thank you for your attention and participation. If you have any questions, feel free to reach out. Looking forward to our next session!
Everything that's inside that indentation will be repeated for as many times as in these parentheses. So that is our parameter there. So I'm gonna change that to four. You'll notice actually if we look at our for loop here, that inside our for loop we have a variable that's set. So the for loop is built in with a variable called the repeat count variable. Every time you iterate through that loop, that variable goes up by one until it knows that it has repeated the action four times. So that is how your for loop works on the back end, on the inside.
If you understand variables, you can start to understand some of the other elements of code that we're using. Okay. So here I wanna think about, we're gonna talk through this as what is going to happen, and then we'll watch it happen. Because I wanna make sure that we're practicing reading the code and understanding what's gonna happen. Also known as code tracing. This is a skill that's very hard for students to do as part of it. So we're gonna go ahead and practice that ourselves.
So we're gonna come back up, you're gonna have to watch my drawing skills for a second. Let me see, there we go. Okay. So the first thing is we have a repeating, it's repeating four times. So we know that it's repeating four times. I'm gonna do my best so you can actually see this. But I wanna go ahead and trace this through. The first time the drive distance is equal to 200 and the angle is equal to 90. So it's going to drive for a little bit and then turn. So just a little bit. Now every time through that loop, my drive distance is going to have 200 added to it. So the second time it's gonna be 400. So that would be twice as long, but it's still gonna turn 90 degrees.
The third time through, we have 400 now is our variable set and we're gonna add another 200. So we're gonna be up to 600. So we'll go up to 600. I put my arrow in the wrong spot 'cause we need to turn right 90 degrees. And then finally that variable is now set to 600, but we're adding 200. So it's gonna go to 800. And then turn. So we should see something like this, like the beginning of a spiral.
This is a really good practice, especially with VEXcode VR because you can easily do this, but this is a really good practice to use with your students, even if you're using physical robots, to have them literally trace out what their robot is going to do based on their code. Have them sit down and read a code snippet that you provide or that they are about to use as part of their pseudo code and have them read through and try and understand what their code is doing with each part.
So let's go ahead watch it in VEXcode VR. So now we know roughly what shape this should make. So I'm gonna hit the play button.
We have our short line, little bit longer, little bit longer, and then twice as long as that second line. So we're seeing that incrementing value because every time it goes through this loop, it's taking the current distance and adding 200 to that. So this is when you start to modify those variables in action. You can do that in a loop, you can do that in many different ways. But those kind of calculations are what make variables so valuable, so versatile is those buckets can do calculations for us, we can change them at any time. It's just somewhere for us to store a value for later so we don't have to do it ourselves or do that hard math or do those calculations ourselves in order to do the hard coding. This just gives us a lot of flexibility in our code.
I will say as well that with all of these examples that I'm showing as I'm changing things, this is representative of how I choose to code. Everyone has their own coding styles, their way to solve a problem. So there's not necessarily one correct answer when you're looking at a code snippet. As long as the robot performs the behavior that it should, then you're doing your code in your own correct way.
Now, as educators, you may want students to practice certain concepts, so you want them to solve the challenge using variables and for loops. That's great. Let's think about how we could solve this in different ways. We could solve it by doing this particular calculation every time we repeat this and actually get rid of one of our loops. There are a lot of different options. I just wanted to point out that there are many ways to code, and sometimes one specific solution key doesn't always work out because there are different answers. We're going to see that as we move on into our functions.
So this wraps up our discussion on variables, and we're going to come back to variables. However, functions themselves are directly related to variables as part of this. Give it one second, it's loading. Okay. So we're moving on from the bucket and transitioning to a shipping container or a storage container. I was really thinking more like a plastic bin—something much larger but still carryable. However, a shipping container works very well too because you can keep things organized within, but you can keep a lot more information.
With functions, you're storing snippets of code instead of just values like integer, boolean, float, or string values. In this case, we are storing snippets of code. We're using that to make our code more readable and also to easily reuse bits of code many times. For those of you familiar with my blocks in block-based coding, functions are essentially my blocks, or my blocks are functions. This is just a different way to use them in your projects.
Now, as we look at what a function looks like, you're going to notice some similarities in how they're used. Excuse me. We'll go back over to VEXcode VR. So now we're in the shipping container. We're leaving our bucket behind for now. We'll come back for the bucket. Let me move all of these back. Get rid of our indentation because we no longer need it. Ooh, not 900 degrees. That would be unfortunate.
In order to define a function, you're going to do this at the very beginning of your project. Any kind of Python project, it also works in block projects, are read top to bottom. So we need to make sure that things like variables and functions are all defined at the beginning of our project. What we are going to do is define a function. So that's going to start with the def. So define, and we're going to call this function Fun Shapes because we can. I'm going to add these parentheses. This is part of the syntax of that. We're going to come back to what goes in those parentheses in a little bit. But for now, we just need those parentheses. It automatically starts to indent what I am doing. Indentation is so important. Everything for your function that you want to repeat is going to be kept inside of that indentation.
For me, I want to go back and repeat these two commands. I know that I'm going to want to repeat them over and over. So for my fun shapes, I want to drive forward and turn. Now, in order to actually use that function, because if I started this project right now, the only thing that would happen is my pen would move down. See, you can't even see the pen move down as it goes because we define the function, but now we need to call that function. We need to reference the function, and we're going to do that by using our name. So I'm just going to put here fun shapes. Now, if I run this again, it's going to drive forward and turn. So it puts the pen down, and then I call fun shapes. It says, "Oh, I've seen that name fun shapes before. Let me go back up to where I defined everything, go back to my storage container, and run what's inside of that storage container." Running that code. I can repeat this multiple times. So I can do fun shapes, fun shapes, fun shapes, and draw that 200-millimeter square.
Thank you for your attention and participation. If you have any questions or need further clarification, please feel free to reach out. Happy coding!
And now, just like that very first problem we had with our variables, my teacher says, "Oh, I actually want you to, you misheard the instructions, I'm sorry. It needs to be 500 millimeters on each side." So now, by changing one number, once again, I can easily change it. My square is being drawn at different sizes.
You can do this in a lot of different ways. You can repeat the function as well using a for loop. You don't have to just repeat them down here. There are a lot of different options for how you organize your functions and organize your code. Now, if I wanted to, the problem here is that right now, if I wanted to change this partway through my project, I cannot. I'm stuck with 500 on each side. If I wanted to draw a rectangle, I could add additional pieces here. I could make this 500 and 300 and then get rid of two of these. So now they're starting to change our shapes as part of that, but that's kind of clunky. I don't really want to use something like that.
What I can do is I actually can add a variable inside of my function as well. So I'm gonna add driving is equal to 500 or just changing variable names 'cause it feels fine. So driving minus 200. So now I can do the same thing, I'm running the same project with a rectangle, but what I'm doing is I'm calling a variable, I'm doing a calculation. It all is running just like how the rest of our variables ran before, but now we have an opportunity to do that inside of our function.
When you look at our code itself, our code is very clean, define main and then these. If you notice also this little bit of uniqueness to VEXcode VR is we're actually coding in the main function while we're doing this. This is an aside, you don't need to know this in order to code with functions. But it's interesting to notice that here we're defining main and that's where we're adding all of our project code. But then what is running VR? How VEXcode VR runs is by running this thread and then running the main function within it. So we're actually using a function within a function as we create them in VEXcode VR, which I think is really cool.
As you start to understand what a function is and how to use it, you can start to recognize those similar pieces. Just like how we saw with the for loop that there were variables inside as well. So now we have our variables in here, we're driving, we're doing calculations. But really, Alaina, I don't wanna do calculations in the middle of a function. I'd rather be able to just change it every time. I'm sure some of you are saying that and wondering what on earth those parentheses are for, which is our variables as parameters.
We are all familiar with parameters such as forward 200 in millimeters. Those are all different parameters that are passed to our main code so that they can run that. So it knows how far to drive forward. You're using parameters with every kind of command that you use more or less. So what we are gonna do is we're gonna define the parameters that we wanna use for this function. So let me get rid of this. Instead of saying that driving is equal to 500, we're gonna say fun_shapes(parentheses driving). So now I have driving here and driving here. But I have nowhere so far where I'm telling it what number driving is equal to. That's where it comes in when you call the function down here.
So now if I say fun_shapes(parenthesis 300), then fun_shapes(parenthesis 600). The first time it calls this function, it knows that driving is equal to 300. The second time it calls this function, it knows that driving is equal to 600. So we can see that run. So now we have even more options for what to do with our robot and what to do with our functions as well. Now you can add more than one parameter also. So you have driving, angles. Well, let's make that a nicer name: Turning. Driving and turning.
That's a nice parallel name. Driving, turning. So now we're gonna separate them with commas. Oops, excuse me. I clicked a little too hard on my mouse. So we're gonna separate them with commas. When you can see that we separated parameters with commas before in our drive train command. So right, the turn distance, degrees. We've seen that practice previously.
So now I can say 300, 45, 600, 950, I don't know, whatever you want it to be. And now that's a lot of degrees to turn. But now you have the option to do all these different types of movements because you know that every time you do your fun shapes function, it's going to do your drive for and your turn for, for whatever distances you specify as part of that.
Let's think about, let me see. There are a lot of math applications for this as well. For this, you can do a lot with division, with calculations to actually do the perimeter calculations, to do those interior angle formulas, and actually put them in your parameters here as well. So if I wanted to draw a rectangle here, let's think about my options.
What I would do, let's see. I am going to edit this right up in my function. This again happens to be one of those ways that you can just modify things depending on who you are and what your coding style is. So I'm gonna make this 300, 90, and I'm gonna make this, oh no, I'm gonna do the same thing, 300, 90 because what's going to happen if I trace this out, I'm going to drive forward for 300 millimeters. I'm gonna turn right for 90 millimeters, then I'm gonna drive forward for 600 millimeters, then I'll turn right for 90, then I'll drive forward for 300, turn right for 90. So it's still that cyclical process, but now we're actually doing calculations even with our parameters as well.
I could do that with the parameters here. I could have just done 300 and 600 over and over. And just repeated this. And we should see the exact same shape now. So again, going back to the fact that there are a lot of ways to solve the same problems and to solve the same challenges.
Now I wanna kind of think about with everyone now that we've kind of gotten through the big tactical, like what is a variable? What is a function? Why am I using them? I wanna think about real-world robotics applications. So what you could be doing with them. Because now we understand how they function, but now we wanna talk more about why we would use them.
If you do have any questions about what we just covered with what are variables and what are functions, please post them either here or especially in the community 'cause then I can answer them directly. We can talk more about it. The other great thing about being in the community is that the VEXcode software developers are also in the community. So if you have some more advanced coding questions, there are people who actually created VEXcode VR inside of the community as well, which is a really fantastic tool and resource as you're learning more of these advanced Python things.
So let's talk about, we know a variable is something to store values. It's our bucket to store values. Our function is our larger bucket, our shipping container to store snippets of code. You can store buckets inside of your shipping container if you wanted to, or you could use your bucket to transport things in and out of your shipping container with those parameters. I think that analogy works at least most of it. If you have a better analogy, also please share that because I'm working with buckets and shipping containers and I feel like there's something more fun out there and probably a little more accurate.
But thinking about why you would use a function or a variable. The first thing I wanna think of when I think of functions and reusing code is I think about in VEX EXP we have the ringleader STEM lab. Or in IQ we have the Cube Collector STEM Lab.
In both scenarios, you are closing your claw around an object, lifting it up, whether it be a cube or a ring, moving it forward, and placing it either on top of a stack or around a post. With that, you're performing the same actions repeatedly. You know exactly how high you want to lift the arm, how far forward you need to drive, and how far down to put the arm to get it on the post or the stack.
With this repetitive action, you have a great opportunity to use a function to keep that code reusable, making it more readable and accurate. Once you've tested that code once, you should be able to use it again and again without needing the full testing process or being able to test it in smaller chunks. That's one really good use. You could also use parameters in that particular instance to distinguish between different heights. For example, is it a stack of two cubes that you're putting a third one on? Is it a stack of three cubes that you're putting a fourth one on? You could have a variable set based on the height of your cubes because you would know what number of cubes you have stacked inside of your VEXcode project.
Those are just a couple of examples, and I'm sure as we get more into the competition season, there'll be even more ideas for how to use functions and variables. But just to recap one last time, let's go ahead and look at what a function and a variable are, and then I will give you the rest of your evening back. So let's go ahead and take a look.
Music Cue
The first thing to know is that variables store information. They're used as a placeholder for a value and can make your code more readable if they are named well. One thing about variables is that they are made to store inside of a local area. So if you have that variable set inside of your function, and if I set another variable, let's get rid of driving as a variable, we'll make these variables again in one moment. We're going to do another fun thing because I forgot about it.
Now, what's interesting is that if I put in here driving is equal to 600, but I put down here inside of this code that driving is equal to 200, it's interesting to think about which one it is going to take. Is it going to take the 200 or the 600? So let's find out. Turning, oh, I forgot about the turning. That is my bad. So what's nice is we can actually look at this error here. It says the name turning is not defined. When I looked over, I still had turning here in my 90 degrees. So let's go ahead and restart that. I'm going to clear the console.
Music Cue
It's doing the 600 millimeters forward. Why it's doing that is because our variables are stored locally. You don't take your bucket and it's not just a pass-around to everyone else; it's your bucket. It's this function's bucket. It cannot live in two different storage containers at once, to keep the analogy going. So you're saying that this driving is 600, and this down here is a brand new variable that has nothing to do with anything else because we've never used the word driving down here. So this is as good as being not here at all. If we tried that again, the exact same thing would happen as part of that. That's what I mean when I say variables are stored locally. They're stored within that function that we're working with. Your bucket can only live inside of one shipping container at one time inside of VEXcode VR Python. That also helps when they're repeating values as part of it.
We also talked about the four different types of variables. We focused only on integer variables today. There's also float, which again has a decimal point. A boolean uses a true or a false value, and a string is some sort of text generally, and that is in quotations. For functions, they store snippets of code.
Thank you for your attention, and I hope this session has been informative. If you have any questions, feel free to reach out. Have a great evening!
So those are our shipping containers, and it makes our code more readable. It also makes it really easy to reuse bits of code multiple times, as we saw through these examples. All of the examples I've walked you through are actually in the slideshow as well.
When I go ahead and post the recording of this video in the community thread on PD Plus, I will also share these slides. This way, you can go through, recreate the same projects that I did, and test them out yourself. Or you could watch the recording again and follow along with me in real time.
I hope that was all helpful information, learning about functions and variables in VEXcode VR, in Python, and seeing how they're all interconnected. Again, you can do all of these same things and apply all of these same concepts with your physical robot for IQ second generation, EXP, or V5.
I can't wait to see what you do with Python in your classroom, with your students, or even for your own learning. I'll see you in the community.
Thank you.
(upbeat music)
Share
Like this video? Share it with others!
Additional Resources
Want to join this live session? Register for Coding with Python here.
You can also join the conversation about this session in the VEX PD+ Community!
Additional Links