网站首页 > 技术文章 正文
变量和数据类型
变量
在 Python 中,你不需要显式声明变量类型。变量名可以直接赋值。
x = 10
y = "Hello, World!"
z = 3.14
数据类型
数字:整数(int)、浮点数(float)、复数(complex)
字符串:单引号或双引号表示
列表:有序集合,可以包含不同类型的元素
元组:有序且不可变的集合
字典:键值对的集合
集合:无序且不重复的元素集合
布尔值:True 和 False
# 数字
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
# 字符串
s = "Hello, World!"
# 列表
lst = [1, 2, 3, "four", 5.0]
# 元组
tup = (1, 2, 3, "four", 5.0)
# 字典
dic = {"name": "Alice", "age": 25}
# 集合
set_ = {1, 2, 3, 4, 5}
# 布尔值
is_true = True
is_false = False
控制结构
条件语句
使用 if、elif 和 else 来实现条件判断。
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
循环
for 循环:遍历序列中的每个元素。
while 循环:当条件为真时继续执行。
# for 循环
for i in range(5):
print(i)
# while 循环
count = 0
while count < 5:
print(count)
count += 1
跳出循环
break:立即退出循环。
continue:跳过当前循环体中剩余的语句,继续下一次循环。
# break 示例
for i in range(10):
if i == 5:
break
print(i)
# continue 示例
for i in range(10):
if i % 2 == 0:
continue
print(i)
函数
定义函数
使用 def 关键字来定义函数。
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
参数
位置参数:按顺序传递参数。
关键字参数:通过参数名传递参数。
默认参数:给参数设置默认值。
可变参数:使用 *args 和 **kwargs 传递多个参数。
def add(a, b):
return a + b
print(add(3, 4))
def say_hello(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(say_hello("Alice"))
print(say_hello("Bob", "Hi"))
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4))
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
模块
导入模块
使用 import 关键字导入模块。
import math
print(math.sqrt(16))
从模块导入特定功能
使用 from ... import ... 语法。
from math import sqrt
print(sqrt(16))
自定义模块
创建一个 Python 文件(如 mymodule.py),并在其中定义一些函数或变量。
# mymodule.py
def hello(name):
return f"Hello, {name}!"
然后在其他文件中导入并使用它。
import mymodule
print(mymodule.hello("Alice"))
异常处理
使用 try、except、else 和 finally 来处理异常。
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("This will always execute")
文件操作
读取文件
使用 open 函数打开文件,并使用 read 方法读取内容。
with open('example.txt', 'r') as file:
content = file.read()
print(content)
写入文件
使用 write 方法写入内容。
with open('example.txt', 'w') as file:
file.write("Hello, World!")
列表推导式
列表推导式是一种简洁的方式来创建列表。
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
字典推导式
字典推导式用于创建字典。
squares_dict = {x: x**2 for x in range(10)}
print(squares_dict) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
集合推导式
集合推导式用于创建集合。
squares_set = {x**2 for x in range(10)}
print(squares_set) # 输出: {0, 1, 64, 4, 36, 9, 16, 81, 49, 25}
类和对象
定义类
使用 class 关键字定义类。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# 创建对象
p = Person("Alice", 25)
print(p.greet())
总结
以上是 Python 基础语法的详细讲解,涵盖了变量、数据类型、控制结构、函数、模块、异常处理、文件操作以及面向对象编程等内容。

猜你喜欢
- 2024-12-13 Python数据类型字符串的几种表示形式
- 2024-12-13 轻松掌握!Python 基本语法与核心数据类型全解析
- 2024-12-13 Python注释方式有哪些
- 2024-12-13 Word 神器 python-docx
- 2024-12-13 万字干货,Python语法大合集,一篇文章带你入门
- 2024-12-13 Python之open()函数
- 2024-12-13 编程语言python:数据类型
- 2024-12-13 Python基础语法到高级概念
- 2024-12-13 Python字符串单引号('...')和双引号("...")的区别
- 2024-12-13 超详细python基础语法(每个都有例子)
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)