Home Backend Development Python Tutorial JavaScript is like Python

JavaScript is like Python

Dec 01, 2024 pm 03:21 PM

JavaScript is like Python

This article presents a comparison between the syntax and fundamental programming constructs of JavaScript and Python. It aims to highlight similarities in how basic programming concepts are implemented across these two popular programming languages.

While both languages share many commonalities, making it easier for developers to switch between them or understand the other's code, there are also distinct syntactical and operational differences that one should be aware of.

It's important to approach this comparison with a light-hearted perspective and not to overemphasize the likeness or differences between JavaScript and Python. The intention is not to declare one language superior to the other but to provide a resource that can help coders who are familiar with Python to understand and transition to JavaScript more easily.

Hello World

JavaScript

// In codeguppy.com environment
println('Hello, World');

// Outside codeguppy.com
console.log('Hello, World');
Copy after login
Copy after login

Python

print('Hello, World')
Copy after login
Copy after login

Variables and Constants

JavaScript

let myVariable = 100;

const MYCONSTANT = 3.14159;
Copy after login

Python

myVariable = 100

MYCONSTANT = 3.14159
Copy after login

String Interpolation

JavaScript

let a = 100;
let b = 200;

println(`Sum of ${a} and ${b} is ${a + b}`);
Copy after login

Python

a = 100
b = 200

print(f'Sum of {a} and {b} is {a + b}')
Copy after login

If Expression / Statement

JavaScript

let age = 18;

if (age < 13) 
{
    println("Child");
} 
else if (age < 20) 
{
    println("Teenager");
} 
else 
{
    println("Adult");
}
Copy after login

Python

age = 18

if age < 13:
    print("Child")
elif age < 20:
    print("Teenager")
else:
    print("Adult")
Copy after login

Conditionals

JavaScript

let age = 20;
let message = age >= 18 ? "Can vote" : "Cannot vote";
println(message);  // Output: Can vote
Copy after login

Python

age = 20
message = "Can vote" if age >= 18 else "Cannot vote"
print(message)  # Output: Can vote
Copy after login

Arrays

JavaScript

// Creating an array
let myArray = [1, 2, 3, 4, 5];

// Accessing elements
println(myArray[0]);  // Access the first element: 1
println(myArray[3]);  // Access the fourth element: 4

// Modifying an element
myArray[2] = 30;  // Change the third element from 3 to 30

// Adding a new element
myArray.push(6);  // Add a new element to the end
Copy after login

Python

# Creating a list to represent an array
my_array = [1, 2, 3, 4, 5]

# Accessing elements
print(my_array[0])  # Access the first element: 1
print(my_array[3])  # Access the fourth element: 4

# Modifying an element
my_array[2] = 30  # Change the third element from 3 to 30

# Adding a new element
my_array.append(6)  # Add a new element to the end
Copy after login

ForEach

JavaScript

let fruits = ["apple", "banana", "cherry", "date"];

for(let fruit of fruits)
    println(fruit);
Copy after login

Python

fruits = ["apple", "banana", "cherry", "date"]

for fruit in fruits:
    print(fruit)
Copy after login

Dictionaries

JavaScript

// Creating a dictionary
fruit_prices = {
    apple: 0.65,
    banana: 0.35,
    cherry: 0.85
};

// Accessing a value by key
println(fruit_prices["apple"]);  // Output: 0.65
Copy after login

Python

# Creating a dictionary
fruit_prices = {
    "apple": 0.65,
    "banana": 0.35,
    "cherry": 0.85
}

# Accessing a value by key
print(fruit_prices["apple"])  # Output: 0.65
Copy after login

Functions

JavaScript

function addNumbers(a, b) 
{
    return a + b;
}

let result = addNumbers(100, 200);
println("The sum is: ", result);
Copy after login

Python

def add_numbers(a, b):
    return a + b

result = add_numbers(100, 200)
print("The sum is: ", result)
Copy after login

Tuple Return

JavaScript

function getCircleProperties(radius) 
{
    const area = Math.PI * radius ** 2;
    const circumference = 2 * Math.PI * radius;

    return [area, circumference];  // Return as an array
}

// Using the function
const [area, circumference] = getCircleProperties(5);

println(`The area of the circle is: ${area}`);
println(`The circumference of the circle is: ${circumference}`);
Copy after login

Python

import math

def getCircleProperties(radius):
    """Calculate and return the area and circumference of a circle."""
    area = math.pi * radius**2
    circumference = 2 * math.pi * radius
    return (area, circumference)

# Using the function
radius = 5
area, circumference = getCircleProperties(radius)

print(f"The area of the circle is: {area}")
print(f"The circumference of the circle is: {circumference}")
Copy after login

Variable number of arguments

JavaScript

function sumNumbers(...args) 
{
    let sum = 0;
    for(let i of args)
        sum += i;
    return sum;
}

println(sumNumbers(1, 2, 3));
println(sumNumbers(100, 200));
Copy after login

Python

def sum_numbers(*args):
    sum = 0
    for i in args:
        sum += i
    return sum

print(sum_numbers(1, 2, 3))
print(sum_numbers(100, 200))
Copy after login

Lambdas

JavaScript

const numbers = [1, 2, 3, 4, 5];

// Use map to apply a function to all elements of the array
const squaredNumbers = numbers.map(x => x ** 2);

println(squaredNumbers);  // Output: [1, 4, 9, 16, 25]
Copy after login

Python

numbers = [1, 2, 3, 4, 5]

# Use map to apply a function to all elements of the list
squared_numbers = map(lambda x: x**2, numbers)

# Convert map object to a list to print the results
squared_numbers_list = list(squared_numbers)

print(squared_numbers_list)  # Output: [1, 4, 9, 16, 25]
Copy after login

Classes

JavaScript

class Book 
{
    constructor(title, author, pages) 
    {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    describeBook() 
    {
        println(`Book Title: ${this.title}`);
        println(`Author: ${this.author}`);
        println(`Number of Pages: ${this.pages}`);
    }
}
Copy after login

Python

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def describe_book(self):
        print(f"Book Title: {self.title}")
        print(f"Author: {self.author}")
        print(f"Number of Pages: {self.pages}")
Copy after login

Usage of classes

JavaScript

// In codeguppy.com environment
println('Hello, World');

// Outside codeguppy.com
console.log('Hello, World');
Copy after login
Copy after login

Python

print('Hello, World')
Copy after login
Copy after login

Conclusion

We encourage you to get involved in refining this comparison. Your contributions, whether they are corrections, enhancements, or new additions, are highly valued. By collaborating, we can create a more accurate and comprehensive guide that benefits all developers interested in learning about JavaScript and Python.


Credits

This article was republished from the blog of the free coding platform https://codeguppy.com platform.

The article was influenced by similar comparisons between other programming languages:

  • Kotlin is like C# https://ttu.github.io/kotlin-is-like-csharp/
  • Kotlin is like TypeScript https://gi-no.github.io/kotlin-is-like-typescript/
  • Swift is like Kotlin https://nilhcem.com/swift-is-like-kotlin/
  • Swift is like Go http://repo.tiye.me/jiyinyiyong/swift-is-like-go/
  • Swift is like Scala https://leverich.github.io/swiftislikescala/

The above is the detailed content of JavaScript is like Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles