Python 是一门简单而强大的编程语言,适合初学者入门。下面是一个简要的 Python 基础教程,涵盖了一些基本概念和语法。

1. 安装 Python

首先,你需要在你的计算机上安装 Python。你可以从 [Python 官网](https://www.python.org/) 下载最新版本的 Python,并按照说明进行安装。

2. 编写你的第一个 Python 程序

使用文本编辑器创建一个新文件,文件扩展名为 .py,例如 hello.py,然后在文件中输入以下代码:
print("Hello, World!")

保存文件后,使用命令行进入文件所在的目录,运行:
python hello.py

你将在命令行中看到输出:Hello, World!。

3. 变量和数据类型
# 变量赋值
name = "John"
age = 25
height = 1.75

# 打印变量
print("Name:", name)
print("Age:", age)
print("Height:", height)

4. 控制流程

4.1 条件语句
# 条件语句
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

4.2 循环语句
# 循环语句
for i in range(5):
    print(i)

# while 循环
count = 0
while count < 5:
    print(count)
    count += 1

5. 函数
# 函数定义
def greet(name):
    return "Hello, " + name + "!"

# 函数调用
result = greet("Alice")
print(result)

6. 列表和字典
# 列表
fruits = ["apple", "banana", "orange"]
print(fruits[0])  # 输出: apple

# 字典
person = {"name": "Bob", "age": 30, "city": "New York"}
print(person["age"])  # 输出: 30

7. 异常处理
# 异常处理
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero")

8. 文件操作
# 文件操作
with open("example.txt", "w") as file:
    file.write("Hello, File!")

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

9. 模块和包

创建一个 calculator.py 文件:
# calculator.py
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

然后在另一个文件中使用这个模块:
# main.py
import calculator

result = calculator.add(5, 3)
print(result)

这只是一个简要的入门教程。如果你想深入学习 Python,建议查阅更详细的教程和官方文档,例如 [Python 官方文档](https://docs.python.org/3/)。


转载请注明出处:http://www.zyzy.cn/article/detail/13307/Python 基础