首頁 >後端開發 >Python教學 >JavaScript 就像 Python

JavaScript 就像 Python

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-12-01 15:21:11416瀏覽

JavaScript is like Python

本文對 JavaScript 和 Python 的語法和基本程式結構進行了比較。它旨在強調這兩種流行的程式語言在實現基本程式設計概念方面的相似之處。

雖然這兩種語言有許多共同點,使開發人員更容易在它們之間切換或理解對方的程式碼,但也應該注意明顯的語法和操作差異。

重要的是要以輕鬆的角度進行這種比較,而不是過度強調 JavaScript 和 Python 之間的相似或差異。目的不是要聲明一種語言優於另一種語言,而是提供一種資源,可以幫助熟悉 Python 的程式設計師更輕鬆地理解並過渡到 JavaScript。

你好世界

JavaScript

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

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

Python

print('Hello, World')

變數和常數

JavaScript

let myVariable = 100;

const MYCONSTANT = 3.14159;

Python

myVariable = 100

MYCONSTANT = 3.14159

字串插值

JavaScript

let a = 100;
let b = 200;

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

Python

a = 100
b = 200

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

If 表達式/語句

JavaScript

let age = 18;

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

Python

age = 18

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

條件句

JavaScript

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

Python

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

陣列

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

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

對於每個

JavaScript

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

for(let fruit of fruits)
    println(fruit);

Python

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

for fruit in fruits:
    print(fruit)

字典

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

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

功能

JavaScript

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

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

Python

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

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

元組返回

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}`);

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}")

可變數量的參數

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));

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))

拉姆達斯

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]

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]

課程

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}`);
    }
}

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}")

類別的使用

JavaScript

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

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

Python

print('Hello, World')

結論

我們鼓勵您參與完善此比較。您的貢獻,無論是更正、增強或新增內容,都受到高度重視。透過合作,我們可以創建更準確、更全面的指南,讓所有有興趣學習 JavaScript 和 Python 的開發人員受益。


製作人員

本文轉載自免費編碼平台https://codeguppy.com平台的部落格。

本文受到其他程式語言之間類似比較的影響:

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

以上是JavaScript 就像 Python的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn