当前位置: 首页 > news >正文

Triton前置——Python基础语法

代码块:缩进 vs 大括号

Python:缩进决定层级(:+ 缩进)

def hello(): print("你好") # 缩进4空格,属于函数 print("世界") # 缩进4空格,属于函数 if x > 0: print("正数") # 缩进4空格,属于if print("哈哈") # 缩进4空格,属于if print("结束") # 不缩进,不属于if

C++:大括号决定层级

void hello() { cout << "你好"; // 在大括号内,属于函数 cout << "世界"; // 在大括号内,属于函数 } if (x > 0) { cout << "正数"; // 在大括号内,属于if cout << "哈哈"; // 在大括号内,属于if } cout << "结束"; // 在大括号外,不属于if

语句结束:换行 vs 分号

Python:换行即可

x = 5 y = 10 z = x + y print(z)

C++:必须加分号

int x = 5; // 必须有分号 int y = 10; // 必须有分号 int z = x + y; // 必须有分号 cout << z; // 必须有分号

变量类型:动态 vs 静态

Python:不需要声明类型

x = 5 # 自动推断为int x = "hello" # 可以随意改变类型 x = 3.14 # 再次改变类型 def add(a, b): # 不需要指定a,b的类型 return a + b add(3, 5) # 可以传整数 add("hi", "!") # 也可以传字符串

C++:必须声明类型

int x = 5; // 声明为int x = 10; // 可以,还是int x = "hello"; // ❌ 错误!不能改变类型 int add(int a, int b) { // 必须指定类型 return a + b; } add(3, 5); // ✅ 可以 add("hi", "!"); // ❌ 错误!类型不匹配

函数定义:def vs 类型

Python

def add(a, b): return a + b def greet(name="世界"): # 默认参数 print(f"你好, {name}") def multiple_return(): # 返回多个值 return 1, 2, 3

C++

int add(int a, int b) { // 必须指定返回类型和参数类型 return a + b; } void greet(string name = "世界") { // 默认参数 cout << "你好, " << name; } tuple<int, int, int> multiple_return() { // 返回多个值需要tuple return {1, 2, 3}; }

循环语法

Python

# for循环 for i in range(10): # 0-9 print(i) for item in [1, 2, 3, 4]: # 遍历列表 print(item) # while循环 i = 0 while i < 10: print(i) i += 1

C++

// for循环 for (int i = 0; i < 10; i++) { // 初始化;条件;更新 cout << i; } for (int item : {1, 2, 3, 4}) { // C++11 范围for cout << item; } // while循环 int i = 0; while (i < 10) { cout << i; i++; }

条件语句

Python

if x > 0: print("正数") elif x == 0: print("零") else: print("负数") # 简洁写法 result = "正数" if x > 0 else "负数"

C++

if (x > 0) { cout << "正数"; } else if (x == 0) { cout << "零"; } else { cout << "负数"; } // 三元运算符 string result = (x > 0) ? "正数" : "负数";

数组/列表

Python

# 列表(动态数组,可增长) list1 = [1, 2, 3] list1.append(4) # 添加元素 list1.pop() # 删除元素 list1[0] # 访问 # 列表推导式 squares = [x*x for x in range(10)] # 元组(不可变) tuple1 = (1, 2, 3) # 字典 dict1 = {"name": "小明", "age": 18}

C++

// 数组(固定大小) int arr[3] = {1, 2, 3}; arr[0] = 10; // vector(动态数组) vector<int> vec = {1, 2, 3}; vec.push_back(4); // 添加 vec.pop_back(); // 删除 vec[0]; // 访问 // map(字典) map<string, int> dict; dict["name"] = "小明"; dict["age"] = 18;

字符串操作

Python

name = "小明" greeting = f"你好, {name}" # f-string(简单!) greeting = "你好, " + name # 拼接 # 切片 s = "hello" s[1:3] # "el" s[::-1] # "olleh"(反转)

C++

string name = "小明"; string greeting = "你好, " + name; // 拼接 // C++11 需要额外库 string greeting = "你好, " + name; // 切片(需要substr) string s = "hello"; s.substr(1, 2); // "el" reverse(s.begin(), s.end()); // "olleh"

内存管理

Python:自动垃圾回收

def create_list(): return [1, 2, 3, 4, 5] # 自动管理内存 # 不需要担心内存泄漏 x = [1, 2, 3] x = None # 旧列表自动被回收

C++:手动管理(或智能指针)

int* create_array() { int* arr = new int[5]; // 手动分配 return arr; } int main() { int* arr = create_array(); // 必须手动释放! delete[] arr; } // 智能指针(现代C++) unique_ptr<int[]> arr = make_unique<int[]>(5); // 自动释放

类(面向对象)

Python

class Person: def __init__(self, name, age): # 构造函数 self.name = name self.age = age def say_hello(self): print(f"你好, 我是{self.name}") @classmethod def create_child(cls, name): return cls(name, 0) # 继承 class Student(Person): def __init__(self, name, age, grade): super().__init__(name, age) self.grade = grade

C++

class Person { public: string name; int age; // 构造函数 Person(string n, int a) : name(n), age(a) {} void say_hello() { cout << "你好, 我是" << name; } // 静态方法 static Person create_child(string name) { return Person(name, 0); } }; // 继承 class Student : public Person { public: int grade; Student(string n, int a, int g) : Person(n, a), grade(g) {} };

异常处理

Python

try: x = 10 / 0 except ZeroDivisionError: print("除以零了!") except Exception as e: print(f"其他错误: {e}") else: print("没有错误") finally: print("总是执行")

C++

try { int x = 10 / 0; } catch (const runtime_error& e) { cout << "错误: " << e.what(); } catch (...) { cout << "其他错误"; } // 没有else和finally

常用操作对比

操作PythonC++
打印print("hello")cout << "hello"
输入input()cin >> x
注释# 注释// 注释
多行注释""" 注释 """/* 注释 */
逻辑与and&&
逻辑或or||
逻辑非not!
比较==, !=, <, >==, !=, <, >
自增x += 1x++x += 1
http://www.cnnetsun.cn/news/4157443.html

相关文章:

  • HumanInput源码剖析:8KB事件库如何解析复杂的组合事件字符串,EventHandler设计全解读
  • NAND闪存工作原理——SSD数据是如何存储的?
  • SDRangel SDR信号接收与频谱分析快速上手
  • 一台电脑两台手柄?任意 PC 游戏双人分屏的完整指南
  • 跑通多模态情感分析:Multimodal-Sentiment-Analysis 图文融合实战指南
  • MonitorControl|macOS外接显示器亮度音量一键调:多屏办公党的屏幕控制方案
  • 论文AI率0%黑科技!降AIGC网站留学生亲测::Turnitin查重秒变“教授最爱”原创风
  • 题解:洛谷 P3184 [USACO16DEC] Counting Haybales S
  • 文档加载工程:从多格式数据到标准化Document对象的实战指南
  • 5 步装好 Windows 微信防撤回补丁:RevokeMsgPatcher 新手完整教程
  • Unlock-Music 音乐解密完整指南:在浏览器里批量解密 qmc、ncm 等加密音乐文件
  • AnythingLLM 本地部署完全指南:私有知识库文档问答
  • Linux入门攻坚——86、ELK Stack-1-基本概念
  • SpringBoot+微信小程序旅游平台:从零到部署的毕设实战指南
  • U盘重装Windows系统全攻略:从启动盘制作到安装设置详解
  • DatalinkX 快速上手指南:从零到跑通第一个数据同步任务
  • 3分钟把整本网页小说存成EPUB:WebToEpub离线阅读工具上手笔记
  • LinkSwift 网盘直链解析工具:实用新手指南
  • 万店连锁智能运维实践:从告警驱动到一键根因定位的STAROps体系
  • slack-irc 消息格式转换艺术:Slack到IRC文本解析与表情映射完整剖析
  • MobilityDB查询完全手册:时空重叠、距离计算与轨迹插值SQL函数大全
  • PhpStorm‑2026.2 完整下载‑安装‑环境配置全套教程(Windows 完整版,适配 PHP8.5、WampServer)
  • React Native和Flutter如何接入Mobile App Automizer?跨平台项目发布自动化实战指南
  • Chrome插件如何实现网页搜索替换:chrome-extensions-searchReplace让整页文字批量更新不伤按钮
  • ISP Tuning 使用
  • NAudio实战上手:5分钟搭出能用的音频播放器
  • TPU与Mooncake集成:如何实现AI推理服务的极致性能与确定性
  • NumPy eigh函数详解:对称矩阵特征值计算的高效工具
  • 基于主体建模(ABM)模拟农业技术采纳:以低排放肥料推广为例
  • 为什么你的 Free Domains 免费子域名申请被拒?10个高频踩坑问题一次说透