int ledPin = 9; // LED connected to digital pin 9 int analogPin = A0; // potentiometer connected to analog pin A0 int val = 0; // variable to store the read value
void setup() { pinMode(ledPin, OUTPUT); // sets the pin as output }
void loop() { val = analogRead(analogPin); // read the input pin analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255 }
def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: return "Something's wrong with the internet" Note the last block: the “variable name” _ acts as a wildcard and never fails to match. If no case matches, none of the branches is executed.
You can combine several literals in a single pattern using | (“or”):
case 401 | 403 | 404: return "Not allowed"
class Point: x: int y: int
def where_is(point): match point: case Point(x=0, y=0): print("Origin") case Point(x=0, y=y): print(f"Y={y}") case Point(x=x, y=0): print(f"X={x}") case Point(): print("Somewhere else") case _: print("Not a point")
PEP 636 – Structural Pattern Matching: Tutorial Author: Daniel F Moisset <dfmoisset at gmail.com> Sponsor: Guido van Rossum <guido at python.org> BDFL-Delegate: Discussions-To: Python-Dev list Status: Final Type: Informational Created: 12-Sep-2020 Python-Version: 3.10 Post-History: 22-Oct-2020, 08-Feb-2021 Resolution: Python-Committers message
PEP 3103 – A Switch/Case Statement Author:Guido van Rossum <guido at python.org> Status:Rejected Type:Standards Track Created:25-Jun-2006 Python-Version:3.0 Post-History:26-Jun-2006
/* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */ void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag so the main loop can // do something about it: if (inChar == '\n') { stringComplete = true; } } }