《Python编程:从入门到实践》:基础知识

BBigSun 评论68阅读模式

康复训练,仅供参考。
复习一下基础的语法知识,夹带了一些个人私货。
这是一本非常适合新手小白的书籍。强烈推荐,可以在“微信读书”APP上阅读。

1 环境搭建

Python 的安装姿势有很多种,按照操作系统分类:(1)Windows 系统安装 Python;(2)Linux 系统安装 Python;(3)Mac系统安装 Python。根据安装包分类:(1)使用可执行文件安装 Python;(2)使用包管理工具安装 Python;(3)使用源码安装 Python。文章源自十年又十年-https://www.bbigsun.com/95.html

本文只简单介绍 Python 环境的搭建,Python 的详细安装教程,可以查看:《安装教程 | Python》文章源自十年又十年-https://www.bbigsun.com/95.html

1.1 安装 Python 环境

1.1.1 Window 安装 Python

(1)下载 Python 安装包,下载地址:https://www.python.org/downloads/文章源自十年又十年-https://www.bbigsun.com/95.html

python-3.11.1-amd64.exe
《Python编程:从入门到实践》:基础知识文章源自十年又十年-https://www.bbigsun.com/95.html

(2)点击安装,按照指示下一步即可。(记住勾选 Add to Path)文章源自十年又十年-https://www.bbigsun.com/95.html

(3)Win + R 输入 cmd, Enter文章源自十年又十年-https://www.bbigsun.com/95.html

$ python --version
Python 3.11.1

1.1.2 Linux 安装 Python3

(1)下载 Python 安装包,下载地址:https://www.python.org/downloads/source/文章源自十年又十年-https://www.bbigsun.com/95.html

(2)选择要安装的版本,这里安装 Python3.11.1,下载地址:https://www.python.org/downloads/release/python-3111/文章源自十年又十年-https://www.bbigsun.com/95.html

(3)安装 Python文章源自十年又十年-https://www.bbigsun.com/95.html

wget https://www.python.org/ftp/python/3.11.1/Python-3.11.1.tar.xz
tar -zxf Python-3.11.1.tgz
mv Python-3.11.1 /opt/python3
ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 --version

1.1.3 安装编辑器 VS Code

免费好用的编辑器文章源自十年又十年-https://www.bbigsun.com/95.html

下载地址:https://code.visualstudio.com/

插件虽好,可不要贪多。多了,容易卡顿。

Python 插件:

  • 代码检查:Python extension for Visual Studio Code
  • 代码提示:Python Type Hint
  • 代码可视化:Python Preview
  • 代码片段:Python Snippets
  • 代码注释:Better Comments
  • 函数注释:autoDocstring
  • 代码缩进:Python Indent

1.2 Hello World

1.2.1 编写 hello.py

#!/usr/bin/env python3

def hello():
    print("Hello World!")

if __name__ == '__main__':
    hello()

1.2.2 运行 hello.py

打开 Vs Code 的 Terminal

$ python hello.py
Hello World!

2 基础语法

2.1 变量

2.1.1 变量的命名

  1. 变量名只能包含字母、数字和下划线。变量名能以字母或下划线打头,但不能以数字打头
  2. 不要将 Python 关键字和函数名用作变量名,即不要使用 Python 保留用于特殊用途的单词。
  3. 变量名应既简短又具有描述性。
  4. 慎用小写字母 l 和大写字母 O,因为它们可能被人错看成数字 1 和 0。

注意:就目前而言,应使用小写的 Python 变量名。虽然在变量名中使用大写字母不会导致错误,但是大写字母在变量名中有特殊含义。

2.1.2 变量的使用

使用赋值语句为变量message赋值,使用print方法将结果输出到控制台。

message = "Hello World!"
print(message)

2.2 数据类型

标准数据类型:

  • Numbers(数字)
  • String(字符串)
  • List(列表)
  • Tuple(元组)
  • Dictionary(字典)

2.2.1 字符串

字符串定义:

'单引号引用的字符串,单引号内特殊字符不转义'

"双引号引用的字符串"

'''多行字符串
多行字符串,双引号同理
'''

字符串格式化输出:

str = "Python"
print(f'方法一:Hello {str}!')
print('方法二:Hello {}!'.format(str))

字符串拼接:

str1 = "Hello "
str2 = "Python"
print(str1 + str2 + "!")

字符串切片:

str = "0123456789"
print(str[0])   # 第一位:0
print(str[1])   # 第二位:1
print(str[2])   # 第三位:2
print(str[9])   # 第10位:9
print(str[-1])  # 倒数第一位:9
print(str[-2])  # 倒数第二位:8
print(str[1:5]) # 第二位到第六位(第六位不取):1234
print(str[0:2:8])   # 第一位到第九位(第九位不取)间隔两位取一个值:0246

2.2.2 数

(1)整数

2 + 3 # 5
3 - 2 # 1
2 * 3 # 6
3 / 2 # 1.5
3 ** 2 # 9
2 + 3*4 # 14
(2+3) * 4 # 20

