博客
关于我
AI 基础:Python 简易入门
阅读量:798 次
发布时间:2023-04-17

本文共 4273 字,大约阅读时间需要 14 分钟。

0. 导语

Python是一种跨平台的计算机程序设计语言。作为一种面向对象的动态类型语言,Python最初被设计用于编写自动化脚本(shell),但随着版本的不断更新和功能的添加,Python逐渐被应用于独立的大型项目开发。

1. Python数据类型

1.1 字符串

在Python中,使用引号引起来的字符集称为字符串,例如 'hello'、"my Python"、"2+3"等。Python支持单引号、双引号和三引号作为字符串的引号类型。
print('hello world!')# 输出: hello world!

字符串可以包含转义字符,例如:

  • \n 表示换行
  • \t 表示制表符
  • \\ 表示自身

可以使用 r 前缀来避免引号转义:

print(r'\\t\\')  # 输出: \t

字符串操作:

  • 判断子字符串:
    s = 'Python'print('Py' in s)  # 输出: Trueprint('py' in s)  # 输出: False
  • 取子字符串:
    print(s[2])  # 输出: 'thon'print(s[1:4])  # 输出: 'thon'

字符串格式化与连接:

word1 = '"hello"'word2 = '"world"'sentence = word1.strip('"') + ' ' + word2.strip('"') + '!'print('The first word is %s, and the second word is %s' % (word1, word2))print(sentence)# 输出: The first word is "hello", and the second word is "world"# hello world!

1.2 整数与浮点数

Python支持大整数和浮点数运算。 - 整数: ```python i = 7 print(i) # 输出: 7 ```- 浮点数: ```python print(7.0 / 3) # 输出: 2.3333333333333335 ```- 其他表示方法: ```python print(0b1111) # 输出: 15 print(0xff) # 输出: 255 print(1.2e-5) # 输出: 0.00001 ```

1.3 布尔值

Python中的布尔值有两个:`True` 和 `False`。 - 布尔运算: ```python print(True and False) # 输出: False print(True or False) # 输出: True print(not True) # 输出: False ```- 数值与布尔运算: ```python print(18 >= 6 * 3 or 'py' in 'Python') # 输出: True print(18 >= 6 * 3 and 'py' in 'Python') # 输出: False ```

1.4 日期与时间

Python提供了`time`和`datetime`模块来处理日期与时间。 - 示例: ```python import time now = time.strftime('%Y-%m-%d', time.strptime('2016-07-20', '%Y-%m-%d')) print(now) # 输出: 2016-07-20 ```- 日期操作: ```python from datetime import date someDay = date(1999, 2, 10) anotherDay = date(1999, 2, 15) deltaDay = anotherDay - someDay print(deltaDay.days) # 输出: 5 ```

2. Python数据结构

2.1 列表

列表是存储一连串元素的容器,支持索引、切片和修改操作。 - 示例: ```python mylist = [0, 1, 2, 3, 4, 5] print(mylist) # 输出: [0, 1, 2, 3, 4, 5] ```- 列表操作: ```python mylist.append('han') # 添加到尾部 print(mylist) # 输出: [0, 1, 2, 3, 4, 5, 'han'] ```

2.2 元组

元组与列表类似,但元素不能修改。 - 示例: ```python scores = [90, 80, 75, 66] studentsTuple = ('ming', 'jun', 'qiang', 'wu', scores) print(studentsTuple) # 输出: ('ming', 'jun', 'qiang', 'wu', [90, 80, 75, 66]) ```- 元组不能修改: ```python try: studentsTuple[1] = 'fu' except TypeError: print('TypeError') ```

2.3 集合

集合用于存储唯一元素,支持集合操作。 - 示例: ```python studentsSet = set(mylist) print(studentsSet) # 输出: {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long'} ```- 集合操作: ```python studentsSet.add('xu') print(studentsSet) # 输出: {0, 1, 2, 'han', 4, '小月', 19978, 'wan', 'long', 'xu'} ```

2.4 字典

字典用于存储键-值对,支持快速查找。 - 示例: ```python k = {"name": "weiwei", "home": "guilin"} print(k["home"]) # 输出: Guilin ```- 字典操作: ```python k["like"] = "music" print(k) # 输出: {'name': 'weiwei', 'home': 'guilin', 'like': 'music'} ```

2.5 列表、元组、集合、字典的互相转换

- 列表转元组: ```python tuple(mylist) # 输出: (0, 1, 2, '小月', 4, 19978, 'han', 'long', 'wan') ```- 字典转列表: ```python list(k) # 输出: ['name', 'home'] ```

3. Python控制流

3.1 顺序结构

```pythons = '7'num = int(s)num -= 1num *= 6print(num) # 输出: 36```

3.2 分支结构

```pythonsalary = 1000if salary > 10000: print("Wow!!!!!!!")elif salary > 5000: print("That's OK.")elif salary > 3000: print("5555555555")else: print("..........")# 输出: ..........```

3.3 循环结构

```pythona = 1while a < 10: if a <= 5: print(a) else: print("Hello") a += 1else: print("Done")# 输出: 12345HelloHelloHelloDone```

3.4 break、continue和pass

```pythonfor i in range(1, 5): if i == 3: break print(i) # 输出: 12```

3.5 列表生成式

```pythonfruits = ['"Apple", '"Watermelon", '"Banana"']test_list = [x.strip('"') for x in fruits]print(test_list) # 输出: ['Apple', 'Watermelon', 'Banana']```

4. Python函数

4.1 调用函数

```pythonstr1 = "as"int1 = -9print(len(str1))print(abs(int1)) # 输出: 29```

4.2 定义函数

```pythondef my_abs(x): if x >= 0: return x else: return -xprint(my_abs(-9)) # 输出: 9```

4.3 高阶函数

```pythondef add(x, y, f): return f(x) + f(y)print(add(7, -5, abs)) # 输出: 12```

其它

  • 变量命名规范:

    • 第一个字符只能是字母或下划线,不能是数字或其他字符。
    • 后续字符可以是字母、下划线或数字。
    • 大小写敏感,nameName不同。
  • 关键字:

    • Python自带的具有特殊含义的标识符,如ifelsedef等。
    • 查看关键字列表:
      import keywordprint(keyword.kwlist)# 输出: ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 注释:

    • 使用 # 进行单行注释。
    • 多行注释使用 """ """ 或 `` `.
  • 帮助文档:

    • Ctrl + q 或访问官方文档获取帮助。

转载地址:http://tvgfk.baihongyu.com/

你可能感兴趣的文章
MySQL-redo日志
查看>>
MySQL-【1】配置
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>
MySQL-数据页的结构
查看>>
MySQL-架构篇
查看>>
MySQL-索引的分类(聚簇索引、二级索引、联合索引)
查看>>
Mysql-触发器及创建触发器失败原因
查看>>
MySQL-连接
查看>>
mysql-递归查询(二)
查看>>
MySQL5.1安装
查看>>
mysql5.5和5.6版本间的坑
查看>>
mysql5.5最简安装教程
查看>>
mysql5.6 TIME,DATETIME,TIMESTAMP
查看>>
mysql5.6.21重置数据库的root密码
查看>>
Mysql5.6主从复制-基于binlog
查看>>