Day 2 · 变量、类型与控制流

Week 1 · Day 2 / 56 · 预计 1.5-2 小时 · 返回大纲

一、变量赋值

Python 变量和 JS 很像,但有一些关键差异:

JavaScript
// 声明 + 赋值
let name = "Alice";
const age = 25;
var old = "不推荐";

// 重新赋值
name = "Bob";

// 同时声明多个
let a = 1, b = 2;
Python
# 直接赋值,不需要声明关键字
name = "Alice"
age = 25

# 重新赋值
name = "Bob"

# 同时赋值多个
a, b = 1, 2

# 交换变量(Python 特有)
a, b = b, a
关键差异:

变量命名规则

# 合法
name = "Alice"
_name = "私有约定"
name2 = "数字不能开头"
MAX_SIZE = 100      # 常量约定
my_name = "snake_case"  # Python 推荐

# 不合法
# 2name = "数字开头"     # SyntaxError
# my-name = "连字符"     # SyntaxError
# class = "关键字"       # SyntaxError
💡 前端类比: JS 用 camelCase,Python 用 snake_case。类名用 PascalCase。

二、数据类型详解

2.1 数字类型

# int - 整数(任意精度)
age = 25
big = 999999999999999999999999  # 不会溢出

# float - 浮点数
pi = 3.14159
price = 9.99

# 类型转换
int("42")       # 42
int(3.99)       # 3(截断,不是四舍五入)
float("3.14")   # 3.14
str(42)         # "42"

# 检查类型
type(42)        # <class 'int'>
type(3.14)      # <class 'float'>
isinstance(42, int)   # True

2.2 布尔类型

JavaScript Truthy/Falsy
// falsy 值
false, 0, "", null, undefined, NaN

// truthy 值
"0", "false", [], {}, function(){}

// 示例
if ("0") { }  // 执行!"0" 是 truthy
Python Truthy/Falsy
# falsy 值
False, 0, 0.0, "", [], {}, (), set(), None

# truthy 值
"0", "False", [0], {0: 0}

# 示例
if "0":  # 执行!"0" 是 truthy
    pass
重要差异:

2.3 None 类型

# None 表示"无"或"空"
result = None

# 检查 None
if result is None:
    print("没有结果")

if result is not None:
    print(f"结果:{result}")

# 不要用 == 判断 None(虽然能跑,但不规范)
if result == None:  # 不推荐
    pass

三、条件语句

3.1 if / elif / else

JavaScript
if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 60) {
    grade = "C";
} else {
    grade = "D";
}
Python
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"
关键差异:

3.2 条件表达式(三元运算符)

JavaScript
const status = age >= 18 ? "成年" : "未成年";
Python
status = "成年" if age >= 18 else "未成年"

3.3 逻辑运算符

运算JavaScriptPython
与&&and
或||or
非!not
# Python 示例
age = 25
has_id = True

if age >= 18 and has_id:
    print("可以进入")

if age < 18 or not has_id:
    print("不能进入")

# 短路运算(和 JS 一样)
result = None or "默认值"      # "默认值"
result = "" or "默认值"        # "默认值"(空字符串是 falsy)
result = "值" or "默认值"      # "值"

四、循环

4.1 for 循环

JavaScript
// for...of(遍历值)
for (const item of items) {
    console.log(item);
}

// for...in(遍历索引)
for (const i in items) {
    console.log(i, items[i]);
}

// 传统 for
for (let i = 0; i < items.length; i++) {
    console.log(items[i]);
}
Python
# 遍历值(最常用)
for item in items:
    print(item)

# 遍历索引和值
for i, item in enumerate(items):
    print(i, item)

# 遍历范围
for i in range(len(items)):
    print(items[i])

# 反向遍历
for item in reversed(items):
    print(item)

4.2 range() 函数

range(5)          # 0, 1, 2, 3, 4
range(1, 6)       # 1, 2, 3, 4, 5
range(0, 10, 2)   # 0, 2, 4, 6, 8(步长 2)
range(5, 0, -1)   # 5, 4, 3, 2, 1(倒序)

