Python语言基础详解

发布时间:2023-05-20

一、变量与数据类型

Python语言中,变量的命名需遵循一定的规则,如只能由数字、字母、下划线组成,且不能以数字开头。Python支持多种数据类型,包括整型、浮点型、布尔型、字符串、列表、元组、字典等。

# 变量命名规则示例
score_1 = 90
Score1 = 85
Score1_ = 92
# 数据类型示例
a = 10 # 整型
b = 2.5 # 浮点型
c = False # 布尔型
d = 'Hello World' # 字符串
e = [1, 2, 3] # 列表
f = (1, 2, 3) # 元组
g = {'name': 'Alice', 'age': 20} # 字典

二、条件与循环

Python语言中,条件和循环语句是非常常用的语句。条件语句用于根据条件判断是否执行某个语句块,循环语句则重复执行某个语句块。

# 条件语句示例
age = 18
if age >= 18:
    print('成年人')
else:
    print('未成年人')
# 循环语句示例
for i in range(1, 6):
    print(i)
while True:
    print('循环中')
    break # 跳出循环

三、函数与模块

函数和模块是Python语言中的两个核心概念。函数用于封装代码,可以提高代码的复用性和可读性;模块则是包含Python代码的文件,可以被其他程序引用。

# 函数示例
def add(a, b):
    return a + b
result = add(3, 5)
print(result)
# 模块示例
# 模块文件mymodule.py内容
def say_hello(name):
    print('Hello, ' + name)
# 程序文件中引用模块
import mymodule
mymodule.say_hello('Alice')

四、字符串操作

字符串操作在Python中非常常用,包括字符串连接、字符串格式化、字符串查找等。

# 字符串连接示例
str1 = 'Hello'
str2 = 'World'
result = str1 + ' ' + str2
print(result)
# 字符串格式化示例
name = 'Alice'
age = 20
result = 'My name is %s, age is %d' % (name, age)
print(result)
# 字符串查找示例
str1 = 'Hello World'
if 'World' in str1:
    print('找到了!')

五、文件操作

Python提供了丰富的文件操作函数,包括文件创建、文件打开、文件读写、文件删除等。

# 文件写操作示例
f = open('test.txt', 'w')
f.write('Hello World')
f.close()
# 文件读操作示例
f = open('test.txt', 'r')
content = f.read()
print(content)
f.close()
# 文件删除示例
import os
os.remove('test.txt')