Python 变量和 JS 很像,但有一些关键差异:
// 声明 + 赋值
let name = "Alice";
const age = 25;
var old = "不推荐";
// 重新赋值
name = "Bob";
// 同时声明多个
let a = 1, b = 2;
# 直接赋值,不需要声明关键字
name = "Alice"
age = 25
# 重新赋值
name = "Bob"
# 同时赋值多个
a, b = 1, 2
# 交换变量(Python 特有)
a, b = b, a
let/const/var,直接写变量名MAX_SIZE = 100a = b = c = 0x, y = 10, 20# 合法
name = "Alice"
_name = "私有约定"
name2 = "数字不能开头"
MAX_SIZE = 100 # 常量约定
my_name = "snake_case" # Python 推荐
# 不合法
# 2name = "数字开头" # SyntaxError
# my-name = "连字符" # SyntaxError
# class = "关键字" # SyntaxError
camelCase,Python 用 snake_case。类名用 PascalCase。
# 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
// falsy 值
false, 0, "", null, undefined, NaN
// truthy 值
"0", "false", [], {}, function(){}
// 示例
if ("0") { } // 执行!"0" 是 truthy
# falsy 值
False, 0, 0.0, "", [], {}, (), set(), None
# truthy 值
"0", "False", [0], {0: 0}
# 示例
if "0": # 执行!"0" 是 truthy
pass
[] 和 {} 是 truthy,Python 中是 falsyNone 类似 JS 的 null + undefinedNaN,除零会抛异常:ZeroDivisionError# None 表示"无"或"空"
result = None
# 检查 None
if result is None:
print("没有结果")
if result is not None:
print(f"结果:{result}")
# 不要用 == 判断 None(虽然能跑,但不规范)
if result == None: # 不推荐
pass
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 60) {
grade = "C";
} else {
grade = "D";
}
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
elif,不是 else if: 和缩进,不是大括号 {}const status = age >= 18 ? "成年" : "未成年";
status = "成年" if age >= 18 else "未成年"
| 运算 | JavaScript | Python |
|---|---|---|
| 与 | && | 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 "默认值" # "值"
// 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]);
}
# 遍历值(最常用)
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)
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]
count = 0
while count < 5:
print(count)
count += 1
# while + else(Python 特有)
count = 0
while count < 5:
print(count)
count += 1
else:
print("循环正常结束") # 没有 break 时执行
# 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)
for...else 类似 JS 的 try...finally,用于判断循环是否被 break 中断。
# 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
# 多个值
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()
执行:
# 要求:
# 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}")
# 要求输出:
# 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() # 换行
# 预设账号密码
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("账号已锁定,请稍后再试")
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}%")
False, 0, "", [], {}, (), Noneif/elif/else,注意冒号和缩进and/or/not 逻辑运算符for item in items 和 for i, item in enumerate(items)range()、while、break、continuefor...else / while...else 的用法