Search code examples
javascriptpythonloopsnested-loopsbreak

Why it works in Javascript but in Python dont?


I made the same code in Python and JavaScript and in JS it works but in python dont

This surprises me because I'm learning javascript, python is the language I believe I know the most and I'm not able to do it

Javascript

var name = "kayque";
var lastname = "othon";

var x = -1;
for(var i=0;i<6;i++){
    process.stdout.write(name[i] + "");
    x++;
    for(x;x<5;){
        process.stdout.write(lastname[x] + "");
        break;
    }
}

Python

name = "kayque"
lastname = "othon"

for letters_name in range(len(name)):
    print(name[letters_name], end="")
    for letters_lastname in range(len(lastname)):
        print(lastname[letters_lastname], end="")
        break
    letters_lastname += 1

I want to solve this problem, I'm learning these languages but I don't understand why in JS it works, but in Python it doesn't...


Solution

  • Your inner loop has a break after the first iteration. That means, that what your code does right now is print o right after each character of your first name ("kayque") which is confirmed because if we run the code the output that we get is ("koaoyoqouoeo"). If you wanna do it in a similar way to javascript here is what gives us the correct answer:

    name = "kayque"
    lastname = "othon"
    
    x = -1
    for i in range(0, 6, 1):
        print(name[i], end="")
        x += 1
        while x < 5:
            print(lastname[x], end="")
            break