(2)浮点数
注意:浮点数结尾包含的小数是不确定的

0.1 + 0.2 # 0.30000000000000004
0.2 - 0.1 # 0.10000000000000004
0.5 * 0.2 # 1.00000000000000004
0.5 / 0.2 # 0.25000000000000004

(3)复数

3i + 4

2.3 其他

2.3.1 常量

通常用大写字母表示:

MAX_NUMBER = 5000

2.3.2 注释

# 单行注释

'''
单引号
多行注释
多行注释
'''

"""
双引号
多行注释
多行注释
"""

2.3.3 行与缩进

学习 Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。

缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。

2.3.4 多行语句

# 使用斜杠将一行语句分为多行显示
sum = one + \
      two + \
      three

# 如果是 [] {} () 则不需要使用多行连接符 \
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

2.3.5 同一行显示多条语句

Python 可以在同一行中使用多条语句,语句之间使用分号(;)分割。

x = 5; print(x)

3 循环语句

3.1 for 循环

for i in range(10):
    print(i)

3.2 while 循环

i = 0
while (i < 10):
    print(i)
    i += 1

3.3 循环嵌套

for i in range(10):
    for j in range(10):
        print(f'{i}{j}')

3.4 循环控制语句

跳出循环:

break

继续循环:

continue

跳过循环:

pass

4 条件语句

4.1 if 语句

import random
i = random.ranint(1,100)

if i < 10:
    print(f'{i} < 10')

if i > 90:
    print(f'{i} > 90')
elif i < 80:
    print(f'{i} < 80')
else:
    print(f'80 < {i} < 90')

4.2 switch...case 语句

Python 没有 switch...case 语句,因为可以用 if 语句实现。

num = input()
if num == '1':
    print(f'{num = 1}')
elif num == '2':
    print(f'{num} = 2')
elif num == '3':
    print(f'{num} = 3')
elif num == '4':
    print(f'{num} = 4')
elif num == 'q':
    print(f'退出程序')
    break
else:
    print(f'switch...case 语句中的 *')

5 列表

5.1 定义

var = []
var = list()

5.2 访问列表中元素

list = [1,2,3,4,5,6,7]
print(list[0]) # 1
print(list[1]) # 2
print(list[2]) # 3
print(list[-1]) # 7
print(list[1:-1]) # 2,3,4,5,6

5.3 更新列表元素

list = []

list.append('abc')
list.append('123')

5.4 删除列表元素

list = ['abc','123']
del list[1]

5.5 列表脚本操作符

len([1,2,3])    # 3
[1,2,3] + [4,5,6]   # [1,2,3,4,5,6]
['str'] * 4       # ['str','str','str','str']
3 in [1,2,3]    # True
for x in [1,2,3]:print(x)   # 1 2 3

5.6 列表函数

cmp(list1,list2)    # 比较两个列表的元素
len(list)   # 返回列表的长度
max(list)   # 返回列表元素最大值
min(list)   # 返回列表元素最小值
list(seq)   # 将元组转换为列表

5.7 列表方法

list.append(obj)
list.count(obj)
list.extend(seq)
list.index(obj)
list.insert(index, obj)
list.pop([index=-1])
list.remove(obj)
list.reverse()
list.sort(cmp=None, key=None, reverse=False)

6 字典

6.1 定义

var = {}
var = dict()

6.2 访问字典的值

dict = {'name': 'Tom', 'Age': '18', 'Gender': 'man'}
print("The cat's name is %s" % dict['name'])

6.3 修改字典

dict = {'name': 'Tom', 'Age': '18', 'Gender': 'man'}
dict['Age'] = '20' # 更新
dict['school'] = 'CQU'  # 添加

6.4 删除字典元素

dict = {'name': 'Tom', 'Age': '18', 'Gender': 'man'}
del dict['name']  # 删除'name'条目
dict.clear()    # 清空字典所有条目
del dict    # 删除字典

6.5 字典的特性

字典值可以没有限制地取任何 python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。

两个重要的点需要记住:

1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
2)键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行

6.6 字典的内置函数

cmp(dct1, dict2)
len(dict)
str(dict)
type(variable)

6.7 字典的内置方法

dict.clear()
dict.copy()
dict.fromkeys(seq[,val])
dict.get()

7 元组

7.1 定义

var = ()
var = turple()

8 函数

8.1 定义

def func():
    print(f'这是一个函数')

8.3 内置函数

9 模块

9.1 导入模块

import random

print(random.random())

9.3 内置模块

10 对象和类

class A:
    pass

11 文件和异常

try:
    print('可能出现异常的代码片段')
except:
    print('出现异常后进行提示')
else:
    print('没有异常进行提示')

12 测试与调试

纸上得来终觉浅,绝知此事要躬行。

weinxin
17688689121
我的微信
微信扫一扫
Python最后更新:2024-5-11
BBigSun
  • 本文由 BBigSun 发表于 2023年 1月 3日 11:10:54
  • 转载请务必保留本文链接:https://www.bbigsun.com/95.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定