検索

JavaScript is like Python

この記事では、JavaScript と Python の構文と基本的なプログラミング構造の比較を示します。この 2 つの人気のあるプログラミング言語間での基本的なプログラミング概念の実装方法の類似点を強調することを目的としています。

両方の言語には多くの共通点があり、開発者が言語を切り替えたり、もう一方のコードを理解したりすることが容易になりますが、注意すべき構文上および操作上の明確な違いもあります。

この比較には気楽な視点で取り組み、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 



<p><strong>Python</strong><br>
</p>

<pre class="brush:php;toolbar:false">age = 18

if age 



<h2>
  
  
  条件文
</h2>

<p><strong>JavaScript</strong><br>
</p>

<pre class="brush:php;toolbar:false">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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
リストと配列の選択は、大規模なデータセットを扱うPythonアプリケーションの全体的なパフォーマンスにどのように影響しますか?リストと配列の選択は、大規模なデータセットを扱うPythonアプリケーションの全体的なパフォーマンスにどのように影響しますか?May 03, 2025 am 12:11 AM

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

Pythonのリストと配列にメモリがどのように割り当てられるかを説明します。Pythonのリストと配列にメモリがどのように割り当てられるかを説明します。May 03, 2025 am 12:10 AM

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

Pythonアレイ内の要素のデータ型をどのように指定しますか?Pythonアレイ内の要素のデータ型をどのように指定しますか?May 03, 2025 am 12:06 AM

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

Numpyとは何ですか、そしてなぜPythonの数値コンピューティングにとって重要なのですか?Numpyとは何ですか、そしてなぜPythonの数値コンピューティングにとって重要なのですか?May 03, 2025 am 12:03 AM

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

「隣接するメモリ割り当て」の概念と、配列にとってその重要性について説明します。「隣接するメモリ割り当て」の概念と、配列にとってその重要性について説明します。May 03, 2025 am 12:01 AM

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境