首页 > 后端开发 > Python教程 > JavaScript 就像 Python

JavaScript 就像 Python

Mary-Kate Olsen
发布: 2024-12-01 15:21:11
原创
482 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板