Python 是一种广泛使用的高级编程语言,以其简洁易读、语法优雅而著称。以下是 Python 基础语法的简要介绍,适合初学者入门:
- 变量和数据类型
变量
变量用于存储数据值。
Python 是动态类型语言,变量类型在赋值时自动确定。
python
x = 10 # 整数
y = 3.14 # 浮点数
z = “Hello, World!” # 字符串
数据类型
整数 (int): 10, -5
浮点数 (float): 3.14, -0.01
字符串 (str): “Hello”, ‘Python’
布尔值 (bool): True, False
列表 (list): [1, 2, 3], [“a”, “b”, “c”]
元组 (tuple): (1, 2, 3), (“a”, “b”, “c”)
字典 (dict): {“name”: “Alice”, “age”: 25}, dict(name=“Alice”, age=25)
集合 (set): {1, 2, 3}, {“a”, “b”, “c”} - 控制结构
条件语句
使用 if, elif, else 进行条件判断。
python
if x > 10:
print(“x is greater than 10”)
elif x == 10:
print(“x is equal to 10”)
else:
print(“x is less than 10”)
循环
使用 for 和 while 进行循环。
python
for 循环
for i in range(5):
print(i)
while 循环
count = 0
while count < 5:
print(count)
count += 1
3. 函数
使用 def 定义函数。
python
def greet(name):
print(f"Hello, {name}!")
greet(“Alice”)
4. 类和对象
使用 class 定义类。
类的实例称为对象。
python
class Dog:
def init(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
dog = Dog(“Buddy”, 3)
dog.bark()
5. 模块和包
Python 模块是一个包含 Python 代码的文件,文件扩展名为 .py。
使用 import 语句导入模块。
python
import math
print(math.sqrt(16)) # 输出 4.0
导入特定函数
from math import sqrt
print(sqrt(16)) # 输出 4.0
6. 文件操作
使用内置函数进行文件读写。
python
写文件
with open(“example.txt”, “w”) as file:
file.write(“Hello, World!\n”)
读文件
with open(“example.txt”, “r”) as file:
content = file.read()
print(content) # 输出 Hello, World!
7. 异常处理
使用 try, except, else, finally 进行异常处理。
python
try:
result = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)
else:
print(f"Result: {result}")
finally:
print(“Execution of try/except block is finished.”)
8. 输入输出
使用 input() 函数获取用户输入。
使用 print() 函数输出结果。
python
name = input("Enter your name: “)
print(f"Hello, {name}!”)
这些是 Python 编程的基础语法和概念。通过学习和实践这些基础知识,你可以逐步掌握更高级的编程技巧。祝你学习愉快!