Python基础知识汇总

Python基础知识

控制结构

条件语句

age = 20
if age >= 18:
    print("成年人")
elif age >= 12:
    print("青少年")
else:
    print("儿童")

循环语句

For循环
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)
While循环
i = 1
while i < 6:
    print(i)
    i += 1

函数

def greet(name="World"):
    print(f"Hello, {name}!")

greet("Alice")  # 输出: Hello, Alice!
greet()         # 输出: Hello, World!

数据结构

列表(Lists)

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出: [1, 2, 3, 4]

元组(Tuples)

my_tuple = (1, 2, 3)
print(my_tuple[0])  # 输出: 1

字典(Dictionaries)

my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"])  # 输出: Alice

集合(Sets)

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # 输出: {1, 2, 3, 4}

模块和包

导入模块:

import math
print(math.sqrt(16))  # 输出: 4.0

创建包:在文件夹内放置__init__.py文件。

异常处理

try:
    result = 10 / 0
except ZeroDivisionError:
    print("除数不能为零")
finally:
    print("执行完毕")

文件操作

读取文件:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

写入文件:

with open('example.txt', 'w') as file:
    file.write("这是一个测试文本。")

常用标准库

os

提供操作系统相关功能。

import os
print(os.getcwd())  # 打印当前工作目录

sys

访问与Python解释器紧密相关的变量和函数。

import sys
print(sys.version)  # 打印Python版本信息

datetime

处理日期和时间。

from datetime import datetime
now = datetime.now()
print(now)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值