IndentationError: unexpected indent with Python block in R Markdown

Consider the following minimal working example:

---
title: "MWE"
author: "Raniere Silva"
date: "13/12/2021"
output: html_document
---

```{python}
def mwe(a, b):
    if a > b:
        out = 'foo'
    elif a < b:
        out = 'bar'
    else:
        out = 'none
    return out
   
mwe(1, 2)
```

When I click in the "Run Current Chunk" in RStudio 1.4.1106, I get the following in the console:

> reticulate::repl_python()
Python 3.9.7 (/home/raniere/anaconda3/envs/faxitron/bin/python)
Reticulate 1.22 REPL -- A Python interpreter in R.
Enter 'exit' or 'quit' to exit the REPL and return to R.
>>> def mwe(a, b):
...     if a > b:
...         out = 'foo'
...     elif a < b:
...         out = 'bar'
...     else:
...         out = 'none
IndentationError: expected an indented block (<string>, line 6)
IndentationError: unexpected indent (<string>, line 1)
>>>     return out
SyntaxError: 'return' outside function (<string>, line 1)
>>>    
>>> mwe(1, 2)
NameError: name 'mwe' is not defined
>>> 

Any recommendation on how to solve this issue?

White space is syntactic in Python and spaces and tabs are distinct. Use all one or the other.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.