Switch in R Programming Language

Switch statements express conditionals across many branches.

Here’s a basic `switch`.

```python
i = 2
print(f"Write {i} as ", end="")

if i == 1:
    print("one")
elif i == 2:
    print("two")
elif i == 3:
    print("three")

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

import datetime

weekday = datetime.datetime.now().weekday()
if weekday in (5, 6):
    print("It's the weekend")
else:
    print("It's a weekday")

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

t = datetime.datetime.now()
hour = t.hour
if hour < 12:
    print("It's before noon")
else:
    print("It's after noon")

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause.

def whatAmI(i):
    if isinstance(i, bool):
        print("I'm a bool")
    elif isinstance(i, int):
        print("I'm an int")
    else:
        print(f"Don't know type {type(i).__name__}")

whatAmI(True)
whatAmI(1)
whatAmI("hey")
$ python switch.py
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type str

Next example: Arrays.