自学python第二天

Python基础语法

一、变量与数据类型

1. 变量赋值

x = 10        # 整数
name = "Alice"  # 字符串
is_student = True  # 布尔值
price = 9.99    # 浮点数

2. 数据类型

数值类型:int(整数)、float(浮点数)、complex(复数)

序列类型:str(字符串)、list(列表)、tuple(元组)

映射类型:dict(字典)

集合类型:set(集合)、frozenset(不可变集合)

布尔类型:bool(True/False)

空值:None

二、条件语句

age = 18

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

注意:Python使用缩进(通常为4个空格)表示代码块,而非括号。

三、循环语句

1. for循环

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

2. while循环

count = 0
while count < 5:
    print(count)
    count += 1

3. 循环控制

break:跳出整个循环

continue:跳过当前循环,继续下一次

else:循环正常结束后执行(未被break中断)

四、函数

def add(a, b):
    """返回两个数的和"""
    return a + b

result = add(3, 5)  # 调用函数
print(result)  # 输出: 8

参数类型:

位置参数:def func(a, b)

默认参数:def func(a, b=10)

可变参数:def func(*args, **kwargs)

五、列表、元组、字典

1. 列表(List)

numbers = [1, 3, 5, 7]
numbers.append(9)  # 添加元素
print(numbers[0])  # 访问第一个元素
print(len(numbers))  # 列表长度

2. 元组(Tuple)

point = (3, 4)  # 元组用括号定义
# point[0] = 5  # 错误:元组不可修改

3. 字典(Dict)

person = {
    "name": "Alice",
    "age": 30,
    "city": "New York"
}
print(person["name"])  # 访问键对应的值
person["age"] = 31  # 修改值

六、字符串操作

text = "Hello, World!"

# 切片
print(text[0:5])  # 输出: Hello

# 常用方法
print(text.lower())  # 转为小写
print(text.replace("World", "Python"))  # 替换子串
print(len(text))  # 字符串长度

# 格式化
name = "Bob"
age = 25
print(f"我叫 {name},今年 {age} 岁。")  # f-string 格式化

七、模块与包

1. 导入模块

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

# 或只导入特定函数
from math import sqrt
print(sqrt(25))  # 输出: 5.0

# 或使用别名
import numpy as np
arr = np.array([1, 2, 3])

2. 自定义模块

创建utils.py文件:

def greet(name):
    return f"Hello, {name}!"

在主程序中导入:

from utils import greet
print(greet("Alice"))  # 输出: Hello, Alice!

八、异常处理

try:
    num = int("abc")  # 尝试将字符串转为整数
except ValueError as e:
    print(f"错误: {e}")  # 输出: 错误: invalid literal for int() with base 10: 'abc'
else:
    print("没有发生异常")
finally:
    print("无论如何都会执行")

九、文件操作

# 写入文件
with open("test.txt", "w") as f:
    f.write("Hello, Python!")

# 读取文件
with open("test.txt", "r") as f:
    content = f.read()
    print(content)  # 输出: Hello, Python!

模式:r(读取)、w(写入,覆盖)、a(追加)、b(二进制模式)

十、面向对象编程

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name}.")

# 创建对象
p1 = Person("Alice", 30)
p1.greet()  # 输出: Hello, my name is Alice.

十一、常用内置函数

函数作用
print()打印输出
len()返回对象长度或元素个数
type()返回对象类型
input()获取用户输入
int()转换为整数
str()转换为字符串
list()转换为列表
range()生成数字序列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值