1

How should I go about turning my JavaScript functions into Python functions so as to have my project's code structure as close as possible to what I already have? Would for instance Python functions run embedded in HTML as JavaScript functions do? Of course, I did not try that yet and I am assuming it is not that simple, but I don't understand why. Would it only be because browsers don't have Python available out of the box?

<script type="text/python">
    def myFunction (x):
        if x > 10:
            print("x is larger than 10")
</script>

instead of:

<script type="text/javascript">
    function myFunction () {
        if (x > 10) {
            alert("x is larger than 10");
        }
    }
</script>
Fernando Soares
  • 140
  • 1
  • 12
  • Nope. Python does not run in the browser. The browser implementors would have to include a Python interpreter. You could look for a Python to Javascript transpiler and convert your Python to JS before running it in the browser. – Mike Cluck Aug 24 '16 at 22:29
  • Unless you use a browser with a built-in Python interpreter, it won't work. – Barmar Aug 24 '16 at 22:29

1 Answers1

2

It is not possible to run Python in any modern browser because, while theoretically possible, none contain a python interpreter. Javascript is the only language which runs in a browser without plugins like Flash or ActiveX.

One possibility for being able to write Python code that will eventually run in the browser is to use a "transpiler". This is a tool that will compile the python code into Javascript. So the browser is ultimately running the language it knows, but you're writing Python. There are already a number of languages like CoffeeScript, TypeScript and even React JSX templates that compile down to raw javascript.

An example of a Python to Javascript transpiler is Transcript. Just keep in mind, since it's not actually Python, there are no guarantees for performance or compatibility since that's largely up to how well the transpiler does it's conversion. You may start with a 2 line Python script that compiles into 30 lines of javascript in order to replicate what you're trying to do.

Below is an example of Transcript compilation:

enter image description here

Soviut
  • 88,194
  • 49
  • 192
  • 260