Skip to content

Python学习笔记

我10年前用过,但过去10年基本没用了。这个帖子来pick-up吧。

安装 Python

https://www.python.org/downloads/

安装开发环境 PyCharm

https://www.jetbrains.com/pycharm/

PyCharm 一些快捷键

数据类型

Bool

# True/False 必须大写开头
print(True and False)
print(not True)

Number

# 向下取整
print(int(7.89))
# 变成浮点 7.0
float(7)

# 四舍五入,小数点和2位
round(3.7778, 2)
# => 3.78

# 向上取整
import m ath
ceil_salary = math.cell(3.6)
# => 3

str(7.3)
# '7.3'

>>> 3/2
1.5
# 地板除法
>>> 3//2
1
>>> 3.0/2
1.5
>>> 3.0//2
1.0

# 幂运算 2^3
>>> 2**3
8
# 2^(-3) = 1/8
>>> 2**-3
0.125

>>> type('520')
<class 'str'>
>>> type(520)
<class 'int'>
>>> type(520.1)
<class 'float'>

# 查看Python的帮助文档,比起type()函数,更建议使用isinstance()来判断变量的类型。
isinstance(“abc", str)
# True
isinstance(520, float)
# False
isinstance(520, int)
# True

String

# 字符串连接
str1 = "hello"
str2 = "world"
print(str1 + " " + str2)

# raw string
raw_str1 = r"the path is C:\data\ "
raw_str1
print(raw_str1)

# 长字符串
long_str = """line 1
line 2
line 3"""

# 输出 format
print("my name is {}, not {}".format(name1, name2);
# 上下一样
print(f"my name is {name1}, not {name2}")

annual_salary = 20000*6
print(f'yearly salary is {annual_salary}')

# 空行
print()

# 用\来转义
# \t == tab
# \n == 换行
print('\t Let\'s go! \n')
# ==
print("\t Let's go! \n")

# 大小写变化
str = "hi, i'm Lei"
# Hi, I'M Lei
str.title()
# Hi, i'm lei
str.capitalize()
# hi, i'm lei
str.lower()
# HI, I'M LEI
str.upper()
# 大写变小写,小写变大写
str.swapcase()
str.isdigit() # 是否整数

# 分割
str = 'there are two lines \n and this is line 2\n'
print(str.split())
# ['there', 'are', 'two', 'lines', 'and', 'this', 'is', 'line', '2']
print(str.split('two'))
# ['there are ', ' lines \n and this is line 2\n']
print(str.splitlines())
# ['there are two lines ', ' and this is line 2']

# 删除空白
str.strip() # 两端都删除
str.rstrip() # 只删除右边
str.lfstrp() # 只删除左边

# 字符串长度
len('abc')

# 切片
    s = 'a bc Def'
    print(s[5:7])  # (0-index)第5个字符开始, 到第7个字符之前(不包括第7个)== 'De'
    print(s[-2:])  # 倒数第2也就是字母 e 开始到最终 == 'ef'
    print(s[-2])  # 只取倒数第2个字母e
    print(s[::-1])  # 整个字符串倒过来


数据结构

列表 list 也就是 array

l = ['e1', 'E2', 'e3']

条件/循环

# if-else
if a == 8:
  print("a is 8")
else:
  print("a is not 8")

# 有趣的 a < b < c 操作
num = int(input("intput a number"))
if (3 <= num <= 7):
  print("i like it")

if case_a:
  do sth
elif case_b:
  do sth
elif case_c:
  do sth
else case_others:
  do sth

# while
while guess != 8:
  if guess > 8:
    print("too big")
  else:
    print("too small")
  temp = input("try again")
  guess = int(temp)

库-math

import math
math.ceil(3.7) # => 3

一些参考