How to write code samples in Markdown

blog.md

A Quick Guide for Writing Code Samples in Markdown

Patrick Rachford
2 min readAug 10, 2022
Photo by Yancy Min on Unsplash

The intention of writing documentation in Markdown is that it is easy to learn, easy to write, and easy to read. Which means that is easy to review and get contribution from a wide variety of people.

The purpose of Markdown’s syntax is to be used as a format for writing web based content. Although there are many flavors of Markdown, for the purposes of this tutorial we will be using GitHub’s syntax of Markdown. Whichever flavor of Markdown you choose, remember that Markdown is rendered into HTML which means you can still achieve the same results, you just need to write a little HTML. Writing inline code and code blocks in Markdown is great for technical blogs, tutorials, and other technical concepts.

In this tutorial, I will demonstrate how to use Markdown syntax for writing code samples.

Inline Code

For code that will be formatted inline, wrap it in back ticks.

Example:

To print “Hello World” type: `print('Hello, world!')` and click OK.

Code Block

A Code Block or Code Fence is used for longer blocks of code. Using a code block allows the code to keep the indention attached. To create a Code Block use four back ticks before and after the code.

Example:

````a = 49b = 49if b > a:    print(“b is greater than a”)elif a == b:    print(“a and b are equal”)````

Extended Syntax

Extended Syntax or info string can be used after the opening of the code block’s back ticks. The first word following the back ticks will specify the code language used in the block.

Example:

````pythona = 49b = 49if b > a:    print(“b is greater than a”)elif a == b:    print(“a and b are equal”)````

Note: To format code in Medium:

  1. Select the text
  • Windows: Control + Alt + 6
  • Mac: Command + Option + 6
  • Linux: Control + Alt + 6

Now you can use inline code, code blocks, or Extended Syntax in Markdown to emphasize code.

--

--

No responses yet