Displaying Python Code in Markdown Text Cells¶
Sometimes it is useful to show Python code in a notebook without it being executable, in a Code cell; for example if it is only a fragment, or it is not working yet and you want to discuss it.
There are several ways to do this, which I will illustrate first with small pieces of code and then for an entire cell.
One method is surrounding Python code with single backward quotes;
for example if a==0:
is displayed diffeerntl than if a==0:
This becomes more obvious when there are multiple lines of code:
if a==0: print("Warning: a=0 will lead to a division by zero error!")
That respects line breaks and indentation, whereas
if a==0: print(“Warning: a=0 will lead to a division by zero error!”)
does not.
Note also that the code chunk is separated by blank lines before and after.
A second method is indenting:
if a==0:
print("Warning: a=0 will lead to a division by zero error!")
These methods can also work for entire code cells, but then there is also another option: using “Raw” cells. I illustrate each with the code cell:
if a==0:
print("Warning: a=0 will lead to a division by zero error!")
else:
print("This is a genuine quadratic; let's compute its real roots, if any ...")
Method 1: backquotes in a Markdown cell:¶
if a==0: print("Warning: a=0 will lead to a division by zero error!") else: print("This is a genuine quadratic; let's compute its real roots, if any ...")
Method 2: indentation in a Markdown cell:¶
if a==0:
print("Warning: a=0 will lead to a division by zero error!")
else:
print("This is a genuine quadratic; let's compute its real roots, if any ...")