2022PythonExamples/5 - Random Numbers and For Loops/README.md

34 lines
2.7 KiB
Markdown

# Random Numbers and For Loops
## What is a For Loop, and why do I care?
There are times where you're going to want to repeat a task or section of code in your program a certain number of times. For Loops take care of this for us. We create a for loop structure like this
```
for indexVariable in range(someNumber):
DO SOME STUFF
```
The indexVariable element stores the current loop iteration number, or index. The range() function creates a sequence of numbers that we can use from 0 to someNumber-1. i.e. If you said range(5), you'd get a list of numbers 0, 1, 2, 3, 4.
## Can you tell me more about range?
There are different types of "ranges" but range() is pretty common to see when first starting out. Range isn't limited to just creating 0..N-1 ranges, you can do more stuff with it.
Lets say you wanted the range to start with 1 instead of 0. You can say range(1, 6), and this will give you a list of numbers 1, 2, 3, 4, 5.
Lets say you wanted to count by 2's instead of by 1. You can say range(0, 5, 2), and this will give you a list of numbers, 0, 2, and 4.
You can even count backwards. range(4, -1, -1) will give you a list of numbers 4, 3, 2, 1 and 0.
You'll have to decide what goes into range() when you are writing code for whatever it is your doing.
## Random numbers, why do I need those?
For Robot Programming, you probably don't. It's pretty rare for a use case to show up where a robot needs to do something based on random input, as it generally isn't very safe to do something like that.
Random makes for easy examples when working with For Loops, which is why it's included here, and in general programming, it's seen a lot of different places, cryptography and securing communications and data especially. For these examples, it just makes for a nice talking point for how loops can be used to repeat a process several times over.
## Why do we "import random"?
Not everything is available to you all at the same time in Python. Some stuff is in seperate packages called "Modules" that extend the functionality of the base language. In order to work with the extra stuff in the Modules we want to use, we have to "announce" with an import statement that we want to use the module.
Some modules (like random) come with Python can don't need to be installed, other modules, like RobotPy and its assoicated pieces, need to be installed, usually through the command line utility pip, before they can be added in your program.
On top of importing separate modules, you can import additional code that exists within your own project. We'll see some of this further down the line in other lessons, but for now, just know that importing becomes much more important as your programs (whether they be for robots or not) become larger and more complex.