公开笔记:Python语法和常用函数介绍

Python是一种高级编程语言,以其简洁、易读和强大的功能而闻名。以下是对Python语法和常用函数的详细介绍,包括大量示例。

1. 基本语法
1.1 注释
  • 单行注释:使用#

  • 多行注释:使用'''"""

# 这是一个单行注释

'''
这是一个多行注释
可以写多行内容
'''

"""
这也是一个多行注释
"""
1.2 变量和数据类型
  • 变量不需要声明类型,直接赋值即可。

  • 常见数据类型:整数(int)、浮点数(float)、字符串(str)、布尔值(bool)、列表(list)、元组(tuple)、字典(dict)、集合(set)等。

a = 10          # 整数
b = 3.14        # 浮点数
c = "Hello"     # 字符串
d = True        # 布尔值
e = [1, 2, 3]   # 列表
f = (1, 2, 3)   # 元组
g = {'key': 'value'}  # 字典
h = {1, 2, 3}   # 集合
1.3 输入输出
  • 输入:input()

  • 输出:print()

name = input("请输入你的名字: ")
print("你好, " + name)
1.4 条件语句
  • ifelifelse

age = 18
if age < 18:
    print("未成年")
elif age == 18:
    print("刚成年")
else:
    print("成年")
1.5 循环语句
  • for循环

  • while循环

# for循环
for i in range(5):
    print(i)

# while循环
count = 0
while count < 5:
    print(count)
    count += 1
1.6 函数定义
  • 使用def关键字定义函数

def greet(name):
    return "Hello, " + name

print(greet("Alice"))
1.7 类和对象
  • 使用class关键字定义类

class Dog:
    def __init__(self, name):
        self.name = name

    def bark(self):
        return "Woof!"

my_dog = Dog("Buddy")
print(my_dog.bark())
2. 常用函数
2.1 字符串操作
  • len():返回字符串长度

  • str.upper():将字符串转换为大写

  • str.lower():将字符串转换为小写

  • str.strip():去除字符串两端的空白字符

  • str.split():将字符串按指定分隔符分割成列表

  • str.join():将列表中的元素连接成字符串

s = "  Hello, World!  "
print(len(s))           # 输出: 15
print(s.upper())        # 输出: "  HELLO, WORLD!  "
print(s.lower())        # 输出: "  hello, world!  "
print(s.strip())        # 输出: "Hello, World!"
print(s.split(","))     # 输出: ['  Hello', ' World!  ']
print("-".join(["a", "b", "c"]))  # 输出: "a-b-c"
2.2 列表操作
  • len():返回列表长度

  • list.append():在列表末尾添加元素

  • list.insert():在指定位置插入元素

  • list.remove():移除列表中第一个匹配的元素

  • list.pop():移除并返回列表中指定位置的元素

  • list.sort():对列表进行排序

  • list.reverse():反转列表中的元素

my_list = [1, 2, 3]
my_list.append(4)       # [1, 2, 3, 4]
my_list.insert(1, 5)    # [1, 5, 2, 3, 4]
my_list.remove(2)       # [1, 5, 3, 4]
my_list.pop(1)          # 返回5, 列表变为[1, 3, 4]
my_list.sort()          # [1, 3, 4]
my_list.reverse()       # [4, 3, 1]
2.3 字典操作
  • len():返回字典中键值对的数量

  • dict.keys():返回字典中所有的键

  • dict.values():返回字典中所有的值

  • dict.items():返回字典中所有的键值对

  • dict.get():返回指定键的值,如果键不存在则返回默认值

  • dict.update():更新字典中的键值对

my_dict = {'name': 'Alice', 'age': 25}
print(len(my_dict))            # 输出: 2
print(my_dict.keys())          # 输出: dict_keys(['name', 'age'])
print(my_dict.values())        # 输出: dict_values(['Alice', 25])
print(my_dict.items())         # 输出: dict_items([('name', 'Alice'), ('age', 25)])
print(my_dict.get('name'))     # 输出: Alice
print(my_dict.get('gender', 'Unknown'))  # 输出: Unknown
my_dict.update({'age': 26})    # 更新age为26
2.4 集合操作
  • len():返回集合中元素的数量

  • set.add():向集合中添加元素

  • set.remove():移除集合中的元素

  • set.union():返回两个集合的并集

  • set.intersection():返回两个集合的交集

  • set.difference():返回两个集合的差集

my_set = {1, 2, 3}
my_set.add(4)           # {1, 2, 3, 4}
my_set.remove(2)        # {1, 3, 4}
new_set = {3, 4, 5}
print(my_set.union(new_set))         # 输出: {1, 3, 4, 5}
print(my_set.intersection(new_set))  # 输出: {3, 4}
print(my_set.difference(new_set))    # 输出: {1}
2.5 文件操作
  • open():打开文件

  • file.read():读取文件内容

  • file.write():向文件写入内容

  • file.close():关闭文件

# 写入文件
with open("example.txt", "w") as file:
    file.write("Hello, World!")

# 读取文件
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # 输出: Hello, World!
2.6 数学函数
  • abs():返回绝对值

  • round():四舍五入

  • min():返回最小值

  • max():返回最大值

  • sum():返回求和结果

  • pow():返回幂运算结果

print(abs(-10))          # 输出: 10
print(round(3.14159, 2)) # 输出: 3.14
print(min(1, 2, 3))      # 输出: 1
print(max(1, 2, 3))      # 输出: 3
print(sum([1, 2, 3]))    # 输出: 6
print(pow(2, 3))         # 输出: 8
2.7 时间和日期
  • time.time():返回当前时间的时间戳

  • time.sleep():暂停程序执行指定的秒数

  • datetime.datetime.now():返回当前日期和时间

import time
from datetime import datetime

print(time.time())          # 输出: 当前时间戳
time.sleep(2)               # 暂停2秒
print(datetime.now())       # 输出: 当前日期和时间
2.8 随机数
  • random.randint():返回指定范围内的随机整数

  • random.choice():从序列中随机选择一个元素

  • random.shuffle():将序列中的元素随机排序

import random

print(random.randint(1, 10))  # 输出: 1到10之间的随机整数
print(random.choice([1, 2, 3]))  # 输出: 随机选择1, 2, 或3
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)  # 输出: 随机排序后的列表
3. 高级特性
3.1 列表推导式
  • 用于快速生成列表

squares = [x**2 for x in range(10)]
print(squares)  # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
3.2 生成器
  • 使用yield关键字生成迭代器

def my_generator():
    yield 1
    yield 2
    yield 3

gen = my_generator()
print(next(gen))  # 输出: 1
print(next(gen))  # 输出: 2
print(next(gen))  # 输出: 3
3.3 装饰器
  • 用于修改或扩展函数的行为

def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# 输出:
# Before function call
# Hello!
# After function call
3.4 上下文管理器
  • 使用with语句管理资源

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
4. 异常处理
  • 使用tryexceptfinally处理异常

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以零")
finally:
    print("执行完毕")
5. 模块和包
  • 使用import导入模块

  • 使用from ... import ...导入特定函数或类

import math
from math import sqrt

print(math.sqrt(16))  # 输出: 4.0
print(sqrt(16))       # 输出: 4.0
6. 常用内置模块
  • os:操作系统接口

  • sys:系统相关的参数和函数

  • json:处理JSON数据

  • re:正则表达式操作

import os
import sys
import json
import re

print(os.getcwd())  # 输出: 当前工作目录
print(sys.argv)     # 输出: 命令行参数
data = '{"name": "Alice", "age": 25}'
parsed_data = json.loads(data)
print(parsed_data['name'])  # 输出: Alice
match = re.search(r'\d+', 'abc123def')
print(match.group())  # 输出: 123

总结

Python的语法简洁明了,功能强大,适合各种编程任务。通过掌握基本语法和常用函数,你可以快速上手Python编程,并利用其丰富的库和框架进行开发。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值