azure011328

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
统计
 

今天了解了Python同Java及C++的不同之处

  1. 语法简洁性:

    • Python的语法通常更简洁,不需要像C++和Java那样繁琐的语法结构。

    ```

    Python

    print("Hello, World!")

// Java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

// C++
#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}


2. 静态类型 vs 动态类型:

   * Python是动态类型语言,变量的类型在运行时确定;而C++和Java是静态类型语言,变量的类型在编译时确定。

Python

x = 5 # 整数
x = "Hello" # 字符串

// Java
int x = 5; // 整数
x = "Hello"; // 编译错误,类型不匹配

// C++
int x = 5; // 整数
x = "Hello"; // 编译错误,类型不匹配


3. 内置数据结构和函数:

   * Python提供了许多内置的数据结构和函数,使得编写代码更加简单和高效。

Python

list_example = [1, 2, 3, 4, 5]
sum_of_list = sum(list_example)

// Java
import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) {
List<Integer> listExample = new ArrayList<>();
listExample.add(1);
listExample.add(2);
listExample.add(3);
listExample.add(4);
listExample.add(5);

       int sumOfList = 0;
       for (int num : listExample) {
           sumOfList += num;
       }
   }

}

// C++
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main() {
vector<int> listExample = {1, 2, 3, 4, 5};
int sumOfList = accumulate(listExample.begin(), listExample.end(), 0);
return 0;
}


4. 异常处理:

   * Python的异常处理机制更简单,不需要显式地声明或捕获异常。

Python

try:
result = 10 / 0
except ZeroDivisionError:
print("除零错误!")

// Java
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除零错误!");
}
}
}

// C++
#include <iostream>
using namespace std;

int main() {
try {
int result = 10 / 0;
} catch (const std::exception& e) {
cout << "除零错误!" << endl;
}
return 0;
}
```

posted on   淮竹i  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
 
点击右上角即可分享
微信分享提示