# 转列表
list(range(5))    # [0, 1, 2, 3, 4]

4.3 while 循环

count = 0
while count < 5:
    print(count)
    count += 1

# while + else(Python 特有)
count = 0
while count < 5:
    print(count)
    count += 1
else:
    print("循环正常结束")  # 没有 break 时执行

4.4 break / continue / else

# break:跳出循环
for i in range(10):
    if i == 5:
        break
    print(i)  # 0 1 2 3 4

# continue:跳过本次
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 1 3 5 7 9

# for + else(Python 特有)
for i in range(5):
    print(i)
else:
    print("循环正常结束")  # 执行

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("循环正常结束")  # 不执行(因为 break)
💡 前端类比: Python 的 for...else 类似 JS 的 try...finally,用于判断循环是否被 break 中断。

五、输入输出

5.1 input() 获取用户输入

# input() 返回字符串
name = input("请输入名字:")
print(f"你好,{name}")

# 转数字
age = int(input("请输入年龄:"))
print(f"明年 {age + 1} 岁")

# 带默认值处理
age_input = input("请输入年龄(默认 25):")
age = int(age_input) if age_input else 25

5.2 print() 高级用法

# 多个值
print("a", "b", "c")           # a b c

# 自定义分隔符
print("a", "b", "c", sep="-")  # a-b-c

# 不换行
print("加载中", end="")
print(".", end="")
print(".")

# 输出到文件
with open("log.txt", "w") as f:
    print("日志内容", file=f)

六、实战:猜数字游戏

创建 day2.py,综合运用今天的内容:

#!/usr/bin/env python3
"""Day 2 练习:猜数字游戏"""

import random

def main():
    # 生成 1-100 的随机数
    secret = random.randint(1, 100)
    attempts = 0
    max_attempts = 7
    
    print("=" * 40)
    print("欢迎来到猜数字游戏!")
    print(f"我想了一个 1-100 的数字,你有 {max_attempts} 次机会")
    print("=" * 40)
    
    while attempts < max_attempts:
        # 获取输入
        guess_input = input(f"\n第 {attempts + 1} 次猜测:")
        
        # 输入验证
        if not guess_input.isdigit():
            print("请输入数字!")
            continue
        
        guess = int(guess_input)
        attempts += 1
        
        # 判断
        if guess == secret:
            print(f"\n🎉 恭喜你!猜对了!")
            print(f"你用了 {attempts} 次")
            break
        elif guess < secret:
            remaining = max_attempts - attempts
            print(f"太小了!还剩 {remaining} 次机会")
        else:
            remaining = max_attempts - attempts
            print(f"太大了!还剩 {remaining} 次机会")
    else:
        # while 正常结束(没 break)= 用完次数
        print(f"\n😢 游戏结束,数字是 {secret}")
    
    # 询问是否再玩
    again = input("\n再玩一次?(y/n): ")
    if again.lower() == "y":
        main()

if __name__ == "__main__":
    main()

执行:

$ python3 day2.py
========================================
欢迎来到猜数字游戏!
我想了一个 1-100 的数字,你有 7 次机会
========================================

第 1 次猜测:50
太小了!还剩 6 次机会

第 2 次猜测:75
太大了!还剩 5 次机会
...

七、动手练习

练习 1:BMI 计算器
输入身高体重,计算 BMI 并给出健康建议
# 要求:
# 1. 输入身高(米)和体重(千克)
# 2. 计算 BMI = 体重 / (身高 ** 2)
# 3. 根据 BMI 输出建议:
#    < 18.5: 偏瘦
#    18.5-24: 正常
#    24-28: 偏胖
#    >= 28: 肥胖
# 4. 用 f-string 格式化输出,保留 1 位小数

# 你的代码:
查看答案
参考答案
height = float(input("请输入身高(米):"))
weight = float(input("请输入体重(千克):"))

