1. 首页 > IT综合教程 > 正文

it教程FG118-Python编程基础

1. Python概述

Python是一种高级编程语言,以其简洁的语法和丰富的库而闻名。Python广泛应用于Web开发、数据科学、人工智能、自动化脚本等领域。更多学习教程www.fgedu.net.cn

生产环境风哥建议:Python是一种功能强大的编程语言,适合快速开发和原型设计。

2. Python安装

Python可以在多个平台上安装,包括Windows、Linux和macOS。

2.1 在Linux上安装Python

# 检查系统是否已安装Python
$ python3 –version

# 如果未安装Python,使用apt安装
$ sudo apt update
$ sudo apt install python3 python3-pip python3-venv

# 验证安装
$ python3 –version
Python 3.8.10

$ pip3 –version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)

2.2 在Windows上安装Python

  1. 访问Python官方网站:https://www.python.org/downloads/windows/
  2. 下载适合您系统的Python安装包
  3. 运行安装包,勾选”Add Python to PATH”选项
  4. 点击”Install Now”按钮完成安装
  5. 打开命令提示符,输入python --version验证安装

3. Python基础语法

Python的语法简洁明了,使用缩进来表示代码块。

3.1 Hello World

# 第一个Python程序
print(“Hello, World!”)

# 运行程序
$ python3 hello.py
Hello, World!

3.2 注释

# 这是单行注释

“””
这是多行注释
可以跨越多行
“””

print(“Hello, World!”) # 这也是注释

4. Python数据类型

Python支持多种数据类型,包括:

4.1 数字

# 整数
x = 10
print(type(x)) #

# 浮点数
y = 3.14
print(type(y)) #

# 复数
z = 1 + 2j
print(type(z)) #

4.2 字符串

# 字符串
s = “Hello, Python!”
print(type(s)) #

# 字符串操作
print(s[0]) # H
print(s[0:5]) # Hello
print(s.upper()) # HELLO, PYTHON!
print(s.lower()) # hello, python!
print(s.replace(“Python”, “World”)) # Hello, World!

4.3 列表

# 列表
lst = [1, 2, 3, 4, 5]
print(type(lst)) #

# 列表操作
lst.append(6) # 添加元素
print(lst) # [1, 2, 3, 4, 5, 6]

lst.remove(3) # 删除元素
print(lst) # [1, 2, 4, 5, 6]

print(lst[0]) # 访问元素
print(lst[1:3]) # 切片

4.4 字典

# 字典
d = {“name”: “Alice”, “age”: 30, “city”: “New York”}
print(type(d)) #

# 字典操作
print(d[“name”]) # 访问值

# 添加键值对
d[“email”] = “alice@fgedu.net.cn”
print(d) # {‘name’: ‘Alice’, ‘age’: 30, ‘city’: ‘New York’, ’email’: ‘alice@fgedu.net.cn’}

# 删除键值对
del d[“age”]
print(d) # {‘name’: ‘Alice’, ‘city’: ‘New York’, ’email’: ‘alice@fgedu.net.cn’}

5. Python控制流

Python的控制流语句包括条件语句和循环语句。

5.1 条件语句

# 条件语句
x = 10

if x > 0:
print(“x is positive”)
elif x < 0: print("x is negative") else: print("x is zero")

5.2 for循环

# for循环
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)

# 输出:
# apple
# banana
# cherry

# 使用range()
for i in range(5):
print(i)

# 输出:
# 0
# 1
# 2
# 3
# 4

5.3 while循环

# while循环
i = 0
while i < 5: print(i) i += 1 # 输出: # 0 # 1 # 2 # 3 # 4

6. Python函数

函数是一段可重用的代码块,用于执行特定的任务。

6.1 定义函数

# 定义函数
def greet(name):
“””This function greets the person passed in as a parameter”””
print(f”Hello, {name}!”)

# 调用函数
greet(“Alice”) # Hello, Alice!

# 带返回值的函数
def add(a, b):
“””This function adds two numbers”””
return a + b

result = add(3, 5)
print(result) # 8

6.2 默认参数

# 默认参数
def greet(name, message=”Hello”):
print(f”{message}, {name}!”)

greet(“Alice”) # Hello, Alice!
greet(“Bob”, “Hi”) # Hi, Bob!

7. Python模块

模块是Python代码的集合,可以被其他程序导入和使用。

7.1 导入模块

# 导入模块
import math

print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0

# 导入模块的特定部分
from math import pi, sqrt

print(pi) # 3.141592653589793
print(sqrt(16)) # 4.0

# 导入模块并指定别名
import math as m

print(m.pi) # 3.141592653589793
print(m.sqrt(16)) # 4.0

7.2 创建模块

# 创建模块(my_module.py)
def greet(name):
print(f”Hello, {name}!”)

def add(a, b):
return a + b

# 使用模块
import my_module

my_module.greet(“Alice”) # Hello, Alice!
result = my_module.add(3, 5)
print(result) # 8

8. Python异常处理

异常处理用于捕获和处理程序运行时的错误。

8.1 try-except语句

# 异常处理
try:
x = int(input(“Enter a number: “))
print(f”You entered: {x}”)
except ValueError:
print(“Invalid input. Please enter a number.”)

# 处理多个异常
try:
x = int(input(“Enter a number: “))
y = 10 / x
print(f”10 / {x} = {y}”)
except ValueError:
print(“Invalid input. Please enter a number.”)
except ZeroDivisionError:
print(“Cannot divide by zero.”)

8.2 finally语句

# finally语句
try:
x = int(input(“Enter a number: “))
y = 10 / x
print(f”10 / {x} = {y}”)
except ValueError:
print(“Invalid input. Please enter a number.”)
except ZeroDivisionError:
print(“Cannot divide by zero.”)
finally:
print(“This will always execute.”)
风哥风哥提示:Python是一种易学易用的编程语言,适合初学者入门,同时也足够强大,可以用于复杂的企业级应用开发。

生产环境风哥建议:

  • 使用虚拟环境隔离项目依赖
  • 遵循PEP 8代码风格指南
  • 编写清晰的文档和注释
  • 使用版本控制工具管理代码
  • 编写单元测试确保代码质量

更多学习教程公众号风哥教程itpux_com

author:www.itpux.com

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息