Python(一):基础

96 阅读2分钟

参考:Learn Python in Y Minutes (learnxinyminutes.com)

一、基础数据和操作

print(3) # 3:数字

# 数学运算符
print(1+1) # 2
print(8-1) # 7
print(10*2) # 20
print(35/5) # 7.0

# 除法
5 // 3       # => 1
-5 // 3      # => -2
5.0 // 3.0   # => 1.0 
-5.0 // 3.0  # => -2.0
10.0 / 3  # => 3.3333333333333335

# 取模
7%3 # => 1
-7%3 # => 2

# 乘方
2 ** 3 # => 8

# 多运算符
1 + 3 * 2 # => 7
(1 + 3) * 2 # => 8

运算符优先级:

Python运算符结合性
()
x[i]
x.attribute
**
~
+、-
*、/、//、%*
+、-
>> 、<<
&
==、!=、>、>=、<、<=
is/is not
in/not in
# 布尔类型
True
False

# 逻辑运算符
not True
not False
True and False
True or False

# 布尔运算
True + True # 2
True * 8 # 8
False - 5 # -5

# 比较运算符
0 == False
1 == True
2 == True
-5 != False
1 > 10
1 < 10
2 <= 2
2 >= 2
1 < 2 < 3
2 < 3 < 2

# bool逻辑运算符
bool(0) # False
bool(4) 

# is 和 ==
a = [1, 2, 3, 4]
b = a 
a is b
b == a
b = [1, 2, 3, 4]
b is a   # False 
b == a

# string
"This"
'This'
"This" + "is"
"This"[0]
len("This")

# 格式化输出
name = "li"
print(f'{name} is this')
print(f'{name} len is {len(name)}')
print('hi', end='!')

# None
"ect" is None
None is None

# False
0""、[]、{}、()、None
# 但是除了None本身外,其他都不等于None,也都is not None

# 输入
str = input("input")

# 三目运算符
'yes' if 0 > 1 else 'no'

# list 可变数据类型
li = []
other_li = [4, 5, 6]
li.append(1) # 添加元素
li.append(2)
li.append(3)
li.append(4)
li.append(5)
li.pop() # 删除最后一个元素
li[0] # 取第一个元素
li[-1] # 最后一个元素
li[1:3] # 截断
li[0:5:2]
li[::-1] # 翻转
li2 = li[:] # 深拷贝
del li[2] # 删除第三个
li.remove(2) # 删除第一个值为2的
li.insert(1, 2) # 在下标为1的地方插入2
li.index(2) # 返回2的下标
li + other_li
li.extend(other_li)
1 in li
len(li)

# tuple 不可变数据类型
tup = (1, 2, 3)
tup[0]
tup[0] = 3 # error
len(tup)
tup + (4,5,6)
2 in tip
tup[:2]
a, b, c = (1, 2, 3)
a, *b, c = (1, 2, 3, 4, 5)
d, e, f = 4, 5, 6
e, d = d, e # 交换

# 查看类型
type((1)) # int
type((1,)) # tuple
type(()) # tuple

# dict
empty_dict = {}
filled_dict = {"one" : 1, "two" : 2, "three" : 3}
# 一个对象能不能作为字典的key,就取决于其有没有__hash__方法。所以所有python自带类型中,除了list、dict、set和内部至少带有上述三种类型之一的tuple之外,其余的对象都能当key。
# 也就是说不可变类型可以作为key,可变类型不可以作为key
filled_dict["one"]
list(filled_dict.keys())
list(filled_dict.values())
"one" in filled_dict.keys()
filled_dict.get("one")
filled_dict.get("one", 4)
filled_dict.setdefault("five", 5)
filled_dict.update({"four":4})
filled_dict["four"] = 4
del filled_dict['one']
{'a':1, **{'b':2}}   # {'a':1, 'b':2}
{'a':1, **{'a':2}}   # {'a':2}

# set
empty_set = set()
some_set = {1, 1, 2, 4}
# 集合的数据类型必须是不可变类型
some_set.add(5)
other_set = {3, 4, 5, 6}
empty_set & other_set
{1, 2, 3, 4} - {2, 3, 5}
{1, 2, 4, 5} ^ {2, 3, 5}
{1, 2} >= {1, 2, 3}
{1, 2} <= {1, 2, 3}
2 in some_set
filled_set = some_set.copy()
filled_set is some_set # False

# 控制流和迭代器
some_var = 5
if some_var > 10:
    pass
elif some_var < 10:
    pass
else:
    pass

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

for i in range(4, 8):
    print(i)

for i in range(1, 9, 2):
    print(i)

animals = [1, 3, 4]
for i, value in enumerate(animals):
    print(i, value)
    
x = 0
while x < 4:
    print(x)
    x += 1

try:
    raise IndexError('This is an index error')
except IndexError as e:
    pass
else:
    pass
finally:
    pass

with open('myfile.txt') as f:
    for line in f:
        print(line)
        
contents = {'a':12, 'b':21}
with open('myfile1.txt', 'w+') as file:
    file.write(str(contents))
    
with open('myfile1.txt', 'w+') as file:
    file.write(json.dumps(contents))

with open('myfile1.txt', 'w+') as file:
    contents = file.read()

with open('myfile1.txt', 'w+') as file:
    contents = json.load(file)
    
it = iter(contents.keys())
next(it)

for i in it:
    print(i)

# 函数
def add(x, y):
    return x + y

add(5, 6)
add(y = 5, x = 6)

def vararges(*args):
    return args
    
def keyword_args(**kwargs):
    return kwargs
    
x = 5
def glo():
    global x
    x = 6

# 匿名函数
(lambda x: x > 2)(3)
(lambda x, y: x ** 2 + y ** 2)(2, 1)

# map
list(map(max, [1, 2, 3], [4, 2, 1]))

# filter
list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))

# list
[x for x in [3, 4, 5, 6, 7] if x > 5]

# modules
import math
math.sqrt(16)
math.ceil(3.7)
math.floor(3.7)

# class
class Human:
    spacies = 'J'
    def __init__(self, name):
        self.name = name
        self._age = 0
    
    @classmethod
    def get_species(cls):
        return cls.spacies
        
    @staticmethod
    def grunt():
        return "*grunt*"
        
    @property
    def age(self):
        return self._age
    
    @age.setter
    def age(self, age):
        self._age = age
     
    @age.deleter
    def age(self):
        del self._age

# 继承
class super(Human):
    def __init__(self, name):
        super().__init__(name)
        
# 多继承
class Bat:
    def __init__(self):
        pass

class multi(Human, Bat):
    def __init__(self):
        Human.__init__(self, 'anonymous')
        Bat.__init__(self)