Python基础:数据类型、输入输出与流程控制
数据类型识别与基础类型 使用type()函数可检测变量类型:
print(type(1000)) # 输出: <class 'int'>
整型(int) 支持算术运算:
x = 50
print(x + 5) # 加法: 55
print(x - 10) # 减法: 40
print(x * 2) # 乘法: 100
print(x / 5) # 除法: 10.0
print(x % 3) # 取余: 2
字符串(str) 引号包裹的文本,支持转义和运算:
print("内部'单引号'")
print('内部"双引号"')
print("转义\"字符\"")
s1 = "Python"
s2 = "编程"
print(s1 + s2) # 连接: Python编程
print("Hi!" * 3) # 重复: Hi!Hi!Hi!
num_str = "256"
converted = int(num_str)
print(type(converted)) # <class 'int'>
布尔型(bool)
flag = True
print(flag, type(flag)) # True <class 'bool'>
用户输入处理
user_name = input("输入姓名: ")
user_age = input("输入年龄: ")
print(f"姓名:{user_name}, 年龄:{user_age}岁")
print(type(user_age)) # 始终返回 <class 'str'>
流程控制结构
条件判断
# 单分支
if 10 > 5:
print("条件成立")
# 双分支
value = False
if value:
print("真值")
else:
print("假值")
# 多分支
choice = input("选择操作(1-3):")
if choice == "1":
print("执行操作A")
elif choice == "2":
print("执行操作B")
elif choice == "3":
print("执行操作C")
else:
print("无效选择")
# 成绩等级匹配
score = int(input("输入分数(0-100):"))
if score > 100:
print("超出范围")
elif score >= 90:
print("A级")
elif score >= 80:
print("B级")
elif score >= 60:
print("C级")
elif score >= 40:
print("D级")
else:
print("E级")
# 嵌套判断
id_name = input("输入ID: ")
id_age = input("输入年龄: ")
if id_name == "admin":
if id_age == "30":
print("验证通过")
else:
print("年龄错误")
else:
print("ID错误")
循环结构
while循环
# 基础循环
counter = 1
while counter <= 5:
print(counter)
counter += 1
# 循环控制
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # 跳过偶数
print(num) # 输出奇数
# 循环中断
while True:
cmd = input("输入命令(exit退出):")
if cmd == "exit":
break
print(f"执行:{cmd}")
for循环
# 遍历序列
colors = ["红", "绿", "蓝"]
for color in colors:
print(color)
# 成员检测
comment = "包含敏感词的内容"
if "敏感词" in comment:
print("存在禁用词汇")
注意:避免混合使用Tab和空格缩进