1

I am trying to put some python code into a javascript function so that I can call it on a button click. I was just wondering if there was a tag or some built-in way to code python inside a javascript function? I know that I may be able to do this by asking the function to open a file or something like that, but if there is a way to contain this entire solution inside one file that would be great.

This is the code I'm trying to put into the function:

user_input = input("input text here: ")
cipher_key = int(input("input cipher key here: "))
for x in user_input:
    if x == " ":
        print(x)
    else:
        ord_num = ord(x)
        alf_num = ord_num - 97 + cipher_key
        en_num = alf_num % 26 + 97
        print(chr(en_num))
12
  • 4
    onclick can only run client code, Python runs on the server. Commented Nov 30, 2020 at 22:28
  • 1
    There is likely a python-like library for javascript. Basically ported functionality. Commented Nov 30, 2020 at 22:30
  • 1
    What are you trying to do onclick? Most likely, if it's something you can do with Python, you can do it with Javascript as well. Commented Nov 30, 2020 at 22:37
  • 1
    @SeyiDaniel The flask endpoint runs on the server. Commented Nov 30, 2020 at 22:41
  • 1
    No, I just meant you can't run Python (or PHP, or any other server-side language) directly in onclick. You can use AJAX to send a request to the server, and you can implement the server processing in any language you want. Commented Nov 30, 2020 at 22:52

1 Answer 1

2

It depends on your environment ; if you are writing a node js program you can do it as indicated here How to execute an external program from within Node.js? . If you’re writing a client side code (for a web browser) you can’t .

Edit

your code is relatively simple so you can convert your function into js. Assuming that you are writing a Nodejs code:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("input text here: ", function(user_input) {
    rl.question("input cipher key here: ", function(cipher_key) {
        rl.close();
        cipher_key = parseInt(cipher_key)
        for (let i = 0; i < user_input.length(); i++) {
            const x = user_input[i];
            if (x === " ")
                process.stdout.write(x)
            else {
                const ord_num = x.charCodeAt(0)
                const alf_num = ord_num - 97 + cipher_key
                const en_num = alf_num % 26 + 97
                process.stdout.write(String.fromCharCode(en_num))

            }
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.