前端工程师的Python教程

代码块

  • javascript
// 使用{}
if (a < 1) {
    console.log(a)
}
  • python
# 使用缩进
if x<1:
    print(x)

数据类型

  • javascript
// 基本(值)类型
// Number(数字)
// BigInt(数字)
// String(字符串)
// Boolen(布尔)
// undefined
// null
// Symbol

// 复合(引用)类型
// Array(列表)
// Object(对象)
// Function(对象)
  • python
# 不可变数据
# Number(数字)(int、float、bool、complex)
# String(字符串)
# Tuple(元组)

# 可变数据
# List(列表)
# Set(集合)
# Dictionary(字典)

# python 中 None 类似js中null
# List 对应javascript中的Array

变(常)量定义

  • javascript
// 需要关键字声明
// 变量命名一般采用lowerCamelCase(驼峰)
var luckNo = 146;
let luckNo = 146;
// 常量建议全大写,单词间采用_分割
const LUCK_NO =146;

// 解构赋值
// =>1 2
const [foo,baz] = [1,2]

// => 1 2 [4,5]
const [foo,baz,...others] = [1,2,4,5]

// => 1 [4,5]
const [foo,,...others] = [1,2,4,5]

// => iron,18
const { name,age } = {name:'iron',age:18}
  • python
# 一般采用snake_case格式命名
# 必须先声明才能使用
luck_no = 146
LUCK_NO =146

# 自动解包
# => 1,2
foo,baz = [1,2]

# => 1 2 [4,5]
foo,baz,*others = [1,2,4,5]

# => 1 [4,5] 
foo, _, *others = [1, 2, 4, 5]

user = {"name": "iron", "age": 18}
# => ('name', 'iron') ('age', 18)
name, age = user.items()  # 类似js中Object.entries

运算符

  • javascript
// 逻辑运算符 &&,||,!
// 比较运算符 ==,===
// 类型运算符 typeof
  • python
# 逻辑运算符 and,or,not
# 比较运算符 ==,===
# 类型运算符 type()函数
# 成员运算符 in,not in
2 in [1,2,3]
# 身份运算符is, not is,判断引用的是否是同一个对象id(a)==id(b)

条件语句

  • javascript
// 基本语法格式
if (baz > 3) {
 // todo
} else if (baz > 2) {
 // todo
} else {
 // todo
}

// 三目表达式
const result = a > 1 ? 1 : 2
  • python
# 基本语法格式
# pass可以用来占位,不影响程序运行
if baz > 3:
    pass
elif baz > 2:
    pass
else:
    pass

# 三目表达式
result = 1 if a > 1 else 2

循环语句

  • javascript
for(let i=0;i<n;i++) {
    # todo
}
  • python
for i in range(n):
    # todo

函数

  • javascript
// 基本函数定义
function foo(p1,[p2,p3,...]) {
    # todo
}
# 箭头函数
const foo = (p1,[p2,p3,...])=> {
    # todo
}
// Array.prototype.map
const result = [1,2,3].map(v=>v+10)
// => [11,12,13]
console.log(result)

// Array.prototype.filter
const result = [1,2,3].filter(v=>v>2)
// => [3]
console.log(result)

// Array.prototype.reduce
const result = [1,2,3].reduce((acc,v)=>{
    return acc+=v
},0)
// => 6
console.log(result)
  • python
// 基本函数定义
def foo(p1,[p2,p3,...]) {
    # todo
}
# Lambda (类似箭头函数)
foo = lambda x: x * x

# map 返回值是Iterator
result = map(lambda x: x + 10, [1, 2, 3])
# => [11,12,13]
print(list(result))

# filter
result = filter(lambda x: x > 2, [1, 2, 3])
# => [3]
print(list(result))

# reduce
from functools import reduce
result = reduce(lambda x,y: x+y,[1,2,3])
# => 6
print(result)

参考