初面网初面网

变量与数据类型——数字、字符串、布尔

概念讲解

程序运行过程中,需要存储数据。变量就是数据的"名字标签"——你给一个数据起个名字,之后用这个名字就能找到它。

Python 是动态类型语言:创建变量时不需要声明类型,类型跟着值走。

常见的数据类型:

类型说明示例
int整数42, -7, 0
float浮点数(小数)3.14, -0.5
str字符串(文本)"hello", 'world'
bool布尔值True, False

代码示例

数字运算:计算商品折扣

original_price = 299.0
discount_rate = 0.8  # 8折
member_discount = 0.95  # 会员再减5%

final_price = original_price * discount_rate * member_discount
print(f"原价: {original_price}, 最终价格: {final_price:.2f}元")
# 输出: 原价: 299.0, 最终价格: 227.24元

字符串处理:清洗用户输入

username = "  Alice123  "
username_clean = username.strip().lower()
print(f"欢迎, {username_clean}!")
# 输出: 欢迎, alice123!

# 字符串常用操作
sentence = "Python is powerful"
print(sentence.split())        # ['Python', 'is', 'powerful']
print(len(sentence))           # 18(字符数)
print(sentence.replace("powerful", "elegant"))  # Python is elegant

布尔逻辑:复合条件判断

age = 25
has_ticket = True
has_money = False

# 可以入场吗?
can_enter = age >= 18 and has_ticket and has_money
print(f"可以入场: {can_enter}")  # False(缺钱)

# 布尔运算规则
print(True and False)   # False
print(True or False)    # True
print(not True)         # False

练习题

题目:写一个程序,根据用户输入的体温,判断是否需要休息。

规则:

  • 体温 < 36.5°C:体温偏低
  • 36.5°C ≤ 体温 < 37.2°C:正常
  • 37.2°C ≤ 体温 < 38°C:轻微发烧,建议休息
  • 体温 ≥ 38°C:发烧,建议就医
  • 体温 < 30°C 或 > 42°C:数据异常,请重新测量
参考答案
def check_temperature(temp):
    if temp < 30 or temp > 42:
        return "数据异常,请重新测量"
    elif temp < 36.5:
        return "体温偏低"
    elif temp < 37.2:
        return "正常"
    elif temp < 38:
        return "轻微发烧,建议休息"
    else:
        return "发烧,建议就医"

# 测试
print(check_temperature(36.0))   # 体温偏低
print(check_temperature(36.8))   # 正常
print(check_temperature(37.5))   # 轻微发烧,建议休息
print(check_temperature(39.0))   # 发烧,建议就医

关键思维:

  • 条件要按顺序写,因为 elif 是"否则如果",先写的条件会优先匹配
  • or 处理边界外的异常情况

更新于 2026/6/7