Make a beat with a Python loop

Repeat a pattern of hits and rests and listen to the result.

Try the project

One bar

Hit · rest · hit · hit

How long should the beat run?

Change the number of bars. The same four steps repeat in order.

8 steps · 6 hits · 2 bars

How a loop builds a beat

Start with a pattern[1, 0, 1, 1]
Repeat itfor bar in range(2):
Two bars[1, 0, 1, 1] [1, 0, 1, 1]

Store one bar.

Each position lasts a quarter of a second. A 1 plays a hit. A 0 waits for the same amount of time, creating a rest.

Repeat the ordered list.

range(2) gives the loop two turns. The inner loop walks through the four steps during each turn.

Predict the output.

Three bars make 12 steps. There are three hits in each bar, so you will hear nine. Switch back to one bar and listen for the rest.

Run the Python version

The printed sequence tells the audio code when to play a hit and when to leave silence.

pattern = [1, 0, 1, 1]
sequence = []
for bar in range(2):
    for hit in pattern:
        sequence.append(hit)
print(sequence)
python3 python-beat.py --bars 3
Download the Python script ↓

Sources

Make something else in Python