1# 算术运算符2a =10+5# 加3b =10-5# 减4c =10*5# 乘5d =10/3# 除(返回浮点)6e =10//3# 整除7f =10%3# 取余8g =2**3# 幂运算910# 比较运算符11x == y # 等于12x != y # 不等于13x > y # 大于14x < y # 小于15x >= y # 大于等于16x <= y # 小于等于1718# 逻辑运算符19a and b # 与20a or b # 或21not a # 非
1age =1823if age <13:4print("儿童")5elif age <18:6print("青少年")7else:8print("成人")
循环语句
1# for 循环2for i inrange(5):# 0,1,2,3,43print(i)45fruits =["apple","banana","cherry"]6for fruit in fruits:7print(fruit)89# while 循环10count =011while count <5:12print(count)13 count +=1
7. 函数定义
1# 定义函数2defgreet(name):3"""这是一个问候函数"""4returnf"Hello, {name}!"56# 调用函数7message = greet("Alice")8print(message)910# 带默认参数的函数11defadd_numbers(a, b=10):12return a + b
1314result = add_numbers(5)# 15
8. 输入输出
1# 输入2name =input("请输入你的名字: ")3age =int(input("请输入你的年龄: "))# 转换为整数45# 格式化输出6name ="Alice"7age =258print(f"{name} is {age} years old.")# f-string(推荐)9print("{} is {} years old.".format(name, age))# format方法
9. 异常处理
1try:2 num =int(input("请输入一个数字: "))3 result =10/ num
4except ValueError:5print("输入的不是有效数字!")6except ZeroDivisionError:7print("不能除以零!")8else:9print(f"结果是: {result}")10finally:11print("程序执行完毕")
10. 文件操作
1# 写入文件2withopen("example.txt","w")asfile:3file.write("Hello, Python!\n")4file.write("第二行内容")56# 读取文件7withopen("example.txt","r")asfile:8 content =file.read()9print(content)1011# 逐行读取12withopen("example.txt","r")asfile:13for line infile:14print(line.strip())
11. 模块导入
1# 导入整个模块2import math
3print(math.sqrt(16))45# 导入特定函数6from datetime import datetime
7current_time = datetime.now()89# 给模块起别名10import numpy as np
12. 列表推导式
1# 生成平方列表2squares =[x**2for x inrange(10)]34# 带条件的推导式5even_squares =[x**2for x inrange(10)if x %2==0]67# 字典推导式8square_dict ={x: x**2for x inrange(5)}