第一章:Python简介与安装
1.1 什么是Python
Python是一种高级、解释型、通用的编程语言。它的设计哲学强调代码的可读性,使用显著的缩进。Python是多范式的,支持面向对象、命令式和函数式编程。
- 简单易学
- 免费开源
- 丰富的库
- 跨平台
1.3 第一个程序
# 这是一个简单的Python程序
print("Hello, World!")
第二章:变量与数据类型
2.1 变量
变量是存储数据的容器。在Python中,不需要声明变量类型。
name = "张三"
age = 25
height = 1.75
is_student = True
2.2 基本数据类型
- 整数 (int):1, 2, 3, -5, 100
- 浮点数 (float):3.14, 2.0, -0.5
- 字符串 (str):"hello", 'world
- 布尔值 (bool):True, False
2.3 类型转换
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)
print(type(num_int)) #
print(type(num_float)) #
第三章:运算符与表达式
3.1 算术运算符
a = 10
b = 3
print(a + b) # 加法 13
print(a - b) # 减法 7
print(a * b) # 乘法 30
print(a / b) # 除法 3.333...
print(a // b) # 整除 3
print(a % b) # 取余 1
print(a ** b) # 幂运算 1000
3.2 比较运算符
x = 5
y = 10
print(x == y) # 等于 False
print(x != y) # 不等于 True
print(x < y) # 小于 True
print(x > y) # 大于 False
print(x <= y) # 小于等于 True
print(x >= y) # 大于等于 False
3.3 逻辑运算符
a = True
b = False
print(a and b) # 与 False
print(a or b) # 或 True
print(not a) # 非 False
第四章:控制流程
4.1 if语句
age = 18
if age >= 18:
print("成年人")
elif age >= 13:
print("青少年")
else:
print("儿童")
4.2 for循环
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(fruit)
# 使用range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
4.3 while循环
count = 0
while count < 5:
print(count)
count += 1
练习题
练习1:计算圆的面积
编写一个程序,输入圆的半径,计算并输出圆的面积。
radius = float(input("请输入圆的半径:"))
pi = 3.14159
area = pi * radius ** 2
print(f"圆的面积是:{area}")
练习2:判断闰年
编写一个程序,判断输入的年份是否为闰年。
year = int(input("请输入年份:"))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year}年是闰年")
else:
print(f"{year}年不是闰年")
练习3:打印九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()