Python学习入门(1)——基础语句

时间:2024-04-13 11:31:03

        在Python中,有一系列基础语句和结构是任何初学者需要掌握的。这些基础语句包括数据类型、控制流语句、函数定义等。下面,将概述这些基本语句的分类和用法:

1. 数据类型和变量赋值

        Python拥有多种数据类型,这些基础类型包括整数、浮点数、字符串、布尔值等。

x = 10          # 整数
y = 20.5        # 浮点数
name = "Alice"  # 字符串
is_valid = True # 布尔值

2. 数据结构

        Python内置了多种复杂的数据结构,如列表、元组、字典和集合。

my_list = [1, 2, 3]               # 列表
my_tuple = (1, 2, 3)              # 元组
my_dict = {'key': 'value'}        # 字典
my_set = {1, 2, 3}                # 集合

3. 控制流语句

        控制流语句用于编写条件逻辑、循环等。

条件语句
if x < y:
    print("x is less than y")
elif x > y:
    print("x is greater than y")
else:
    print("x and y are equal")
循环
# for循环
for i in range(5):
    print(i)

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

4. 函数定义

        函数是用于封装代码的可重用块。

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

5. 输入和输出

        输入和输出是与用户进行交互的基本方式。

# 输出
print("Hello, World!")

# 输入
user_name = input("Enter your name: ")

6. 文件操作

        文件操作允许读写文件。

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

# 读取文件
with open("file.txt", "r") as file:
    content = file.read()
    print(content)

7. 错误和异常处理

        错误和异常处理是任何健壮程序的重要组成部分。

try:
    # 尝试执行的代码
    result = 10 / 0
except ZeroDivisionError:
    # 发生特定异常时执行的代码
    print("Divided by zero!")
finally:
    # 无论是否发生异常都会执行的代码
    print("This is executed last.")

8. 模块和包

        在Python中,模块和包用于组织和重用代码。

# 导入模块
import math
print(math.sqrt(16))

# 从模块导入特定函数
from math import sqrt
print(sqrt(16))

9. 列表推导式和生成器表达式

        Python支持非常强大的列表推导式(list comprehensions)和生成器表达式(generator expressions),它们提供了一种简洁的方法来创建列表或其他类型的序列,非常适合进行快速的序列转换和计算。

# 列表推导式
squares = [x**2 for x in range(10)]

# 条件列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# 生成器表达式
sum_of_squares = sum(x**2 for x in range(10))

10. 装饰器

        装饰器是修改函数或类的功能的一种优雅方式。它们在不改变原有函数定义的情况下,给函数增加新的功能。

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

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

say_hello()

11. 类和对象

        Python是一种面向对象的编程语言,支持类的继承、封装和多态等面向对象的基本特征。

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

    def speak(self):
        return "Woof!"

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

    def speak(self):
        return "Meow!"

# 使用类
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak())
print(cat.speak())

12. 异常自定义和抛出

        除了处理内置的异常外,Python允许你定义和抛出自定义的异常,这对于创建可预测的错误处理行为非常有用。

class MyError(Exception):
    pass

def check_value(x):
    if x < 0:
        raise MyError("Negative value")
    return x

try:
    result = check_value(-10)
except MyError as e:
    print(e)

13. 上下文管理器和with语句

  with语句用于包裹执行需要设置前置和后置操作的代码块,比如文件操作,这样可以确保如文件这样的资源正确地被打开和关闭。

class ManagedFile:
    def __init__(self, name):
        self.name = name
    def __enter__(self):
        self.file = open(self.name, 'w')
        return self.file
    def __exit__(self, exc_type, exc_value, traceback):
        if self.file:
            self.file.close()

with ManagedFile('hello.txt') as f:
    f.write('Hello, world!')