🐍 前端开发 0 基础学 Python 入门指南:条件语句篇

🐍 前端开发 0 基础学 Python 入门指南:条件语句篇

从 JavaScript 到 Python,深入理解 if/else 条件判断的差异!

📝 一、Python 中的 if 语句基础

1.1 基本语法对比

Python 和 JavaScript 的 if 语句语法有明显差异:

python 复制代码
# Python - 使用冒号和缩进
age = 18
if age >= 18:
    print("你已经成年了")
else:
    print("你还未成年")
javascript 复制代码
// JavaScript - 使用花括号
let age = 18
if (age >= 18) {
  console.log('你已经成年了')
} else {
  console.log('你还未成年')
}

1.2 关键语法差异

特性 Python JavaScript 说明
条件后符号 冒号 : 无(直接用 {} Python 必须要冒号
代码块 缩进 花括号 {} Python 用缩进表示层级
条件括号 不需要括号 需要括号 () Python 更简洁
缩进规范 强制(通常 4 空格) 可选(仅为美观) Python 缩进错误会报错!
elif elif else if Python 更简短

⚠️ 重要提示:Python 的缩进不是装饰,而是语法的一部分!

python 复制代码
# ✅ 正确 - 使用4个空格缩进
if age >= 18:
    print("成年人")

# ❌ 错误 - 缩进不一致会报错
if age >= 18:
    print("成年人")
  print("可以投票")  # IndentationError!

🔄 二、if-elif-else 多重条件

2.1 成绩评级示例

python 复制代码
# Python
score = 85

if score >= 90:
    print("优秀")
elif score >= 75:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")
# 输出: 良好
javascript 复制代码
// JavaScript
let score = 85

if (score >= 90) {
  console.log('优秀')
} else if (score >= 75) {
  console.log('良好')
} else if (score >= 60) {
  console.log('及格')
} else {
  console.log('不及格')
}
// 输出: 良好

2.2 执行流程

ini 复制代码
score = 85
    ↓
score >= 90?  → ❌ 否
    ↓
score >= 75?  → ✅ 是 → 打印"良好" → 结束
    ↓
(不再检查后续条件)

关键点: 找到第一个满足的条件后,立即执行并结束,不会检查后续条件!


🎯 三、多重条件判断

3.1 逻辑运算符

Python 和 JavaScript 的逻辑运算符有所不同:

逻辑 Python JavaScript 说明
and && 都为真
or `
not ! 取反

3.2 判断正负奇偶

python 复制代码
# Python
num = 15

if num > 0 and num % 2 == 0:
    print("正偶数")
elif num > 0 and num % 2 != 0:
    print("正奇数")
elif num < 0 and num % 2 == 0:
    print("负偶数")
elif num < 0 and num % 2 != 0:
    print("负奇数")
else:
    print("零")
# 输出: 正奇数
javascript 复制代码
// JavaScript
let num = 15

if (num > 0 && num % 2 === 0) {
  console.log('正偶数')
} else if (num > 0 && num % 2 !== 0) {
  console.log('正奇数')
} else if (num < 0 && num % 2 === 0) {
  console.log('负偶数')
} else if (num < 0 && num % 2 !== 0) {
  console.log('负奇数')
} else {
  console.log('零')
}
// 输出: 正奇数

3.3 逻辑运算符优先级

python 复制代码
# and 优先级高于 or
result = True or False and False
print(result)  # True
# 等价于: True or (False and False)

# 使用括号明确优先级(推荐✅)
result = (True or False) and False
print(result)  # False

🔀 四、嵌套 if 语句

4.1 闰年判断

python 复制代码
# Python
year = 2024

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} 是闰年")
else:
    print(f"{year} 不是闰年")
# 输出: 2024 是闰年

闰年规则:

  1. 能被 4 整除 不能被 100 整除
  2. 或者 能被 400 整除
python 复制代码
# 嵌套写法(更清晰)
year = 2024

if year % 400 == 0:
    print(f"{year} 是闰年")
elif year % 100 == 0:
    print(f"{year} 不是闰年")
elif year % 4 == 0:
    print(f"{year} 是闰年")
else:
    print(f"{year} 不是闰年")

4.2 嵌套层级对比

python 复制代码
# Python - 用缩进表示层级
age = 20
has_license = True

if age >= 18:
    if has_license:
        print("可以开车")
    else:
        print("需要考驾照")
else:
    print("未成年,不能开车")
javascript 复制代码
// JavaScript - 用花括号表示层级
let age = 20
let hasLicense = true

if (age >= 18) {
  if (hasLicense) {
    console.log('可以开车')
  } else {
    console.log('需要考驾照')
  }
} else {
  console.log('未成年,不能开车')
}

⚠️ 避免过深嵌套: 嵌套超过 3 层会降低代码可读性,建议重构!


📊 五、if 语句与数据结构

5.1 列表过滤 - 筛选偶数

python 复制代码
# Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print("偶数列表:", even_numbers)
# 输出: 偶数列表: [2, 4, 6, 8, 10]
javascript 复制代码
// JavaScript
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let evenNumbers = []

for (let num of numbers) {
  if (num % 2 === 0) {
    evenNumbers.push(num)
  }
}

console.log('偶数列表:', evenNumbers)
// 输出: 偶数列表: [2, 4, 6, 8, 10]

5.2 列表推导式(Python 独有 ✨)

Python 提供了更简洁的语法:

python 复制代码
# 方式1: 传统 for + if
even_numbers = []
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

# 方式2: 列表推导式(推荐✅)
even_numbers = [num for num in numbers if num % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8, 10]

# 更多示例
squares = [x**2 for x in range(1, 6)]  # [1, 4, 9, 16, 25]
positive = [x for x in [-2, -1, 0, 1, 2] if x > 0]  # [1, 2]

JavaScript 需要使用 filter 方法:

javascript 复制代码
// JavaScript
let evenNumbers = numbers.filter((num) => num % 2 === 0)
console.log(evenNumbers) // [2, 4, 6, 8, 10]

5.3 字典过滤 - 筛选及格学生

python 复制代码
# Python
students = {'Alice': 85, 'Bob': 92, 'Charlie': 78, 'David': 90}
passed_students = {}

for name, score in students.items():
    if score >= 80:
        passed_students[name] = score

print("及格学生:", passed_students)
# 输出: 及格学生: {'Alice': 85, 'Bob': 92, 'David': 90}

使用字典推导式(更简洁 ✨):

python 复制代码
# 字典推导式
passed_students = {name: score for name, score in students.items() if score >= 80}
print(passed_students)
# 输出: {'Alice': 85, 'Bob': 92, 'David': 90}

JavaScript 对比:

javascript 复制代码
// JavaScript
let students = { Alice: 85, Bob: 92, Charlie: 78, David: 90 }
let passedStudents = {}

for (let [name, score] of Object.entries(students)) {
  if (score >= 80) {
    passedStudents[name] = score
  }
}

console.log('及格学生:', passedStudents)

// 或使用 reduce
let passedStudents = Object.entries(students).reduce((acc, [name, score]) => {
  if (score >= 80) acc[name] = score
  return acc
}, {})

🎨 六、真值判断(Truthy/Falsy)

6.1 Python 的假值

Python 中以下值被视为 False

python 复制代码
# 布尔值
bool_val = False

# 数字零
zero_int = 0
zero_float = 0.0
zero_complex = 0j

# 空序列
empty_str = ""
empty_list = []
empty_tuple = ()

# 空映射
empty_dict = {}
empty_set = set()

# None
none_val = None

# 测试
if not empty_list:
    print("空列表为假")  # ✅ 会执行

6.2 真值判断示例

python 复制代码
# 判断字符串是否为空
name = ""
if name:
    print(f"你好, {name}")
else:
    print("名字不能为空")  # ✅ 会执行

# 判断列表是否有元素
items = []
if items:
    print(f"有 {len(items)} 个商品")
else:
    print("购物车是空的")  # ✅ 会执行

# 判断字典是否有数据
user = {}
if user:
    print(f"用户: {user['name']}")
else:
    print("未登录")  # ✅ 会执行

6.3 Python vs JavaScript 假值对比

假值类型 Python JavaScript 说明
布尔 False false 相同
数字零 0, 0.0 0, -0, 0n 相同
空字符串 "" "" 相同
空值 None null, undefined Python 只有 None
空数组 [] [] 是真值! 不同
空对象 {} {} 是真值! 不同
NaN ❌ 无 NaN JS 独有

关键区别:

python 复制代码
# Python - 空列表/字典为假
if []:
    print("不会执行")
javascript 复制代码
// JavaScript - 空数组/对象为真!⚠️
if ([]) {
  console.log('会执行!') // ✅
}

if ({}) {
  console.log('会执行!') // ✅
}

// JS 需要显式判断
if (arr.length > 0) {
  console.log('数组有元素')
}

🔍 七、三元运算符(条件表达式)

7.1 基本语法

python 复制代码
# Python - 条件表达式
age = 20
status = "成年" if age >= 18 else "未成年"
print(status)  # "成年"

# 等价于
if age >= 18:
    status = "成年"
else:
    status = "未成年"
javascript 复制代码
// JavaScript - 三元运算符
let age = 20
let status = age >= 18 ? '成年' : '未成年'
console.log(status) // "成年"

7.2 语法对比

特性 Python JavaScript
语法 值1 if 条件 else 值2 条件 ? 值1 : 值2
顺序 条件在中间 条件在前面
可读性 更接近自然语言 符号化

7.3 嵌套三元运算符

python 复制代码
# Python
score = 85
grade = "优秀" if score >= 90 else "良好" if score >= 75 else "及格" if score >= 60 else "不及格"
print(grade)  # "良好"

# ⚠️ 建议:嵌套过多时使用 if-elif-else 更清晰
if score >= 90:
    grade = "优秀"
elif score >= 75:
    grade = "良好"
elif score >= 60:
    grade = "及格"
else:
    grade = "不及格"
javascript 复制代码
// JavaScript
let score = 85
let grade =
  score >= 90 ? '优秀' : score >= 75 ? '良好' : score >= 60 ? '及格' : '不及格'
console.log(grade) // "良好"

🚀 八、高级技巧

8.1 in 运算符判断

python 复制代码
# 判断元素是否在序列中
fruit = "apple"
if fruit in ["apple", "banana", "orange"]:
    print("这是水果")  # ✅ 会执行

# 判断键是否在字典中
user = {"name": "张三", "age": 25}
if "name" in user:
    print(f"用户名: {user['name']}")  # ✅ 会执行

# 判断子串是否在字符串中
text = "Hello World"
if "World" in text:
    print("包含 World")  # ✅ 会执行

JavaScript 对比:

javascript 复制代码
// JavaScript
let fruit = 'apple'
if (['apple', 'banana', 'orange'].includes(fruit)) {
  console.log('这是水果')
}

let user = { name: '张三', age: 25 }
if ('name' in user) {
  console.log(`用户名: ${user.name}`)
}

let text = 'Hello World'
if (text.includes('World')) {
  console.log('包含 World')
}

8.2 match 语句(Python 3.10+)

Python 3.10 引入了类似 switch 的语法:

python 复制代码
# Python 3.10+
status_code = 404

match status_code:
    case 200:
        print("请求成功")
    case 404:
        print("页面未找到")  # ✅ 会执行
    case 500:
        print("服务器错误")
    case _:
        print("未知状态")

# 支持模式匹配
point = (0, 0)
match point:
    case (0, 0):
        print("原点")  # ✅ 会执行
    case (0, y):
        print(f"y 轴上的点: y={y}")
    case (x, 0):
        print(f"x 轴上的点: x={x}")
    case (x, y):
        print(f"坐标: ({x}, {y})")

JavaScript switch 语句:

javascript 复制代码
// JavaScript
let statusCode = 404

switch (statusCode) {
  case 200:
    console.log('请求成功')
    break
  case 404:
    console.log('页面未找到') // ✅ 会执行
    break
  case 500:
    console.log('服务器错误')
    break
  default:
    console.log('未知状态')
}

关键区别: Python 的 match 不需要 break,更强大的模式匹配!

8.3 海象运算符(:=)Python 3.8+

在条件表达式中赋值:

python 复制代码
# Python 3.8+
# 传统写法
user_input = input("请输入: ")
if len(user_input) > 5:
    print(f"输入太长: {len(user_input)} 个字符")

# 使用海象运算符
if (n := len(input("请输入: "))) > 5:
    print(f"输入太长: {n} 个字符")

# 实用场景:避免重复计算
import re
text = "联系电话: 138-0013-8000"
if (match := re.search(r'\d{3}-\d{4}-\d{4}', text)):
    print(f"找到电话: {match.group()}")

🆚 九、总结对比

9.1 语法差异总结

特性 Python JavaScript
条件后符号 冒号 :
代码块 缩进(4 空格) 花括号 {}
条件括号 不需要 需要 ()
elif elif else if
逻辑与 and &&
逻辑或 or `
逻辑非 not !
三元运算符 值1 if 条件 else 值2 条件 ? 值1 : 值2
Switch match(3.10+) switch
成员判断 in .includes() / in
空值 None null, undefined

9.2 假值差异

类型 Python JavaScript
空数组 ❌ 假 ✅ 真
空对象 ❌ 假 ✅ 真
空字符串 ✅ 假 ✅ 假
数字零 ✅ 假 ✅ 假

9.3 核心差异

特性 Python JavaScript
代码风格 缩进强制 花括号
语法设计 接近自然语言 符号化
列表推导式 ✅ 原生支持 ❌ 需用 filter/map
match 语句 ✅ 强大的模式匹配 switch 较简单
空容器 视为假值 视为真值

💡 最佳实践

10.1 保持正确的缩进

python 复制代码
# ✅ 好 - 使用4个空格
if condition:
    do_something()
    do_another()

# ❌ 不好 - 混用空格和Tab
if condition:
    do_something()
	do_another()  # 可能导致错误!

提示: VS Code 可设置自动转换 Tab 为空格。

10.2 避免过深嵌套

python 复制代码
# ❌ 不好 - 嵌套太深
if condition1:
    if condition2:
        if condition3:
            if condition4:
                do_something()

# ✅ 好 - 提前返回
if not condition1:
    return
if not condition2:
    return
if not condition3:
    return
if not condition4:
    return
do_something()

10.3 利用 Python 的真值判断

python 复制代码
# ❌ 不好
if len(items) > 0:
    process(items)

# ✅ 好 - 更 Pythonic
if items:
    process(items)

# ❌ 不好
if user_name != "":
    greet(user_name)

# ✅ 好
if user_name:
    greet(user_name)

10.4 使用 in 简化判断

python 复制代码
# ❌ 不好
if status == 200 or status == 201 or status == 204:
    print("成功")

# ✅ 好
if status in [200, 201, 204]:
    print("成功")

# 或使用元组(更快)
if status in (200, 201, 204):
    print("成功")

10.5 复杂条件使用变量

python 复制代码
# ❌ 不好 - 条件复杂难读
if user.age >= 18 and user.has_license and not user.is_banned:
    allow_drive()

# ✅ 好 - 使用有意义的变量名
is_adult = user.age >= 18
has_permission = user.has_license and not user.is_banned

if is_adult and has_permission:
    allow_drive()

🎯 实战练习

练习 1: BMI 计算器

python 复制代码
print("=== BMI 健康指数计算器 ===\n")

# 输入身高和体重
height = float(input("请输入身高(米): "))
weight = float(input("请输入体重(公斤): "))

# 计算 BMI
bmi = weight / (height ** 2)

# 判断健康状态
print(f"\n你的 BMI 指数是: {bmi:.2f}")

if bmi < 18.5:
    status = "偏瘦"
    suggestion = "建议增加营养摄入"
elif bmi < 24:
    status = "正常"
    suggestion = "继续保持健康生活方式"
elif bmi < 28:
    status = "偏胖"
    suggestion = "建议适量运动和控制饮食"
else:
    status = "肥胖"
    suggestion = "建议咨询医生并制定减重计划"

print(f"健康状态: {status}")
print(f"建议: {suggestion}")

练习 2: 会员折扣系统

python 复制代码
print("=== 购物折扣计算系统 ===\n")

# 输入信息
total_amount = float(input("购物金额: "))
is_member = input("是否会员? (是/否): ") == "是"
member_years = 0

if is_member:
    member_years = int(input("会员年限: "))

# 计算折扣
discount = 0

if not is_member:
    # 非会员: 满200打9折
    if total_amount >= 200:
        discount = 0.1
else:
    # 会员折扣
    if member_years >= 5:
        discount = 0.3  # 5年以上会员: 7折
    elif member_years >= 2:
        discount = 0.2  # 2-5年会员: 8折
    else:
        discount = 0.15  # 新会员: 85折

    # 额外满减
    if total_amount >= 500:
        discount += 0.05  # 额外5%折扣

# 计算最终价格
discount = min(discount, 0.5)  # 最多5折
final_amount = total_amount * (1 - discount)
saved = total_amount - final_amount

# 输出结果
print("\n" + "=" * 40)
print(f"原价: ¥{total_amount:.2f}")
print(f"折扣: {discount * 100:.0f}%")
print(f"应付: ¥{final_amount:.2f}")
print(f"节省: ¥{saved:.2f}")
print("=" * 40)

练习 3: 密码强度检测

python 复制代码
def check_password_strength(password):
    """检测密码强度"""

    # 检查长度
    length = len(password)

    # 检查各种字符类型
    has_lower = any(c.islower() for c in password)
    has_upper = any(c.isupper() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_special = any(not c.isalnum() for c in password)

    # 计算得分
    score = 0

    if length >= 8:
        score += 1
    if length >= 12:
        score += 1
    if has_lower:
        score += 1
    if has_upper:
        score += 1
    if has_digit:
        score += 1
    if has_special:
        score += 1

    # 判断强度
    if score <= 2:
        strength = "弱"
        color = "🔴"
    elif score <= 4:
        strength = "中"
        color = "🟡"
    else:
        strength = "强"
        color = "🟢"

    # 输出建议
    suggestions = []
    if length < 8:
        suggestions.append("密码长度至少8位")
    if not has_lower:
        suggestions.append("添加小写字母")
    if not has_upper:
        suggestions.append("添加大写字母")
    if not has_digit:
        suggestions.append("添加数字")
    if not has_special:
        suggestions.append("添加特殊字符")

    return strength, color, score, suggestions

# 测试
print("=== 密码强度检测器 ===\n")
password = input("请输入密码: ")

strength, color, score, suggestions = check_password_strength(password)

print(f"\n密码强度: {color} {strength} (得分: {score}/6)")

if suggestions:
    print("\n改进建议:")
    for i, tip in enumerate(suggestions, 1):
        print(f"  {i}. {tip}")
else:
    print("\n✅ 密码强度很好!")

📚 核心要点

  1. 语法特点

    • Python 使用 冒号 + 缩进,不用花括号
    • 缩进是语法的一部分,错误会导致报错
    • elif 代替 else if
  2. 逻辑运算符

    • 使用 and, or, not(不是 &&, ||, !
    • 更接近自然语言,易读
  3. 真值判断

    • 空容器(列表、字典、字符串)为假
    • 与 JavaScript 不同:[]{} 在 Python 中是假值
  4. 高级特性

    • 列表/字典推导式:简洁的过滤和转换
    • in 运算符:优雅的成员判断
    • match 语句:强大的模式匹配(3.10+)
    • 海象运算符:在条件中赋值(3.8+)
  5. 最佳实践

    • 保持一致的缩进(4 空格)
    • 避免过深嵌套,提前返回
    • 利用 Python 的真值判断特性
    • 使用有意义的变量名提高可读性
  6. 关键区别

    • Python: 强制缩进、更 Pythonic 的写法
    • JavaScript: 花括号、更灵活但易出错

本文适合前端开发者快速掌握 Python 的条件语句,通过大量实例和对比理解 Python 的特点。

相关推荐
扎瓦斯柯瑞迫3 小时前
cursor: 10分钟魔改环境、优雅获取Token
前端·javascript·后端
java1234_小锋3 小时前
PyTorch2 Python深度学习 - 初识PyTorch2,实现一个简单的线性神经网络
开发语言·python·深度学习·pytorch2
San303 小时前
CSS3 星球大战:用前端技术打造震撼的3D动画效果
前端·css·html
用户12039112947263 小时前
从零构建一个HTML5敲击乐Web应用:前端开发最佳实践指南
前端
Violet_YSWY3 小时前
将axios、async、Promise联系在一起讲一下&讲一下.then 与其关系
开发语言·前端·javascript
San303 小时前
扩展卡片效果:用 Flexbox 和 CSS 过渡打造惊艳交互体验
前端·javascript·css
写代码的皮筏艇3 小时前
JS数据类型转换
前端·javascript
Qinana3 小时前
🌟 从 CSS 到 Stylus:打造更优雅、高效的样式开发体验
前端·javascript·css
AAA阿giao3 小时前
弹性布局:CSS 布局的“变形金刚”来了!
前端·css