入门必学25个python命令
打印输出:print()
输出字符串:
# 输出简单的欢迎信息 print("欢迎来到Python编程世界!")
输出变量值:
name = "Alice" # 输出变量的值,使用逗号分隔不同的参数 print("你好,", name)
使用f-string格式化输出:
age = 25 # 使用f-string嵌入变量到字符串中 print(f"我今年{age}岁了。")
输出多个变量,用空格分隔:
first_name = "张" last_name = "三" # 输出多个变量,自动以空格分隔 print(first_name, last_name)
控制输出不换行:
# 使用end参数控制输出后不换行,默认是换行符'\n' print("这是第一行", end=" ") print("这是在同一行继续输出的内容")
变量定义与赋值
定义并赋值一个整数变量:
# 定义一个整数类型的变量 my_age = 28 print(my_age) # 输出变量的值
定义并赋值一个浮点数变量:
# 定义一个浮点数类型的变量 pi_value = 3.14159 print(pi_value) # 输出变量的值
同时为多个变量赋值:
# 同时给多个变量赋值 x, y, z = 1, 2, 3 print(x, y, z) # 输出所有变量的值
重新赋值变量:
# 变量可以被重新赋值 counter = 0 counter = counter + 1 print(counter) # 输出更新后的值
使用变量进行计算:
# 变量可以参与数学运算 price = 9.99 quantity = 3 total_cost = price * quantity print(total_cost) # 输出总成本
数据类型转换
字符串转整数:
# 将字符串形式的数字转换为整数 num_str = "100" num_int = int(num_str) print(num_int) # 输出转换后的整数
浮点数转字符串:
# 将浮点数转换为字符串 num_float = 3.14 num_str = str(num_float) print(num_str) # 输出转换后的字符串
列表转元组:
# 将列表转换为元组 list_items = [1, 2, 3] tuple_items = tuple(list_items) print(tuple_items) # 输出转换后的元组
元组转集合:
# 将元组转换为集合,去除重复元素 tuple_data = (1, 2, 2, 3, 4, 4) set_data = set(tuple_data) print(set_data) # 输出转换后的集合
创建字典:
# 使用键值对创建字典 dict_data = dict(name="李四", age=30) print(dict_data) # 输出字典
条件语句
简单的if条件判断:
score = 60 if score >= 60: print("及格") # 如果分数大于等于60,输出及格 if...else结构: temperature = 75 if temperature > 80: print("天气炎热") else: print("天气凉爽") if...elif...else结构: user_input = 3 if user_input == 1: print("选择了选项一") elif user_input == 2: print("选择了选项二") else: print("选择了其他选项")
嵌套的条件判断:
is_student = True grade = 90 if is_student: if grade >= 90: print("优秀学生") else: print("普通学生") else: print("非学生") 复合条件判断: height = 175 weight = 70 if height > 170 and weight < 80: print("符合标准")
循环语句
for循环遍历列表:
fruits = ["苹果", "香蕉", "橙子"] for fruit in fruits: print(fruit) # 遍历列表中的每个元素,并打印出来 for循环结合range函数: for i in range(1, 5): # 从1开始到4结束(不包括5) print(i) # 打印当前索引 while循环: count = 0 while count < 5: print(count) # 当count小于5时,打印count的值 count += 1 # 每次循环后增加count的值
for循环与列表解析:
squares = [x**2 for x in range(10)] for square in squares: print(square) # 使用列表解析生成平方数列表,并遍历打印 带有break语句的循环: for number in range(1, 10): if number == 5: break # 当number等于5时,跳出循环 print(number)
函数定义
定义一个简单的函数:
def greet(): """这是一个简单的问候函数""" print("你好,欢迎来到Python的世界!") # 打印欢迎信息 greet() # 调用greet函数
带参数的函数定义:
def say_hello(name): """根据传入的名字打印个性化问候""" print(f"你好, {name}!") # 使用f-string格式化字符串 say_hello("小明") # 调用say_hello函数并传递参数
返回值的函数:
def add_numbers(a, b): """返回两个数相加的结果""" return a + b # 返回计算结果 result = add_numbers(5, 3) # 调用add_numbers函数并接收返回值 print(result) # 输出结果
包含默认参数的函数:
def describe_pet(pet_name, animal_type='狗'): """描述宠物的信息""" print(f"\n我有一只{animal_type}。") print(f"我的{animal_type}叫{pet_name}。") describe_pet('旺财') # 使用默认参数调用describe_pet函数 describe_pet('汤姆', '猫') # 传递所有参数调用describe_pet函数
可变数量参数的函数:
def make_pizza(*toppings): """打印顾客点的所有配料""" print("\n制作披萨需要以下配料:") for topping in toppings: print(f"- {topping}") make_pizza('蘑菇', '青椒', '培根') # 调用make_pizza函数并传递多个参数
调用函数
调用无参函数:
def welcome_message(): """显示欢迎消息""" print("欢迎使用我们的服务!") welcome_message() # 直接调用函数
调用带参数的函数:
def display_message(message): """显示传递的消息""" print(message) display_message("这是通过函数传递的消息。") # 调用函数并传递参数
调用返回值的函数:
def get_formatted_name(first_name, last_name): """返回整洁的姓名""" full_name = f"{first_name} {last_name}" return full_name.title() musician = get_formatted_name('jimi', 'hendrix') # 调用函数获取返回值 print(musician) # 打印返回值
调用带有关键字参数的函数:
def build_profile(first, last, **user_info): """创建一个字典,其中包含我们知道的有关用户的一切""" user_info['first_name'] = first user_info['last_name'] = last return user_info user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') print(user_profile) # 调用函数并传递关键字参数
调用可变参数的函数:
def make_sandwich(*items): """列出三明治中的所有配料""" print("\n正在为您制作含有以下配料的三明治:") for item in items: print(f"- {item}") make_sandwich('火腿', '奶酪', '生菜') # 调用函数并传递多个参数
输入函数
获取用户输入并输出:
name = input("请输入您的名字: ") # 提示用户输入 print(f"您好, {name}!") # 输出用户输入的名字
获取数字输入并进行计算:
age = int(input("请输入您的年龄: ")) # 将输入转换为整数 next_year_age = age + 1 print(f"明年您将会是 {next_year_age} 岁。")
获取多个输入并存储在列表中:
hobbies = [] # 创建空列表来保存爱好 hobby = input("请输入您的爱好 (输入'结束'来停止): ") while hobby != '结束': hobbies.append(hobby) # 添加到列表 hobby = input("请输入您的下一个爱好 (输入'结束'来停止): ") print("您的爱好有:", hobbies)
处理浮点数输入:
height = float(input("请输入您的身高(米): ")) weight = float(input("请输入您的体重(千克): ")) bmi = weight / (height * height) # 计算BMI指数 print(f"您的BMI指数是 {bmi:.2f}") # 格式化输出保留两位小数
结合条件判断处理输入:
answer = input("您喜欢编程吗?(yes/no): ") if answer.lower() == 'yes': print("太棒了,继续加油!") else: print("没关系,每个人都有自己的兴趣。")
注释
单行注释示例:
# 这是一个单行注释 print("Hello, World!") # 在打印语句后添加注释
多行注释示例:
''' 这是一段多行注释, 用来解释下面这段代码的功能。 ''' print("这是一段测试代码。")
文档字符串示例:
def square_number(n): """ 返回给定数字的平方。 参数 n: 要求平方的数字 返回: 数字的平方 """ return n * n print(square_number(4)) # 调用square_number函数
使用注释来临时禁用代码:
# print("这条消息不会被打印出来。") print("这条消息会被打印出来。") 注释用于调试和说明复杂逻辑: # 计算阶乘 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) # 递归调用自身 print(factorial(5)) # 输出5的阶乘
缩进
正确缩进的if语句:
age = 20 if age >= 18: print("成年人") # 正确缩进,属于if块 print("检查完成") # 不属于if块
循环中的正确缩进:
for i in range(5): print(i) # 每次循环都会执行,并且正确缩进 print("循环结束") # 循环结束后执行,不缩进
函数体内的正确缩进:
def my_function(): print("这是函数内部的代码") # 函数体内的代码必须缩进 my_function() # 调用函数
错误的缩进会导致语法错误:
def another_function(): print("如果没有正确缩进,会抛出IndentationError") # 这里缺少缩进,会导致错误
嵌套结构中的缩进:
if True: print("外层条件成立") if False: print("内层条件不成立") # 内层条件的代码块 else: print("内层条件成立") # 内层else部分的代码块
退出程序
使用 exit() 来终止程序:
print("程序开始") exit() # 程序在此处停止,不会执行后续代码 print("这行代码不会被执行") # 此行代码不会被执行
使用 sys.exit() 并传递状态码:
import sys print("尝试正常退出...") sys.exit(0) # 以状态码0退出,表示正常结束 [ty-reference](1)
在函数中使用 sys.exit() 处理错误情况:
import sys def divide(a, b): if b == 0: print("除数不能为零") sys.exit(1) # 错误退出,状态码为1 [ty-reference](1) return a / b result = divide(10, 0)
结合异常处理使用 sys.exit():
import sys try: raise ValueError("触发一个值错误") except ValueError: print("捕获到异常,准备退出程序") sys.exit(2) # 根据异常类型选择不同的退出状态码 [ty-reference](1)
在条件语句中使用 exit():
user_input = input("请输入'y'来继续:") if user_input != 'y': print("用户决定退出") exit() # 用户决定不继续,则退出程序 print("继续执行程序...") # 只有当用户输入'y'时才会执行
数学运算符
加法运算:
a = 5 b = 3 print(f"{a} + {b} = {a + b}") # 输出: 5 + 3 = 8
减法运算:
a = 10 b = 4 print(f"{a} - {b} = {a - b}") # 输出: 10 - 4 = 6
乘法运算:
a = 7 b = 6 print(f"{a} * {b} = {a * b}") # 输出: 7 * 6 = 42
除法运算:
a = 9 b = 2 print(f"{a} / {b} = {a / b}") # 输出: 9 / 2 = 4.5
整除和取模运算:
a = 11 b = 3 print(f"{a} // {b} = {a // b}, {a} % {b} = {a % b}") # 输出: 11 // 3 = 3, 11 % 3 = 2
逻辑运算符
使用 and 进行条件判断:
age = 20 has_license = True if age >= 18 and has_license: print("可以合法驾驶") # 当年龄大于等于18且有驾照时输出此消息
使用 or 进行条件判断:
is_student = False has_discount_card = True if is_student or has_discount_card: print("可以享受折扣") # 学生或有折扣卡都可以享受折扣
使用 not 反转布尔值:
raining = False if not raining: print("天气不错,适合外出") # 如果不下雨,则适合外出
组合使用逻辑运算符:
temperature = 22 humidity = 70 if temperature > 20 and humidity < 80: print("气候宜人") # 温度高于20且湿度低于80时气候宜人
在循环中结合逻辑运算符:
for i in range(1, 11): if i % 2 == 0 and i % 3 == 0: print(f"{i} 同时能被2和3整除") # 打印同时能被2和3整除的数字
身份运算符
使用 is 检查对象身份:
x = ["apple", "banana"] y = x print(x is y) # 输出: True,因为x和y引用同一个列表对象
使用 is not 检查不同对象:
x = ["apple", "banana"] z = ["apple", "banana"] print(x is not z) # 输出: True,尽管内容相同,但它们是两个不同的对象
结合 id() 函数验证身份运算符:
x = [1, 2, 3] y = x print(id(x), id(y)) # 输出相同的内存地址 print(x is y) # 输出: True
在条件判断中使用身份运算符:
a = None b = None if a is b: print("a和b都是None,或者引用同一对象") # 输出: a和b都是None,或者引用同一对象
对比 == 和 is 的区别:
x = [1, 2, 3] y = list(x) # 创建一个新的列表,与x内容相同 print(x == y) # 输出: True,因为它们的内容相等 print(x is y) # 输出: False,因为它们不是同一个对象
成员运算符
使用 in 检查元素是否在序列中:
fruits = ["apple", "banana", "cherry"] if "banana" in fruits: print("香蕉在水果列表中") # 输出: 香蕉在水果列表中
使用 not in 检查元素是否不在序列中:
fruits = ["apple", "banana", "cherry"] if "orange" not in fruits: print("橙子不在水果列表中") # 输出: 橙子不在水果列表中
在循环中使用成员运算符:
for fruit in ["apple", "banana", "cherry"]: if fruit in ["banana", "cherry"]: print(f"{fruit} 是我喜欢吃的水果之一") # 输出喜欢的水果
在字符串中查找字符:
sentence = "Hello, world!" if "world" in sentence: print("找到了单词 'world'") # 输出: 找到了单词 'world'
在字典中检查键的存在性:
student_scores = {"Alice": 90, "Bob": 85} if "Alice" in student_scores: print(f"Alice的成绩是 {student_scores['Alice']}") # 输出: Alice的成绩是 90
长度运算:len()
计算字符串长度:
text = "Hello, World!" print(f"字符串 '{text}' 的长度是 {len(text)}") # 输出: 字符串 'Hello, World!' 的长度是 13
列表元素数量统计:
numbers = [1, 2, 3, 4, 5] print(f"列表 {numbers} 中有 {len(numbers)} 个元素") # 输出: 列表 [1, 2, 3, 4, 5] 中有 5 个元素
元组大小:
fruits = ("apple", "banana", "cherry") print(f"元组 {fruits} 的大小是 {len(fruits)}") # 输出: 元组 ('apple', 'banana', 'cherry') 的大小是 3
字典键值对数目:
person = {"name": "Alice", "age": 25, "city": "New York"} print(f"字典中有 {len(person)} 对键值对") # 输出: 字典中有 3 对键值对
集合元素计数:
unique_numbers = {1, 2, 2, 3, 4, 4, 5} print(f"集合 {unique_numbers} 包含 {len(unique_numbers)} 个唯一元素") # 输出: 集合 {1, 2, 3, 4, 5} 包含 5 个唯一元素
范围生成器:range()
打印数字0到4:
for i in range(5): print(i) # 输出: 0 1 2 3 4
打印从1到10的偶数:
for i in range(2, 11, 2): print(i) # 输出: 2 4 6 8 10
反向打印数字9到0:
for i in range(9, -1, -1): print(i) # 输出: 9 8 7 6 5 4 3 2 1 0
使用 range() 创建列表:
numbers_list = list(range(1, 6)) print(f"创建的列表是 {numbers_list}") # 输出: 创建的列表是 [1, 2, 3, 4, 5]
结合 len() 和 range() 迭代列表:
items = ["apple", "banana", "cherry"] for i in range(len(items)): print(f"第{i+1}项是{items[i]}") # 输出: 第1项是apple 第2项是banana 第3项是cherry
切片操作
提取列表的一部分:
my_list = [0, 1, 2, 3, 4, 5] slice_of_list = my_list[1:4] print(f"切片后的列表是 {slice_of_list}") # 输出: 切片后的列表是 [1, 2, 3]
使用负索引进行切片:
my_string = "Python" reversed_slice = my_string[-3:] print(f"切片结果是 {reversed_slice}") # 输出: 切片结果是 hon
步长为2的切片:
my_tuple = (0, 1, 2, 3, 4, 5) even_elements = my_tuple[::2] print(f"每隔一个元素提取的结果是 {even_elements}") # 输出: 每隔一个元素提取的结果是 (0, 2, 4)
完全反转序列:
sequence = "abcdef" reversed_sequence = sequence[::-1] print(f"反转后的序列是 {reversed_sequence}") # 输出: 反转后的序列是 fedcba
使用切片更新列表中的部分:
letters = ['a', 'b', 'c', 'd', 'e'] letters[1:4] = ['B', 'C', 'D'] print(f"更新后的列表是 {letters}") # 输出: 更新后的列表是 ['a', 'B', 'C', 'D', 'e']
列表生成式
创建包含平方数的列表:
squares = [x**2 for x in range(1, 6)] print(f"平方数列表是 {squares}") # 输出: 平方数列表是 [1, 4, 9, 16, 25]
筛选出偶数:
even_numbers = [num for num in range(1, 11) if num % 2 == 0] print(f"偶数列表是 {even_numbers}") # 输出: 偶数列表是 [2, 4, 6, 8, 10]
将字符串转换为大写:
words = ["hello", "world", "python"] upper_words = [word.upper() for word in words] print(f"大写单词列表是 {upper_words}") # 输出: 大写单词列表是 ['HELLO', 'WORLD', 'PYTHON']
生成笛卡尔积:
pairs = [(x, y) for x in [1, 2, 3] for y in ['a', 'b']] print(f"笛卡尔积列表是 {pairs}") # 输出: 笛卡尔积列表是 [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
根据条件过滤和转换:
mixed_data = [0, "apple", 1, "banana", 2, None, 3, ""] filtered_data = [item for item in mixed_data if isinstance(item, int) and item > 0] print(f"过滤并转换后的数据是 {filtered_data}") # 输出: 过滤并转换后的数据是 [1, 2, 3]
元组定义
定义一个简单的元组:
simple_tuple = (1, 2, 3) print(f"简单元组是 {simple_tuple}") # 输出: 简单元组是 (1, 2, 3)
单元素元组需要尾随逗号:
single_element_tuple = (42,) print(f"单元素元组是 {single_element_tuple}") # 输出: 单元素元组是 (42,)
元组解包:
coordinates = (10, 20) x, y = coordinates print(f"x坐标是 {x}, y坐标是 {y}") # 输出: x坐标是 10, y坐标是 20
不可变性示例:
immutable_tuple = (1, 2, 3) try: immutable_tuple[0] = 4 # 尝试修改元组中的元素会导致错误 except TypeError as e: print(f"错误信息: {e}") # 输出: 错误信息: 'tuple' object does not support item assignment
使用元组作为字典的键:
student_scores = {(1, "Alice"): 90, (2, "Bob"): 85} print(f"Alice的成绩是 {student_scores[(1, 'Alice')]}") # 输出: Alice的成绩是 90
字典定义:使用花括号 {} 定义键值对结构的字典
创建一个简单的字典:
person = {"name": "Alice", "age": 25} print(f"字典内容: {person}") # 输出: 字典内容: {'name': 'Alice', 'age': 25}
使用 dict() 构造函数创建字典:
book = dict(title="Python编程", author="张三") print(f"书的信息: {book}") # 输出: 书的信息: {'title': 'Python编程', 'author': '张三'}
创建包含列表作为值的字典:
shopping_list = {"fruits": ["apple", "banana"], "vegetables": ["carrot", "lettuce"]} print(f"购物清单: {shopping_list}") # 输出: 购物清单: {'fruits': ['apple', 'banana'], 'vegetables': ['carrot', 'lettuce']}
创建空字典并动态添加键值对:
empty_dict = {} empty_dict["country"] = "China" print(f"国家信息: {empty_dict}") # 输出: 国家信息: {'country': 'China'}
创建具有相同值的字典:
default_values = {}.fromkeys(['height', 'width'], 0) print(f"默认尺寸: {default_values}") # 输出: 默认尺寸: {'height': 0, 'width': 0}
字典操作:如 get(), pop(), update() 方法来操作字典中的数据
使用 get() 方法获取字典中的值:
user_info = {"name": "李四", "email": "[email protected]"} email = user_info.get("email", "无邮箱信息") print(f"用户邮箱: {email}") # 输出: 用户邮箱: [email protected]
使用 pop() 方法移除并返回指定键的值:
scores = {"math": 90, "english": 85} math_score = scores.pop("math") print(f"数学成绩已移除: {math_score}") # 输出: 数学成绩已移除: 90
使用 update() 方法合并两个字典:
first_half = {"Q1": 100, "Q2": 200} second_half = {"Q3": 300, "Q4": 400} first_half.update(second_half) print(f"全年业绩: {first_half}") # 输出: 全年业绩: {'Q1': 100, 'Q2': 200, 'Q3': 300, 'Q4': 400}
清空字典所有条目:
inventory = {"apples": 30, "bananas": 45} inventory.clear() print(f"库存清空后: {inventory}") # 输出: 库存清空后: {}
检查字典中是否存在特定键:
settings = {"theme": "dark", "language": "en"} has_theme = "theme" in settings print(f"是否有主题设置: {has_theme}") # 输出: 是否有主题设置: True
文件操作:open(), read(), write() 等方法用于处理文件读写
打开文件并读取其内容:
with open('example.txt', 'r') as file: content = file.read() print(f"文件内容: {content}")
向文件写入文本:
with open('output.txt', 'w') as file: file.write("这是一个测试文件。") print("写入完成")
追加文本到文件末尾:
with open('output.txt', 'a') as file: file.write("\n这是追加的内容。") print("追加完成")
逐行读取文件内容:
with open('example.txt', 'r') as file: for line in file: print(line.strip()) # 去掉每行末尾的换行符 使用 with 语句同时打开多个文件进行读写: with open('source.txt', 'r') as src, open('destination.txt', 'w') as dest: content = src.read() dest.write(content) print("复制完成")
异常处理:使用 try...except...finally 结构来捕获并处理异常
处理文件不存在的异常:
try: with open('nonexistent_file.txt', 'r') as f: content = f.read() except FileNotFoundError as e: print(f"错误: {e}") finally: print("无论是否发生异常,都会执行此代码")
处理数值转换错误:
try: number = int("abc") except ValueError as e: print(f"错误: {e}")
处理多种异常:
try: result = 10 / 0 except ZeroDivisionError as e: print(f"除零错误: {e}") except Exception as e: print(f"其他错误: {e}")
使用 else 子句在没有异常时执行代码:
try: number = int("123") except ValueError: print("输入不是一个有效的整数") else: print(f"成功转换为整数: {number}")
在函数中使用异常处理:
def divide(a, b): try: return a / b except ZeroDivisionError: print("除数不能为零") return None result = divide(10, 0) if result is not None: print(f"结果是: {result}")
模块导入:import 或 from ... import ... 导入其他模块的功能到当前脚本中
导入整个模块:
import math print(f"圆周率: {math.pi}") # 输出: 圆周率: 3.141592653589793
从模块中导入特定功能:
from datetime import datetime current_time = datetime.now() print(f"当前时间: {current_time}") # 输出: 当前时间: 2025-02-06 14:16:00.123456
使用别名简化模块引用:
import numpy as np array = np.array([1, 2, 3]) print(f"数组: {array}") # 输出: 数组: [1 2 3]
从模块中导入所有功能(不推荐):
from os.path import * print(f"当前工作目录: {getcwd()}") # 输出: 当前工作目录: /path/to/current/working/directory
动态导入模块:
import importlib json_module = importlib.import_module('json') data = json_module.dumps({"key": "value"}) print(f"JSON字符串: {data}") # 输出: JSON字符串: {"key": "value"}
无论您是编程新手还是希望深化技能的开发者,都欢迎加入我们的学习之旅,共同交流进步!