Python编程笔记

B站影视 电影资讯 2025-03-09 20:34 2

摘要:# Variables and data typesx = 10 # Integery = 3.14 # Floatname = "Alice" # Stringis_valid = True # Booleanprint(x, y, name, is_val

1. Python简介Python是一种解释型、高级和通用的编程语言。它通过显著的缩进使用来强调代码的可读性。

# Hello World programprint("Hello, World!")

2.变量和数据类型变量用于存储数据值。Python支持各种数据类型,如整数、浮点数、字符串等。

# Variables and data typesx = 10 # Integery = 3.14 # Floatname = "Alice" # Stringis_valid = True # Booleanprint(x, y, name, is_valid)

3.条件语句条件语句允许基于条件执行代码。

# Conditional statementsage = 18if age >= 18: print("You are an adult.")else: print("You are a minor.")

4.循环Python提供for和while循环来迭代序列或重复操作。

示例(for循环):

# For loop examplefor i in range(5): print(i)# While loop examplecount = 0while count

5.函数函数是执行特定任务的可重用代码块。

# Function exampledef greet(name): return f"Hello, {name}!"print(greet("Alice"))

6.列表和字典列表用于在单个变量中存储多个项,字典以键值对的形式存储数据。

示例(列表):

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

示例(字典):

# Dictionary exampleperson = {"name": "Alice", "age": 25}print(person["name"], person["age"])

7. Python允许你读写文件。

范例:

# File handling examplewith open("example.txt", "w") as file: file.write("Hello, File!")with open("example.txt", "r") as file: content = file.read print(content)

8.异常处理使用try、except和finally块优雅地处理错误。

# Exception handling exampletry: num = int(input("Enter a number: ")) print(10 / num)except ValueError: print("Invalid input! Please enter a number.")except zeroDivisionError: print("Cannot divide by zero.")finally: print("Execution complete.")

9. Python支持使用类和对象进行面向对象编程。

# Class and object exampleclass Person: def __init__(self, name, age): self.name = name self.age = age def introduce(self): return f"My name is {self.name} and I am {self.age} years old."person1 = Person("Alice", 25)print(person1.introduce)

10.库和模块Python拥有丰富的库生态系统,可用于各种任务。

# Using the math moduleimport mathprint(math.sqrt(16)) # Square rootprint(math.pi) # Value of Pi

实时示例:网页搜罗

# Web scraping using requests and BeautifulSoupimport requestsfrom bs4 import BeautifulSoupurl = "https://example.com"response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")for link in soup.find_all('a'): print(link.get('href'))

来源:自由坦荡的湖泊AI

相关推荐