Python 是一种广泛使用的高级编程语言,因其易读性和简洁的语法,在数据分析、机器学习、Web开发、自动化脚本等领域有着广泛应用。Python 的设计哲学强调代码的可读性,使其成为初学者的理想选择。
Python 安装与环境搭建要开始使用 Python,首先需要安装 Python 编译器。Python 可在多种操作系统上运行,包括 Windows、macOS、Linux 等。以下是安装 Python 的步骤:
- 访问 Python 官方网站(https://www.python.org/downloads/)下载最新版本的 Python。
- 运行下载的安装程序。对于 Windows 用户,下载后运行
.exe
文件;对于 macOS 用户,下载后打开.pkg
文件。 - 在安装过程中,勾选
Add Python to PATH
选项,这将确保 Python 命令可以在命令行中调用。对于 macOS 和 Linux 用户,这一步是默认行为。 - 安装完成后,打开命令行工具(如 Windows 的命令提示符,macOS 和 Linux 的 Terminal)并输入
python --version
或python3 --version
验证安装是否成功。
Python 的包管理工具是 pip
,用于安装和管理 Python 的第三方库。确保安装了 pip
,可以通过命令 pip --version
来检查。
安装完 Python 后,可以选择一个编辑器来编写代码。Python 官方推荐使用 IDLE,它是自带的集成开发环境。还有许多其他开发工具,如 Visual Studio Code、PyCharm、Jupyter Notebook 等。
Python 基本语法和概念变量与类型
Python 中的变量不需要显式声明类型,类型由赋值决定。Python 有多种基本数据类型,包括整型(int)、浮点型(float)、字符串(str)、布尔型(bool)等。
变量赋值
a = 10 # 整型
b = 3.14 # 浮点型
c = "Hello, World!" # 字符串
d = True # 布尔型
变量类型检查
print(type(a)) # 输出: <class 'int'>
print(type(b)) # 输出: <class 'float'>
print(type(c)) # 输出: <class 'str'>
print(type(d)) # 输出: <class 'bool'>
数据类型转换
Python 提供了多种将数据从一种类型转换为另一种类型的方法,如 int()
, float()
, str()
, bool()
。
# 整型转换
num_str = "123"
num = int(num_str)
print(num) # 输出: 123
# 浮点型转换
float_num = float(num)
print(float_num) # 输出: 123.0
# 字符串转换
str_num = str(num)
print(str_num) # 输出: 123
# 布尔型转换
bool_val = bool(num)
print(bool_val) # 输出: True
数字运算
Python 支持基本算术运算,如加法、减法、乘法、除法等。
a = 10
b = 3
# 加法
sum = a + b
print(sum) # 输出: 13
# 减法
diff = a - b
print(diff) # 输出: 7
# 乘法
product = a * b
print(product) # 输出: 30
# 除法
quotient = a / b
print(quotient) # 输出: 3.3333333333333335
# 取模
mod = a % b
print(mod) # 输出: 1
字符串操作
字符串是 Python 中常用的数据类型,提供了丰富的操作方法。
s = "Hello, World!"
# 字符串拼接
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2 + "!"
print(s3) # 输出: Hello, World!
# 字符串长度
print(len(s)) # 输出: 13
# 字符串索引
print(s[0]) # 输出: H
print(s[-1]) # 输出: !
# 字符串切片
print(s[0:5]) # 输出: Hello
print(s[7:]) # 输出: World!
# 字符串格式化
name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name, age)
print(message) # 输出: My name is Alice and I am 25 years old.
# f-string
message = f"My name is {name} and I am {age} years old."
print(message) # 输出: My name is Alice and I am 25 years old.
列表与元组
列表和元组是 Python 中用于存储有序集合的常用数据结构。
列表
# 创建列表
list1 = [1, 2, 3, 4]
list2 = ["apple", "banana", "cherry"]
# 列表操作
print(list1[0]) # 输出: 1
list1.append(5) # 添加元素
list1.remove(2) # 删除元素
list1[1] = 3 # 修改元素
print(list1) # 输出: [1, 3, 3, 5]
# 列表切片
print(list1[1:3]) # 输出: [3, 3]
元组
# 创建元组
tuple1 = (1, 2, 3, 4)
tuple2 = ("apple", "banana", "cherry")
# 元组操作
print(tuple1[0]) # 输出: 1
# 元组是不可变的,不能添加、删除或修改元素
print(tuple1) # 输出: (1, 2, 3, 4)
# 元组切片
print(tuple1[1:3]) # 输出: (2, 3)
字典
字典是 Python 中用于存储键值对的数据结构。
# 创建字典
dict1 = {"name": "Alice", "age": 25, "city": "Beijing"}
dict2 = dict(name="Bob", age=30, city="Shanghai")
# 字典操作
print(dict1["name"]) # 输出: Alice
dict1["name"] = "Charlie" # 修改元素
dict1["country"] = "China" # 添加元素
print(dict1) # 输出: {'name': 'Charlie', 'age': 25, 'city': 'Beijing', 'country': 'China'}
# 删除元素
del dict1["age"]
print(dict1) # 输出: {'name': 'Charlie', 'city': 'Beijing', 'country': 'China'}
# 字典遍历
for key, value in dict1.items():
print(f"{key}: {value}")
# 输出:
# name: Charlie
# city: Beijing
# country: China
控制流语句
控制流语句用于控制程序的执行流程,包括条件语句和循环语句。
条件语句
条件语句允许基于条件执行不同的代码块。Python 中的条件语句主要有 if
, elif
, else
。
age = 18
if age < 18:
print("未成年")
elif age >= 18 and age < 60:
print("成年人")
else:
print("老年人")
# 输出: 成年人
循环语句
循环语句用于重复执行一段代码,直到满足特定条件为止。Python 中的循环语句主要有 for
和 while
。
for 循环
for i in range(5):
print(i)
# 输出:
# 0
# 1
# 2
# 3
# 4
# 带有起始和结束的范围
for i in range(1, 6):
print(i)
# 输出:
# 1
# 2
# 3
# 4
# 5
# 通过迭代器
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 输出:
# apple
# banana
# cherry
while 循环
count = 0
while count < 5:
print(count)
count += 1
# 输出:
# 0
# 1
# 2
# 3
# 4
函数
函数是 Python 中可重用的代码块,用于完成特定任务。定义函数时使用 def
关键字。
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # 输出: Hello, Alice!
函数参数
函数参数允许在调用函数时传递值。
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 输出: 8
默认参数
函数可以定义默认参数值,当调用函数时没有提供相应的参数时就会使用默认值。
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # 输出: Hello, Guest!
greet("Alice") # 输出: Hello, Alice!
变量作用域
Python 中有局部变量和全局变量两种变量作用域。
局部变量
def func():
x = 10 # 局部变量
print(x)
func() # 输出: 10
print(x) # NameError: name 'x' is not defined
全局变量
x = 10 # 全局变量
def func():
print(x)
func() # 输出: 10
文件操作
文件操作是 Python 中的重要功能之一,用于读取和写入文件。
# 写入文件
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is an example file.\n")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 输出:
# Hello, World!
# This is an example file.
异常处理
异常处理是编程中非常重要的部分,用于捕获和处理程序运行时发生的错误。
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"除数不能为零: {e}")
finally:
print("执行完成")
# 输出:
# 除数不能为零: division by zero
# 执行完成
模块与包
模块是 Python 中的一组相关函数和变量的集合,可以被其他程序导入并使用。包则是模块的集合,可以包含子包和模块。
import math
print(math.sqrt(16)) # 输出: 4.0
面向对象编程
面向对象编程(OOP)是 Python 中的重要特性之一,通过类和对象实现代码的封装、继承和多态。
# 定义类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
# 创建对象
person1 = Person("Alice", 25)
person1.introduce() # 输出: My name is Alice and I am 25 years old.
继承
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def study(self, subject):
print(f"{self.name} is studying {subject}.")
student1 = Student("Bob", 20, 3)
student1.introduce() # 输出: My name is Bob and I am 20 years old.
student1.study("Python") # 输出: Bob is studying Python.
多态
class Teacher(Person):
def teach(self, subject):
print(f"{self.name} is teaching {subject}.")
teacher1 = Teacher("Charlie", 40)
teacher1.introduce() # 输出: My name is Charlie and I am 40 years old.
teacher1.teach("Math") # 输出: Charlie is teaching Math.
实践示例
计算阶乘
编写一个函数 factorial(n)
,计算 n
的阶乘。
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # 输出: 120
列表排序
编写一个函数 sort_list(lst)
,对列表进行排序。
def sort_list(lst):
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst
random_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_list = sort_list(random_list)
print(sorted_list) # 输出: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
文件读写
编写一个函数 read_lines(filename)
,读取文件中的每一行,并返回行列表。
def read_lines(filename):
with open(filename, "r") as file:
lines = file.readlines()
return lines
lines = read_lines("example.txt")
for line in lines:
print(line.strip())
# 输出:
# Hello, World!
# This is an example file.
通过以上内容,我们全面介绍了 Python 编程的基本概念和语法,包括变量与类型、控制流语句、函数、文件操作、异常处理、面向对象编程等。希望这些知识能够帮助你更好地理解和使用 Python 编程语言。
共同學習,寫下你的評論
評論加載中...
作者其他優質文章