1. Python简介Python是一种解释型、高级和通用的编程语言。它通过显著的缩进使用来强调代码的可读性。
# Hello World program
print("Hello, World!")
2.变量和数据类型变量用于存储数据值。Python支持各种数据类型,如整数、浮点数、字符串等。
# Variables and data types
x = 10 # Integer
y = 3.14 # Float
name = "Alice" # String
is_valid = True # Boolean
print(x, y, name, is_valid)
3.条件语句条件语句允许基于条件执行代码。
# Conditional statements
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
4.循环Python提供for和while循环来迭代序列或重复操作。
示例(for循环):
# For loop example
for i in range(5):
print(i)
例如(while循环):
# While loop example
count = 0
while count < 5:
print(count)
count += 1
5.函数函数是执行特定任务的可重用代码块。
# Function example
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
6.列表和字典列表用于在单个变量中存储多个项,字典以键值对的形式存储数据。
示例(列表):
# List example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
示例(字典):
# Dictionary example
person = {"name": "Alice", "age": 25}
print(person["name"], person["age"])
7. Python允许你读写文件。
范例:
# File handling example
with 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 example
try:
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 example
class 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 module
import math
print(math.sqrt(16)) # Square root
print(math.pi) # Value of Pi
实时示例:网页搜罗
# Web scraping using requests and BeautifulSoup
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for link in soup.find_all('a'):
print(link.get('href'))