bmi = weight / (height ** 2)

if bmi < 18.5:
    status = "偏瘦"
    advice = "多吃点,注意营养均衡"
elif bmi < 24:
    status = "正常"
    advice = "继续保持健康的生活方式"
elif bmi < 28:
    status = "偏胖"
    advice = "建议控制饮食,增加运动"
else:
    status = "肥胖"
    advice = "建议咨询医生,制定减重计划"

print(f"\n你的 BMI 是:{bmi:.1f}")
print(f"状态:{status}")
print(f"建议:{advice}")
练习 2:九九乘法表
用嵌套循环打印九九乘法表
# 要求输出:
# 1x1=1  
# 2x1=2  2x2=4  
# 3x1=3  3x2=6  3x3=9  
# ...
# 9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81

# 你的代码:
查看答案
参考答案
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{i}x{j}={i*j}", end="  ")
    print()  # 换行
练习 3:登录验证
模拟用户登录,最多 3 次机会
# 预设账号密码
USERNAME = "admin"
PASSWORD = "123456"

# 要求:
# 1. 最多 3 次输入机会
# 2. 输入正确:打印"登录成功",break
# 3. 输入错误:提示剩余次数
# 4. 3 次都错:打印"账号已锁定"
# 5. 用 while 循环实现

# 你的代码:
查看答案
参考答案
USERNAME = "admin"
PASSWORD = "123456"

attempts = 0
max_attempts = 3

while attempts < max_attempts:
    username = input("用户名:")
    password = input("密码:")
    
    attempts += 1
    
    if username == USERNAME and password == PASSWORD:
        print("登录成功!")
        break
    else:
        remaining = max_attempts - attempts
        if remaining > 0:
            print(f"用户名或密码错误,还剩 {remaining} 次机会")
else:
    print("账号已锁定,请稍后再试")
练习 4:成绩等级
输入多个成绩,统计各等级人数
scores = [85, 92, 78, 90, 88, 76, 95, 89, 72, 84]

# 要求:
# 1. 统计 A(90+)、B(80-89)、C(70-79)、D(60-69)、F(<60) 各等级人数
# 2. 用 for 循环 + if/elif/else
# 3. 输出每个等级的人数和占比(百分比保留 1 位小数)

# 你的代码:
查看答案
参考答案
scores = [85, 92, 78, 90, 88, 76, 95, 89, 72, 84]

# 初始化计数器
a_count = 0
b_count = 0
c_count = 0
d_count = 0
f_count = 0

# 统计
for score in scores:
    if score >= 90:
        a_count += 1
    elif score >= 80:
        b_count += 1
    elif score >= 70:
        c_count += 1
    elif score >= 60:
        d_count += 1
    else:
        f_count += 1

total = len(scores)

# 输出
print(f"总人数:{total}")
print(f"A (90+):{a_count} 人,占比 {a_count/total*100:.1f}%")
print(f"B (80-89):{b_count} 人,占比 {b_count/total*100:.1f}%")
print(f"C (70-79):{c_count} 人,占比 {c_count/total*100:.1f}%")
print(f"D (60-69):{d_count} 人,占比 {d_count/total*100:.1f}%")
print(f"F (<60):{f_count} 人,占比 {f_count/total*100:.1f}%")

八、打卡验收

理解 Python 变量不需要声明关键字,直接赋值
掌握 Python 的 falsy 值:False, 0, "", [], {}, (), None
会用 if/elif/else,注意冒号和缩进
会用 and/or/not 逻辑运算符
掌握 for item in items 和 for i, item in enumerate(items)
会用 range()、while、break、continue
理解 for...else / while...else 的用法
完成 4 个动手练习,代码能跑通
打卡方式: 全部勾选后,告诉我 "Day 2 打卡",并贴出你的代码,我帮你检查。
明天预告(Day 3): 函数定义、参数(默认参数、关键字参数、*args/**kwargs)、lambda 表达式、文档字符串。