diff --git a/lessons/01-flowcharts/README.md b/lessons/01-flowcharts/README.md index baa741c..2fd8981 100644 --- a/lessons/01-flowcharts/README.md +++ b/lessons/01-flowcharts/README.md @@ -7,21 +7,15 @@ section: "Programming with Blocks" # One step at a time -Before we write a single line of Python, let's get the big idea out of the way: -**a program is a list of instructions, and the computer runs them one at a time, -in order.** It never skips ahead, and it never runs two steps at once by -accident. It finishes one box, updates its memory, and follows the arrow to the -next box. +Your robot is powering on for the first time, and it knows nothing about FRC yet. Before we write a single line of Python, let's get the big idea out of the way: **a program is a list of instructions, and the robot runs them one at a time, in order.** It never skips ahead, and it never runs two steps at once by accident. It finishes one box, updates its memory, and follows the arrow to the next box. A **flowchart** shows that exact journey from **START** to **END**: -- Each **box** is one instruction — like storing a number or doing math. +- Each **box** is one instruction, like storing a number or doing math. - Each **arrow** shows which step runs next. -- **Robot Memory** at the bottom shows the named values the robot is remembering - right now. +- **Robot Memory** at the bottom shows the named values the robot is remembering right now. -The flowchart here calculates an FRC robot's **autonomous score**: `3` coral at -`4` points each, plus a `3`-point bonus for leaving the starting zone. +The flowchart here teaches the robot how an FRC **autonomous score** works: `3` coral at `4` points each, plus a `3`-point bonus for leaving the starting zone. Press **▶ Run** (or click **⏭ Step** to advance one instruction at a time) and watch **Robot Memory** update as each box lights up. You can also click diff --git a/lessons/05-what-is-java/README.md b/lessons/05-what-is-java/README.md index c4011fd..2825881 100644 --- a/lessons/05-what-is-java/README.md +++ b/lessons/05-what-is-java/README.md @@ -7,15 +7,15 @@ section: "Python Fundamentals" # A language, not a magic spell -You've been building programs already, as flowcharts of blocks ([lesson {n}](#/lesson/01-flowcharts) onward). From here on we write those same ideas as **text**, in a language called **Python**. +Your robot has been learning the basics through block flowcharts ([lesson {n}](#/lesson/01-flowcharts) onward). From here on we write those same robot instructions as **text**, in a language called **Python**. Why does FRC 2713 teach software fundamentals in Python? Python reads close to plain English and keeps extra boilerplate out of your way, so you can focus on the core ideas: variables, decisions, loops, functions, objects, and state machines. Those concepts carry straight over to any language you use on the team later, including Java for robot code, and Python itself is useful for scripts, data analysis, and team tools. -A programming language is a strict set of grammar rules. English is forgiving. "Computer the on it run" is garbled, yet a person can still guess what you meant. Python won't guess. Every instruction has to follow the rules, or Python stops and points to the exact line that confused it. That isn't the computer being difficult; it's the computer telling you what it needs fixed. +A programming language is a strict set of grammar rules. English is forgiving. "Robot the on it run" is garbled, yet a person can still guess what you meant. Python won't guess. Every instruction has to follow the rules, or Python stops and points to the exact line that confused it. That isn't the computer being difficult; it's the computer telling you what it needs fixed. Two habits matter right from the start: -- **Python is case-sensitive.** `Print` and `print` are different words to Python, just like "Rex" and "rex" are different if one is a name and the other isn't. Spelling has to match, capital letters included. +- **Python is case-sensitive.** `Print` and `print` are different words to Python, just like `"Intake"` and `"intake"` are different strings. Spelling has to match, capital letters included. - **Indentation matters.** Python uses spaces at the start of a line to group steps that belong together. Lining code up isn't just for neatness here; it's part of the grammar. # The punctuation you'll see everywhere @@ -24,37 +24,37 @@ Before you write a single instruction, it helps to recognize the symbols Python ```text : colon - starts an indented block of steps -( ) parentheses - hold the "ingredients" a function needs -, comma - separates ingredients when there is more than one +( ) parentheses - hold the inputs a function needs +, comma - separates inputs when there is more than one " " quotes - mark exact text, called a "string" # hash - starts a comment (a note for humans) ``` - **Colons `:`** sit at the end of a header line to say "an indented block of steps comes next." You'll see them on `if` statements, loops, and functions. - **Parentheses `( )`** hold what an instruction needs to do its job. Some instructions need nothing (`()`), some need one thing, and some need several. -- **Commas `,`** separate those things when an instruction needs more than one, the same job a comma does in "eggs, milk, and flour." +- **Commas `,`** separate those things when an instruction needs more than one, the same job a comma does in "intake, shooter, and climber." - **Quotes `" "`** mark exact text for Python to use as-is, called a **string**. Anything inside the quotes is data, not instructions, so Python won't try to run it. - **Hash `#`** starts a **comment**. Anything after `#` on a line is a note for humans, and Python skips right over it. # Reading a program's shape -Here is a tiny Python program so you can see those symbols working together: +Here is a tiny Python program for our robot so you can see those symbols working together: ```text -# a short Python program -def greet(name): - print("Hello, " + name) +# announce the robot's current match mode +def announce(mode): + print("Robot mode: " + mode) -greet("Ada") +announce("auto") ``` Don't worry about memorizing this yet. You'll learn to write your own functions in [lesson {n}](#/lesson/11-writing-methods). For today, just spot the pieces using the vocabulary above: -- `# a short Python program` is a comment that Python ignores. -- `def greet(name):` defines a reusable block named `greet` that expects one input, `name`. The colon at the end tells Python an indented block is coming next. -- ` print("Hello, " + name)` is indented by four spaces, so it belongs *inside* `greet`. -- `greet("Ada")` is back at the left edge, outside `greet`, so Python runs it and hands `"Ada"` into the function. +- `# announce the robot's current match mode` is a comment that Python ignores. +- `def announce(mode):` defines a reusable block named `announce` that expects one input, `mode`. The colon at the end tells Python an indented block is coming next. +- ` print("Robot mode: " + mode)` is indented by four spaces, so it belongs *inside* `announce`. +- `announce("auto")` is back at the left edge, outside `announce`, so Python runs it and hands `"auto"` into the function. Notice how indentation shows what belongs to what, just like a box drawn around steps in a flowchart. Python doesn't require an outer wrapper class to start running code, so a one-line script is already a valid program. -You now know enough vocabulary to read Python without getting tripped up by the syntax. Next lesson, you'll write and run your first real instruction. +You now know enough vocabulary to read Python without getting tripped up by the syntax. Next lesson, you'll run the robot's first real instruction. diff --git a/lessons/06-hello-world/README.md b/lessons/06-hello-world/README.md index 47a085f..955de9e 100644 --- a/lessons/06-hello-world/README.md +++ b/lessons/06-hello-world/README.md @@ -11,19 +11,19 @@ You've already been building programs as flowcharts of blocks. Everything you di A **program** is a list of instructions, written in a language a computer can follow step by step, in order. -That's it. Not magic, just a recipe: "Crack two eggs. Whisk them. Pour into a hot pan." A computer program is the same idea, except the kitchen is the computer's memory and screen, and the chef is the computer itself, which follows your instructions *exactly* as written, including your mistakes. +That's it. Not magic, just a pre-match checklist: "Zero the gyro. Spin up the flywheel. Drive forward two meters." A robot program is the same idea, except the robot controller follows your instructions *exactly* as written, including your mistakes. Everything you learn here builds the foundation you'll use for FRC robot software, simulations, and team tools. # Your first program -Here is a complete, one-line Python program: +When a robot boots up on the workbench, the first thing you want to know is that it is alive and talking to the driver station. Here is a complete, one-line Python program that prints its first message: ```python print("Hello, world!") ``` -`print` is a function that means "show this on the screen." The text in quotes is exactly what gets shown. Computers don't know that `Hello, world!` is a greeting; they just do what they're told with the data they're given. Each instruction sits on its own line, with no semicolon needed at the end. +`print` is a function that means "show this on the console." The text in quotes is exactly what gets shown. The robot doesn't know that `Hello, world!` is a greeting; it just does what it's told with the data it's given. Each instruction sits on its own line, with no semicolon needed at the end. Two things to know about the playground before you press Run: @@ -36,10 +36,10 @@ Now break it on purpose. Try changing the text between the quotes, removing a qu # Your turn -Edit the code below so it prints a greeting with **your own name** in it, instead of `world`. Run it to check. +Edit the code below so the robot announces itself to the driver station with **your robot's name or team number** instead of `world`. Run it to check. ```python print("Hello, world!") ``` -Once that works, add a second line that prints something else about yourself, like your favorite subject or a hobby. Each `print(...)` line runs in order, top to bottom, and produces its own line of output. +Once that works, add a second line that prints a startup status, like `"Battery checked"` or `"Autonomous armed"`. Each `print(...)` line runs in order, top to bottom, and produces its own line of output. diff --git a/lessons/07-variables/README.md b/lessons/07-variables/README.md index 4e4bd94..e8f8488 100644 --- a/lessons/07-variables/README.md +++ b/lessons/07-variables/README.md @@ -7,20 +7,20 @@ section: "Python Fundamentals" # A name for a value -Back in [the very first lesson](#/lesson/01-flowcharts), every **number block** held a value, and arrows carried that value forward to the blocks that needed it. In Python we do the same thing with a **variable**: a name that stands for a value. +Back in [the very first lesson](#/lesson/01-flowcharts), every box stored values in **Robot Memory**, and later steps read them back. In Python we do the same thing with a **variable**: a name that stands for a value. ```python -name = "Ada" -print("Hello, " + name) +robot_name = "Red Hawk" +print("Booting " + robot_name) ``` -Read the `=` as "gets" or "is set to," **not** as "equals" from math. It means: take the value on the right, and store it under the name on the left. After that line runs, the name `name` holds the text `"Ada"`, and anywhere you write `name` Python reaches in and uses that value. +Read the `=` as "gets" or "is set to," **not** as "equals" from math. It means: take the value on the right, and store it under the name on the left. After that line runs, `robot_name` holds the text `"Red Hawk"`, and anywhere you write `robot_name` Python reaches in and uses that value. -Every value in Python has a **type**, which is the *kind* of value it is. `"Ada"` is a `str` (short for *string*, meaning text). Python figures out the type from the value you assign, so you don't have to write `str` in front of `name`, and it still tracks the type behind the scenes. More on types in [lesson {n}](#/lesson/08-numbers-and-text). +Every value in Python has a **type**, which is the *kind* of value it is. `"Red Hawk"` is a `str` (short for *string*, meaning text). Python figures out the type from the value you assign, so you don't have to write `str` in front of `robot_name`, and it still tracks the type behind the scenes. More on types in [lesson {n}](#/lesson/08-numbers-and-text). -The `+` between `"Hello, "` and `name` **joins** text together into one string, so this program prints `Hello, Ada`. +The `+` between `"Booting "` and `robot_name` **joins** text together into one string, so this program prints `Booting Red Hawk`. -Press **Run**. Then change `"Ada"` to your own name and run again. Notice you only had to change it in **one place**, even though the name gets *used* on the next line. That's the whole point of giving a value a name. +Press **Run**. Then change `"Red Hawk"` to a name for your own robot and run again. Notice you only had to change it in **one place**, even though the name gets *used* on the next line. That's the whole point of giving a value a name. # Use a name as many times as you like @@ -41,14 +41,14 @@ You can name a variable almost anything, as long as it starts with a letter or u # A variable can vary -Here's where the name earns the word *variable*: the value it holds can **change** while the program runs. Assigning to a name a second time replaces what was there before. +Here's where the name earns the word *variable*: the value it holds can **change** while a match runs. Assigning to a name a second time replaces what was there before. ```python score = 0 -print(f"Starting score: {score}") +print(f"Match start: {score}") score = 10 -print(f"After scoring: {score}") +print(f"After autonomous: {score}") score = score + 5 print(f"After a bonus: {score}") @@ -56,4 +56,4 @@ print(f"After a bonus: {score}") Read those last two assignments carefully. `score = 10` throws away the old `0` and stores `10`. Then `score = score + 5` looks strange until you remember `=` means "gets set to," not "equals." Python works out the right side first (`10 + 5 = 15`), then stores that back into `score`. This "take the value, change it, put it back" pattern is the same running total the **repeat** block kept in [lesson {n}](#/lesson/03-loops), a value that updates itself one step at a time. -Your turn: add a line that gives a `10` point penalty (subtract, don't add), then print the score again. Predict the final number before you run it. +Your turn: add a line that takes a `10`-point foul penalty (subtract, don't add), then print the score again. Predict the final number before you run it. diff --git a/lessons/08-numbers-and-text/README.md b/lessons/08-numbers-and-text/README.md index fc9be27..14f3ac6 100644 --- a/lessons/08-numbers-and-text/README.md +++ b/lessons/08-numbers-and-text/README.md @@ -25,25 +25,25 @@ Run it. The lesson: the *quotes* decide everything. `7` is a number you can add; # Text that looks like a number -Sometimes a value *looks* like a number but is really text because it's wrapped in quotes, like `"24"`. If you try `"24" + 1` in Python, it stops with a `TypeError` because Python refuses to guess whether you meant `"241"` or `25`. +Sometimes the field management system or driver station sends a value that *looks* like a number but arrives as text wrapped in quotes, like `"24"`. If you try `"24" + 1` in Python, it stops with a `TypeError` because Python refuses to guess whether you meant `"241"` or `25`. The fix is to **convert** the text into a real number with `int(...)`: ```python -age_text = "24" -age = int(age_text) -print(f"Next year you will be {age + 1}") +match_text = "24" +match_number = int(match_text) +print(f"Next up: qualification match {match_number + 1}") ``` -Using a separate name for the converted number (`age_text` for the `str`, `age` for the `int`) keeps the program easy to read. You can tell at a glance what is text and what is a number, building on the naming habit from [lesson {n}](#/lesson/07-variables). Inside the f-string, Python evaluates `age + 1` first before inserting the result, just like inner-first evaluation in [lesson {n}](#/lesson/01-flowcharts). +Using a separate name for the converted number (`match_text` for the `str`, `match_number` for the `int`) keeps the program easy to read. You can tell at a glance what is text and what is a number, building on the naming habit from [lesson {n}](#/lesson/07-variables). Inside the f-string, Python evaluates `match_number + 1` first before inserting the result, just like inner-first evaluation in [lesson {n}](#/lesson/01-flowcharts). Conversion goes the other way too: `str(42)` turns a number into the text `"42"`, which is handy whenever you want to join a number onto a string with `+` instead of an f-string. -One more type while we're here: numbers with a decimal point, like a motor voltage of `12.5`, use the type **`float`** (short for *floating-point number*): +One more type while we're here: numbers with a decimal point, like a robot battery voltage of `12.5`, use the type **`float`** (short for *floating-point number*): ```python voltage = 12.5 print(f"Battery: {voltage} volts") ``` -Your turn: start with the text `"9"`, convert it with `int(...)`, and print that number **plus 5**. Then try removing `int(...)` for a moment and running it to see the `TypeError` Python gives when you mix text and numbers. +Your turn: start with a dashboard reading `coral_text = "9"`, convert it with `int(...)`, and print that number **plus 5** more scored in teleop. Then try removing `int(...)` for a moment and running it to see the `TypeError` Python gives when you mix text and numbers. diff --git a/lessons/09-if-statements/README.md b/lessons/09-if-statements/README.md index a10c873..59b5254 100644 --- a/lessons/09-if-statements/README.md +++ b/lessons/09-if-statements/README.md @@ -7,57 +7,57 @@ section: "Python Fundamentals" # The decision diamond, in text -Remember the **decision diamond** from [lesson {n}](#/lesson/02-conditionals)? It asked a true/false question and then took one path or the other, skipping the branch it didn't take. Python writes that same idea with the word **`if`**: +Remember the **decision diamond** from [lesson {n}](#/lesson/02-conditionals)? It asked a true/false question about a robot sensor and then took one path or the other, skipping the branch it didn't take. Python writes that same idea with the word **`if`**: ```python -temperature = 5 -if temperature < 10: - print("Bring a jacket!") -print("Have a good day.") +battery = 9 +if battery < 10: + print("Low battery! Slowing drive.") +print("Status check complete.") ``` Three things to notice: -- **The question** follows `if` and ends with a colon `:`. `temperature < 10` works out to `True` or `False`, just like the question in the diamond. +- **The question** follows `if` and ends with a colon `:`. `battery < 10` works out to `True` or `False`, just like the question in the diamond. - **The indented lines** form the `True` branch. Everything indented under the `if` runs *only* when the question is true. - **The last line** is back at the left edge, outside the `if`, so it runs no matter what. -Indentation replaces the arrows leaving the diamond. Run it, then change `temperature` to `20` and run again. The jacket line vanishes, while the "good day" line always prints. +Indentation replaces the arrows leaving the diamond. Run it, then change `battery` to `12` and run again. The low-battery warning vanishes, while the status check line always prints. # Both paths: else [Lesson {n}'s](#/lesson/02-conditionals) diamond always had *two* arrows, a `true` arrow and a `false` arrow. Python spells the second one **`else:`**: ```python -score = 7 -if score >= 6: - print("You passed!") +coral = 7 +if coral >= 6: + print("Ranking point earned!") else: - print("Not yet, try again.") + print("Need more coral.") ``` Exactly one of those two blocks runs, every time. If the question is true, you get the first; otherwise you get the second. The other is skipped, "the road not taken" from [lesson {n}](#/lesson/02-conditionals), in text form. -One thing to watch closely: `>=` means "greater than or equal to," and the "is it equal?" test is `==` with **two** equals signs. A single `=` means "store a value" ([lesson {n}](#/lesson/07-variables)), so Python uses `==` to *ask* about equality. Mixing them up is the code version of the `>` vs `≥` bug [lesson {n}](#/lesson/02-conditionals) warned about. +One thing to watch closely: `>=` means "greater than or equal to," and the "is it equal?" test is `==` with **two** equals signs. A single `=` means "store a value" ([lesson {n}](#/lesson/07-variables)), so Python uses `==` to *ask* about equality. Mixing them up is the code version of the `<` vs `≤` bug [lesson {n}](#/lesson/02-conditionals) warned about. -Change `score` to `6`, then `5`, and run each time. Convince yourself `>= 6` lets a `6` pass while a `5` doesn't. +Change `coral` to `6`, then `5`, and run each time. Convince yourself `>= 6` earns the ranking point at `6` while `5` does not. # More than two paths: elif -Sometimes there are more than two outcomes. `elif` (short for "else if") lets you ask another question when the previous one was false: +Sometimes a match check has more than two outcomes. `elif` (short for "else if") lets your robot ask another question when the previous one was false: ```python score = 95 if score >= 90: - print("Grade: A") + print("Match tier: Playoff ready") elif score >= 80: - print("Grade: B") + print("Match tier: Strong match") elif score >= 70: - print("Grade: C") + print("Match tier: Solid start") else: - print("Grade: F") + print("Match tier: Check the pit log") ``` -Python checks each question **top to bottom** and takes the **first** one that's true, then skips all the rest. That order matters: a score of `95` is also `>= 80`, but because `>= 90` is checked first and wins, you never reach the B line. This is the same "one step at a time, in order" discipline from [lesson {n}](#/lesson/01-flowcharts). +Python checks each question **top to bottom** and takes the **first** one that's true, then skips all the rest. That order matters: a score of `95` is also `>= 80`, but because `>= 90` is checked first and wins, you never reach the `80` line. This is the same "one step at a time, in order" discipline from [lesson {n}](#/lesson/01-flowcharts). -Run it, then change `score` to `85`, `72`, and `40` and run each time to see a different branch win. Then your challenge: build a program that sets a number in a variable and prints whether it's `"negative"`, `"zero"`, or `"positive"`. That's three paths, so you'll need an `if`, an `elif`, and an `else`. +Run it, then change `score` to `85`, `72`, and `40` and run each time to see a different branch win. Then your challenge: set a motor's `speed` in a variable and print whether the motor is `"reversing"` (negative), `"stopped"` (zero), or `"forward"` (positive). That's three paths, so you'll need an `if`, an `elif`, and an `else`. diff --git a/lessons/10-loops/README.md b/lessons/10-loops/README.md index 6d6a40a..a3f0290 100644 --- a/lessons/10-loops/README.md +++ b/lessons/10-loops/README.md @@ -7,11 +7,11 @@ section: "Python Fundamentals" # Repeat, in text -In [lesson {n}](#/lesson/03-loops) the **repeat** block did a step over and over so you didn't have to copy it out by hand. Python's version is the **`for` loop**, and it comes with a built-in counter. Meet the counter first: +In [lesson {n}](#/lesson/03-loops) the **repeat** block ramped a drive motor without copying boxes by hand. Python's version is the **`for` loop**, and it comes with a built-in counter. Meet the counter first: ```python for i in range(5): - print(f"This is loop number {i}") + print(f"Control loop tick {i}") ``` Read the header in three pieces: @@ -20,40 +20,40 @@ Read the header in three pieces: - **`i`** is the counter variable. On each pass, Python puts the next number from `range(5)` into `i`. - **The colon `:` and indented lines** hold the steps that repeat, just like `if` in [lesson {n}](#/lesson/09-if-statements). -Run it and watch `i` climb: `0`, `1`, `2`, `3`, `4`. That's five passes, and the loop hands you the "which time around am I?" number on every one. Programmers start counting at zero; you'll see why it's handy in [lesson {n}](#/lesson/12-arrays). +Run it and watch `i` climb: `0`, `1`, `2`, `3`, `4`. That's five passes, and the loop hands you the "which tick am I on?" number on every one. Programmers start counting at zero; you'll see why it's handy in [lesson {n}](#/lesson/12-arrays). -Once the counting makes sense, put the loop to work: change `range(5)` to `range(3)`, then `range(10)`, and watch the count follow. Then swap the print line for `print("Go team!")`. Same loop, only now it repeats a message five times. You don't have to *use* `i` for the loop to do its job of repeating. +Once the counting makes sense, put the loop to work: change `range(5)` to `range(3)`, then `range(10)`, and watch the count follow. Then swap the print line for `print("Checking sensors...")`. Same loop, only now it repeats a robot check five times. You don't have to *use* `i` for the loop to do its job of repeating. # A running total -The real power of [lesson {n}'s](#/lesson/03-loops) repeat block was the **running total**, a value it remembered and updated each time around. You build that yourself in a `for` loop by combining it with a variable ([lesson {n}](#/lesson/07-variables)): +The real power of [lesson {n}'s](#/lesson/03-loops) repeat block was the **running total**, a value the robot remembered and updated each time around. Here our robot scores five 3-point game pieces in a row, tracking its score with a `for` loop and a variable ([lesson {n}](#/lesson/07-variables)): ```python total = 0 for i in range(5): total = total + 3 - print(f"So far: {total}") -print(f"Final total: {total}") + print(f"Score so far: {total}") +print(f"Final score: {total}") ``` -Trace it: `total` starts at `0`, and each pass adds `3`, so it climbs `3`, `6`, `9`, `12`, `15`, the exact sequence the "repeat +" block produced. The pattern is *set a starting value before the loop, then update it inside the loop.* Notice `print(f"Final total: {total}")` is not indented, so it runs once after the loop finishes. +Trace it: `total` starts at `0`, and each pass adds `3`, so it climbs `3`, `6`, `9`, `12`, `15`, the exact sequence the "repeat +" block produced. The pattern is *set a starting value before the loop, then update it inside the loop.* Notice `print(f"Final score: {total}")` is not indented, so it runs once after the loop finishes. -Try it yourself: change the starting value, the loop count, or the amount you add. Then make a **multiplying** total. Start at `1` and do `total = total * 2` each pass, and check that you get `2`, `4`, `8`, `16`, `32`, just like the "repeat ×" block. +Try it yourself: change the starting value, the loop count, or the points per piece. Then build a **multiplying** total for a flywheel spin-up. Start at `1` and do `total = total * 2` each pass, and check that you get `2`, `4`, `8`, `16`, `32`, just like the "repeat ×" block. # When you don't know the count: while -A `for` loop repeats a **known** number of times. Sometimes you need to keep going *until something happens*, and you don't know how many steps that will take. That's a **`while` loop**: it repeats as long as a question stays true. +A `for` loop repeats a **known** number of times. Sometimes a robot needs to keep going *until something happens*, and you don't know how many ticks that will take. That's a **`while` loop**: it repeats as long as a question stays true. ```python countdown = 5 while countdown > 0: print(countdown) countdown = countdown - 1 -print("Liftoff!") +print("Autonomous start!") ``` -Each time around, Python re-checks `countdown > 0`. As long as it's true, Python runs the indented steps; the moment it's false, the loop stops and the program moves on. Here we count `5, 4, 3, 2, 1` and then lift off. Notice the loop **changes the thing it's checking** (`countdown` shrinks each pass). That part is essential. +Each time around, Python re-checks `countdown > 0`. As long as it's true, Python runs the indented steps; the moment it's false, the loop stops and the match begins. Here we count `5, 4, 3, 2, 1` and then launch autonomous. Notice the loop **changes the thing it's checking** (`countdown` shrinks each pass). That part is essential. If a `while` loop never changes its condition, it runs **forever**, an "infinite loop," which is the most common beginner bug. Picture deleting `countdown = countdown - 1`: `countdown` would stay `5` and the question would never turn false. -Your turn: write a `while` loop that starts a `total` at `1`, **doubles** it each pass, and keeps going *while* `total < 100`. Print `total` each time. What's the first value it prints that's past 100? +Your turn: write a `while` loop that ramps a flywheel's `power` starting at `1`, **doubles** it each pass, and keeps going *while* `power < 100`. Print `power` each time. What's the first value it prints that's past 100? diff --git a/lessons/11-writing-methods/README.md b/lessons/11-writing-methods/README.md index 004a114..c175652 100644 --- a/lessons/11-writing-methods/README.md +++ b/lessons/11-writing-methods/README.md @@ -7,28 +7,28 @@ section: "Python Fundamentals" # Packaging steps with def -Since [lesson {n}](#/lesson/06-hello-world), every script you wrote ran straight from top to bottom. Now you're ready to build reusable blocks of your own, just like the custom blocks in [lesson {n}](#/lesson/04-functions). In Python, a reusable block of code is called a **function**, and you create one with **`def`**: +Since [lesson {n}](#/lesson/06-hello-world), every script you wrote ran straight from top to bottom. Now your robot is ready to package repeatable routines into reusable blocks, just like the custom blocks in [lesson {n}](#/lesson/04-functions). In Python, a reusable block of code is called a **function**, and you create one with **`def`**: ```python -def say_hello(): - print("Hello from inside a function!") +def check_systems(): + print("Motors and sensors ready!") -say_hello() -say_hello() +check_systems() +check_systems() ``` Two parts to spot: -- **`def say_hello():`** defines a function named `say_hello`. The indented lines underneath are the steps inside it. -- **`say_hello()`** calls the function, telling Python to run those indented steps. +- **`def check_systems():`** defines a function named `check_systems`. The indented lines underneath are the steps inside it. +- **`check_systems()`** calls the function, telling Python to run those indented steps. -Defining a function doesn't run it; it just teaches Python the block exists. It only does its work when you *call* it, and you can call it as many times as you need. Later, in [lesson {n}](#/lesson/17-classes-and-objects), you'll also put functions inside classes, where they're called methods. +Defining a function doesn't run it; it just teaches the robot the routine exists. It only does its work when you *call* it, and you can call it as many times as you need. Later, in [lesson {n}](#/lesson/17-classes-and-objects), you'll also put functions inside classes, where they're called methods. -Run it and notice the message prints twice from one function definition. +Run it and notice the status check prints twice from one function definition. # Define a block of your own -[Lesson {n}](#/lesson/04-functions) gave you a **double** block with a little flowchart hidden inside that you could drop in wherever you needed it. Here is that same block in Python: +[Lesson {n}](#/lesson/04-functions) gave you a **double** block to boost a robot's speed or double a match score. Here is that same block in Python: ```python def double_it(n): @@ -45,34 +45,34 @@ Read the function piece by piece: Run this, then change `5` and run again: same block, different input, just like [lesson {n}](#/lesson/04-functions). -The `n` is called a **parameter**, a placeholder that gets filled in with whatever value you pass when you call the function. A function can take more than one: +The `n` is called a **parameter**, a placeholder that gets filled in with whatever value you pass when you call the function. A function can take more than one, like adding auto points and teleop points together: ```python -def add(a, b): - return a + b +def add(auto_pts, teleop_pts): + return auto_pts + teleop_pts -print(add(2, 3)) +print(add(15, 32)) ``` -Add `add` next to `double_it` in the editor above and call `add(2, 3)` inside `print(...)`. +Add `add` next to `double_it` in the editor above and call `add(15, 32)` inside `print(...)`. # Order matters (again) -[Lesson {n}](#/lesson/04-functions) ended with the big idea that **order matters**: `add 1` then `double` gave a different answer than `double` then `add 1`. Let's prove it in code with two functions of your own: +[Lesson {n}](#/lesson/04-functions) ended with the match scoring pipeline showing that **order matters**: adding the leave bonus then doubling gave a different score than doubling then adding the leave bonus. Let's prove it in code with two functions of your own: ```python -def add_one(n): - return n + 1 +def add_leave_bonus(score): + return score + 1 -def double_it(n): - return n * 2 +def double_it(score): + return score * 2 -print(double_it(add_one(4))) -print(add_one(double_it(4))) +print(double_it(add_leave_bonus(4))) +print(add_leave_bonus(double_it(4))) ``` -Trace the first print line from the inside out: `add_one(4)` is `5`, then `double_it(5)` is `10`. The second line: `double_it(4)` is `8`, then `add_one(8)` is `9`. Same two blocks, same starting number, **different order, different answer**, matching the [lesson-4](#/lesson/04-functions) result. +Trace the first print line from the inside out: `add_leave_bonus(4)` is `5`, then `double_it(5)` is `10`. The second line: `double_it(4)` is `8`, then `add_leave_bonus(8)` is `9`. Same two blocks, same starting score, **different order, different answer**, matching the [lesson {n}](#/lesson/04-functions) result. Run it and confirm you get `10` then `9`. -Your challenge: write a function `square(n)` that returns `n * n`, then use it together with `add_one` to compute **`(4 + 1)` squared**. Predict the answer before you run, and watch your call order, because `square(add_one(4))` and `add_one(square(4))` are *not* the same. +Your challenge: write a function `square(n)` that returns `n * n` (the same math FRC drive code uses to square joystick inputs for smoother control), then combine it with `add_leave_bonus` to compute **`(4 + 1)` squared**. Predict the answer before you run, and watch your call order, because `square(add_leave_bonus(4))` and `add_leave_bonus(square(4))` are *not* the same. diff --git a/lessons/12-arrays/README.md b/lessons/12-arrays/README.md index f54e768..14a19c7 100644 --- a/lessons/12-arrays/README.md +++ b/lessons/12-arrays/README.md @@ -7,10 +7,11 @@ section: "Data Structures" # One name, many values -Every variable so far has held a *single* value: one number, one string. Real -programs deal in **groups**, like the six sensor readings on a robot, the names -of everyone on the drive team, or the points scored in each match. Python holds -a group in a **list**: values inside square brackets, separated by commas. +Every variable your robot has used so far held a *single* value: one score, one +voltage, one name. In a real match, a robot deals in **groups**, like the five +sensor readings on its chassis, the names of everyone on the drive team, or the +points scored in each match. Python holds a group in a **list**: values inside +square brackets, separated by commas. ```python readings = [12, 47, 3, 88, 21] diff --git a/lessons/15-sets/README.md b/lessons/15-sets/README.md index 930aff3..1b2934f 100644 --- a/lessons/15-sets/README.md +++ b/lessons/15-sets/README.md @@ -14,25 +14,27 @@ answer "what is at position `i`?" Dictionaries **set** throws out positions and keys and answers just one question: **"is this value in the group, or not?"** -Python's `set` acts like a collection that refuses duplicates: +Python's `set` acts like a collection that refuses duplicates. Here the robot +tracks which zones of the FRC field it has visited during a match: ```python visited = set() -visited.add("red") -visited.add("blue") -visited.add("red") +visited.add("loading_zone") +visited.add("scoring_zone") +visited.add("loading_zone") print(visited) print(len(visited)) ``` -Run it. Even though `"red"` was added twice, it only appears **once**. The -second `.add("red")` does nothing because `"red"` is already there, and -`len(visited)` prints `2`, not `3`. That is the point of a set: it enforces "no -duplicates" for you so you never have to check yourself before adding. +Run it. Even though `"loading_zone"` was added twice, it only appears **once**. +The second `.add("loading_zone")` does nothing because `"loading_zone"` is +already there, and `len(visited)` prints `2`, not `3`. That is the point of a +set: it enforces "no duplicates" for you so you never have to check yourself +before adding. You can also create a non-empty set with curly braces, like -`visited = {"red", "blue"}`. Notice that `{}` on its own makes an empty -dictionary, so always write `set()` when you want an empty set. +`visited = {"loading_zone", "scoring_zone"}`. Notice that `{}` on its own makes +an empty dictionary, so always write `set()` when you want an empty set. # Checking membership @@ -42,20 +44,20 @@ main reason the type exists, and Python can answer them fast even when the set holds thousands of items: ```python -visited = {"red", "blue"} -print("red" in visited) -print("green" in visited) +visited = {"loading_zone", "scoring_zone"} +print("loading_zone" in visited) +print("climb_zone" in visited) ``` -`True`, then `False`. Think of a set as a robot's memory of places it has -already visited or alliance colors it has faced. You do not care about the -order, and you do not want the same one counted twice. Add with `.add(...)`, -check with `in`, and delete with `.remove(...)`: +`True`, then `False`. Think of a set as a robot's memory of field zones it has +already reached or AprilTags it has spotted. You do not care about the order, +and you do not want the same one counted twice. Add with `.add(...)`, check with +`in`, and delete with `.remove(...)`: ```python -visited = {"red", "blue"} -visited.remove("red") -print("red" in visited) +visited = {"loading_zone", "scoring_zone"} +visited.remove("loading_zone") +print("loading_zone" in visited) ``` If you want to remove an item without risking an error when it is already gone, @@ -66,16 +68,16 @@ use `.discard(...)` instead of `.remove(...)`. A `for` loop walks a set just like a list or dictionary: ```python -alliances = {"red", "blue", "green"} -for alliance in alliances: - print(f"Faced: {alliance}") +zones = {"loading_zone", "scoring_zone", "climb_zone"} +for zone in zones: + print(f"Visited: {zone}") ``` All three lines always appear, but not necessarily in the order you wrote them. Unlike lists and dictionaries ([lesson {n}](#/lesson/14-maps)), a `set` does not preserve insertion order. It organizes values for fast `in` lookups, not for tidy printing. If you need them in alphabetical or numeric order, loop over -`sorted(alliances)` instead. +`sorted(zones)` instead. Your turn: start with this list of scouted robot numbers, `seen = [254, 1114, 254, 118, 1114, 33]`. Loop over `seen` and add each one to diff --git a/lessons/20-state-machines/README.md b/lessons/20-state-machines/README.md index 9c6a99b..d329026 100644 --- a/lessons/20-state-machines/README.md +++ b/lessons/20-state-machines/README.md @@ -15,23 +15,24 @@ then in code. A state machine is simple to say: the machine is **always in exactly one state**, and it **moves to another state when an event happens**. That's it. -Here's the classic example, a traffic light. Each rounded box is a **state**, -and each arrow is a **transition**, labelled with the **event** that triggers it. +Here is an **FRC match mode** cycle. Each rounded box is a **state**, and each +arrow is a **transition**, labelled with the **event** that triggers it. ```blocks preset: sm-demo ``` -The light is glowing on its current state. There's one event here, the timer -finishing, so press **timer done** and watch the machine move: `RED → GREEN → -YELLOW → RED`, forever. Notice what you *can't* do: the light can't be red and -green at once, and it can't jump from red straight to yellow. One state at a -time, and it only moves the way an arrow allows. That restriction is the whole -point. It's what makes the behavior predictable. +The robot is glowing on its current mode. There's one event here, the timer +finishing, so press **timer done** and watch the match move: `DISABLED → AUTO → +TELEOP → DISABLED`, match after match. Notice what the robot *can't* do: it +can't be in `DISABLED` and `TELEOP` at once, and it can't jump straight from +`DISABLED` to `TELEOP` without running `AUTO`. One state at a time, and it only +moves the way an arrow allows. That restriction is the whole point. It's what +makes robot behavior predictable on the field. # Events, and what gets ignored -A traffic light only had one event. A real mechanism has several, and here's the +The match-mode cycle only had one event. A real mechanism has several, and here's the key idea: **a state only reacts to the events it has an arrow for. Everything else, it ignores.** diff --git a/lessons/21-state-machines-in-code/README.md b/lessons/21-state-machines-in-code/README.md index 32e96f6..6e15dcf 100644 --- a/lessons/21-state-machines-in-code/README.md +++ b/lessons/21-state-machines-in-code/README.md @@ -18,30 +18,30 @@ library: ```python from enum import Enum -class LightState(Enum): - RED = "red" - GREEN = "green" - YELLOW = "yellow" +class MatchMode(Enum): + DISABLED = "disabled" + AUTO = "auto" + TELEOP = "teleop" -state = LightState.RED +state = MatchMode.DISABLED match state: - case LightState.RED: - print("STOP") - case LightState.GREEN: - print("GO") - case LightState.YELLOW: - print("SLOW DOWN") + case MatchMode.DISABLED: + print("Motors locked") + case MatchMode.AUTO: + print("Running autonomous") + case MatchMode.TELEOP: + print("Driver control") ``` -That's the traffic light from [lesson {n}](#/lesson/20-state-machines). `LightState` lists the three -legal states, one variable `state` holds which state the machine is in right -now, and `match` picks the behavior for that state (you can also write the same +That's the match-mode cycle from [lesson {n}](#/lesson/20-state-machines). `MatchMode` lists the three +legal modes, one variable `state` holds which mode the robot is in right +now, and `match` picks the behavior for that mode (you can also write the same checks with `if` and `elif` from [lesson {n}](#/lesson/09-if-statements) and `==` from [lesson {n}](#/lesson/16-booleans)). The glowing box in the diagram *is* this variable, nothing more. -Run it, then change `state` to `LightState.GREEN` and run again. Same code, -different state, different behavior. Notice you can only be in one state at a +Run it, then change `state` to `MatchMode.AUTO` and run again. Same code, +different state, different behavior. Notice the robot can only be in one mode at a time, because a variable holds one value, which is the exact rule the diagram enforced. @@ -53,21 +53,21 @@ the variable**. Let's package "what comes next" as a function ([lesson {n}](#/le ```python from enum import Enum -class LightState(Enum): - RED = "red" - GREEN = "green" - YELLOW = "yellow" +class MatchMode(Enum): + DISABLED = "disabled" + AUTO = "auto" + TELEOP = "teleop" def next_state(state): match state: - case LightState.RED: - return LightState.GREEN - case LightState.GREEN: - return LightState.YELLOW - case LightState.YELLOW: - return LightState.RED - -state = LightState.RED + case MatchMode.DISABLED: + return MatchMode.AUTO + case MatchMode.AUTO: + return MatchMode.TELEOP + case MatchMode.TELEOP: + return MatchMode.DISABLED + +state = MatchMode.DISABLED print(state.name) state = next_state(state) print(state.name) @@ -76,8 +76,8 @@ print(state.name) ``` Each `state = next_state(state)` is one press of **timer done** from the -diagram: it looks at where we are and hands back where we go. Run it and watch -`RED → GREEN → YELLOW`. The reassignment trick from [lesson {n}](#/lesson/07-variables) is doing the +diagram: it looks at where the robot is and hands back where it goes. Run it and watch +`DISABLED → AUTO → TELEOP`. The reassignment trick from [lesson {n}](#/lesson/07-variables) is doing the real work. The machine "moves" because we overwrite `state` with its next value. # The loop that drives it @@ -89,34 +89,34 @@ That's a loop ([lesson {n}](#/lesson/10-loops)), and dropping our machine inside ```python from enum import Enum -class LightState(Enum): - RED = "red" - GREEN = "green" - YELLOW = "yellow" +class MatchMode(Enum): + DISABLED = "disabled" + AUTO = "auto" + TELEOP = "teleop" def next_state(state): match state: - case LightState.RED: - return LightState.GREEN - case LightState.GREEN: - return LightState.YELLOW - case LightState.YELLOW: - return LightState.RED - -state = LightState.RED + case MatchMode.DISABLED: + return MatchMode.AUTO + case MatchMode.AUTO: + return MatchMode.TELEOP + case MatchMode.TELEOP: + return MatchMode.DISABLED + +state = MatchMode.DISABLED for tick in range(6): print(tick, state.name) state = next_state(state) ``` -Each time around the loop is one **tick**: print where we are, then advance. -Run it and watch the light cycle `RED → GREEN → YELLOW → RED → GREEN …`, +Each time around the loop is one **tick**: print where the robot is, then advance. +Run it and watch the match cycle `DISABLED → AUTO → TELEOP → DISABLED → AUTO …`, driven entirely by that one repeating step. A real robot's loop is this exact shape, just running 50 times a second instead of 6. -Your turn: add a fourth state, `FLASHING = "flashing"`, that the light enters -after `YELLOW` and leaves back to `RED`. You'll change `next_state` in two -spots: make `case LightState.YELLOW:` return `LightState.FLASHING`, and add a -new `case LightState.FLASHING:` that returns `LightState.RED`. That's the same +Your turn: add a fourth state, `ENDGAME = "endgame"`, that the match enters +after `TELEOP` and leaves back to `DISABLED`. You'll change `next_state` in two +spots: make `case MatchMode.TELEOP:` return `MatchMode.ENDGAME`, and add a +new `case MatchMode.ENDGAME:` that returns `MatchMode.DISABLED`. That's the same as adding a box and rerouting the arrows in the diagram. Run the loop and confirm your new state shows up in the cycle. diff --git a/lessons/22-events-and-transitions/README.md b/lessons/22-events-and-transitions/README.md index cd02d7c..8ca4dae 100644 --- a/lessons/22-events-and-transitions/README.md +++ b/lessons/22-events-and-transitions/README.md @@ -7,7 +7,7 @@ section: "State Machines" # Transitions depend on an event -The traffic light moved on its own. One event, `timer done`, always advanced +The match-mode machine moved on its own. One event, `timer done`, always advanced it. Real mechanisms wait for **specific events**: a button press, a sensor tripping, a shot finishing. So a transition depends on **two things**: which state you're in, *and* which event just happened. diff --git a/lessons/26-decisions-in-code-revisited/README.md b/lessons/26-decisions-in-code-revisited/README.md index b5377d6..840332d 100644 --- a/lessons/26-decisions-in-code-revisited/README.md +++ b/lessons/26-decisions-in-code-revisited/README.md @@ -7,6 +7,10 @@ section: "Advanced Python" # match: one question, many answers +Your robot's mechanisms work in practice now. This section upgrades that code for +competition: cleaner dispatch, smarter enums, hardware interfaces for simulation, +and fluent motor configs. + [Lesson {n}](#/lesson/22-events-and-transitions) dispatched on an event string with `if`/`elif`. That works, but when every branch tests the *same* variable against different exact values, Python 3.10+ has a cleaner shape built for it: **`match`** and **`case`**. ```python diff --git a/lessons/31-lambdas/README.md b/lessons/31-lambdas/README.md index d95a79a..6aef1e2 100644 --- a/lessons/31-lambdas/README.md +++ b/lessons/31-lambdas/README.md @@ -123,4 +123,4 @@ Run it. The first call is ready, so `action()` runs and prints `fire!`. The seco One rule of thumb: reach for `lambda` when the body is a single short expression. The moment it needs two steps, an `if` statement, or a descriptive name, write a regular `def` function and pass its name (without parentheses) as the callback instead. -Your turn: write a function `describe(check: Callable[[], bool]) -> None` that prints `"ready"` or `"not ready"` depending on `check()`. Call it three times with three different lambdas: one always `True`, one always `False`, and one that computes its answer from a comparison you make up (like `7 > 3`). +Your turn: write a function `describe(check: Callable[[], bool]) -> None` that prints `"ready"` or `"not ready"` depending on `check()`. Call it three times with three different lambdas: one always `True`, one always `False`, and one that checks a robot condition you make up (like `12.2 > 11.5` for battery voltage). diff --git a/lessons/35-a-star/README.md b/lessons/35-a-star/README.md index c8cd202..8c3bd45 100644 --- a/lessons/35-a-star/README.md +++ b/lessons/35-a-star/README.md @@ -14,8 +14,8 @@ ends, backs out, hugs walls that lead nowhere, and only reaches the goal because it refuses to give up. It finds *a* path. It does not find the *shortest* one. -For a robot on a field with a shot clock, the difference matters. "Reaches the -goal" and "reaches the goal in the fewest moves" are two different problems, +For a robot on an FRC field with a 15-second autonomous clock, the difference matters. "Reaches the +scoring zone" and "reaches the scoring zone in the fewest moves" are two different problems, and the second one needs a smarter idea. That idea is **A\*** (say "A-star"), one of the most widely used pathfinding diff --git a/lessons/README.md b/lessons/README.md index 98e638b..78e1976 100644 --- a/lessons/README.md +++ b/lessons/README.md @@ -66,7 +66,7 @@ it's the exact content the [training site](../site) renders, page by page. [`site/src/lib/statePresets.ts`](../site/src/lib/statePresets.ts) route to `StatePlayground` (a drivable state diagram with event buttons) rather than the dataflow block editor. They follow the same demo, edit, build arc: - `sm-demo` (traffic light, lesson 20), `sm-edit` (game-piece handler), and + `sm-demo` (match modes, lesson 20), `sm-edit` (game-piece handler), and `sm-build` (wire up a climber yourself). - **` ```maze ` fences render the maze playground.** The fence body names a starter solver (such as `solver: python-wallfollower` or diff --git a/lessons/algorithms/README.md b/lessons/algorithms/README.md index f23a400..d038348 100644 --- a/lessons/algorithms/README.md +++ b/lessons/algorithms/README.md @@ -7,7 +7,10 @@ section: "Algorithms" # A maze is a robot's world -On the right is a maze. It is fun to solve by hand, and for us it is also a tiny, simplified version of the problem every FRC robot faces: **"I'm here, I need to get there, and there are things in my way."** +Your robot now has variables, loops, and mechanisms. Time to put it on a practice +field. On the right is a maze. It is fun to solve by hand, and for us it is also +a tiny, simplified version of the problem every FRC robot faces in autonomous: +**"I'm here, I need to get there, and there are things in my way."** Strip a competition field down to its essentials and you get this: a space divided into a **grid** of cells, some paths open, some blocked by **walls**, a place you **start**, and a place you are trying to **reach**. diff --git a/site/src/components/StatePlayground.tsx b/site/src/components/StatePlayground.tsx index 2d208b3..cdeb309 100644 --- a/site/src/components/StatePlayground.tsx +++ b/site/src/components/StatePlayground.tsx @@ -34,7 +34,7 @@ interface StateData { active: boolean // is this the current state? isStart: boolean editable: boolean // rename via inline input (build mode) - tone?: 'red' | 'green' | 'yellow' // optional fixed color, e.g. the traffic light + tone?: 'red' | 'green' | 'yellow' // optional fixed color, e.g. match mode states [key: string]: unknown } diff --git a/site/src/lib/statePresets.ts b/site/src/lib/statePresets.ts index 0b6f910..b4e355c 100644 --- a/site/src/lib/statePresets.ts +++ b/site/src/lib/statePresets.ts @@ -50,25 +50,25 @@ const trans = (from: string, to: string, on: string, label: string, back = false markerEnd: { type: MarkerType.ArrowClosed }, }) -// ---- Demo: a traffic light (watch it cycle) -------------------------------- +// ---- Demo: FRC match modes (watch it cycle) -------------------------------- // One event drives the whole thing, so the student's only job is to press it and -// watch the current-state token move: red → green → yellow → red. +// watch the current-state token move: disabled -> auto -> teleop -> disabled. const smDemo: StatePreset = { kind: 'state', draggable: false, buildable: false, - start: 'red', + start: 'disabled', events: [{ id: 'timer', label: 'timer done' }], nodes: [ - state('red', 'RED', 60, 0, 'red'), - state('green', 'GREEN', 60, 150, 'green'), - state('yellow', 'YELLOW', 60, 300, 'yellow'), + state('disabled', 'DISABLED', 60, 0, 'red'), + state('auto', 'AUTO', 60, 150, 'yellow'), + state('teleop', 'TELEOP', 60, 300, 'green'), ], edges: [ - trans('red', 'green', 'timer', 'timer done'), - trans('green', 'yellow', 'timer', 'timer done'), - trans('yellow', 'red', 'timer', 'timer done', true), + trans('disabled', 'auto', 'timer', 'timer done'), + trans('auto', 'teleop', 'timer', 'timer done'), + trans('teleop', 'disabled', 'timer', 'timer done', true), ], } diff --git a/site/src/routes/LessonIndex.tsx b/site/src/routes/LessonIndex.tsx index 04b64c9..ff00eef 100644 --- a/site/src/routes/LessonIndex.tsx +++ b/site/src/routes/LessonIndex.tsx @@ -17,8 +17,8 @@ export function LessonIndex() {