Python基础知识

数据类型

字符 str

  • 引号:在字符中显示单引号,则编程时用双引号将字符括起来;在字符中显示双引号,则编程时用单引号将字符括起来; 字符中的单引号:course = "He's finger" 字符串中的双引号:words = 'Python is for "beginners"'
  • 大小写course.upper()course.lower()course.title()
  • 查找替换course.find('xxx'),course.replace('xxx','aaa')
  • 字符长度:使用len()
  • f与花括号:可以被用来格式化输出字符(在字符中嵌入变量)。
    1
    2
    3
    first_name='John'
    last_name='Smith'
    msg = f"{first_name} [{last_name}] is a coder"

整数 int 浮点数 float 复数 complex

数据索引

  1. Python中的索引从0开始
  2. 数据索引中的负号表示从结束端开始:[1:-1]是正确的,-1表示倒数第二个数据

数据切片索引 与Matlab不同的是,A[1:5]返回的不是数列A中位于1、2、3、4、5号位置的数据;取而代之的是:

1
2
3
4
5
6
7
8
9
10
A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(A[1:5])

Output:
[2, 3, 4, 5]

-------------------------------------------
[A]: | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
cut: -0---1---2---3---4---5---6---7---8---9----10-

if

常用调用模式如下,用缩进控制开始和结束(与matlab不同):

1
2
3
4
5
6
if is_hot:
print('xxxxx')
elif is_coldL:
print('xxxxxx')
else:
print('xxxx')

常用逻辑运算符 1. 和:and,例如:is_hot and is_cold 1. 或:or 1. 非:not,例如:is_cold and not is_windnot会将其后的False转化为True;上例中如果is_cold = Trueis_wind = False,则返回True

比大小: 1. 大于:>、小于:<、等于:== 1. 大于等于:>=、小于等于:<= 1. 不等于:!=

循环

while常用调用模式如下,break可以用来跳出程序:

1
2
3
4
5
i=1
while i<=5:
print('i')
i = i + 1
print('Done') #用缩进控制while的结束

for常用调用模式

1
2
for item in [1,2,3,4]
print(item)

函数

常用函数

绝对值:abs() 四舍五入到整数:round() 生成等间距数列:range(5,10,2);step=2,from 5 to 10,输出 5 7 9

常用命令

运算符号

  1. +;减-;乘*;除/;幂**
  2. 特殊除号:得到结果的整数部分//;得到结果的余数%
  3. 增广运算符X += 3x = x + 3等价、x -= 3同理

import

调用包:import XXX,例如import math;使用时math.acos()

Questions

  1. methods 和 function 在Python有何区别的?