引入包
import random
import math
import json
math库
print(math.ceil(4.1))
print(math.floor(4.9))
print(math.fabs(-10))
print(math.sqrt(9))
print(math.exp(1))
分别是:向上取整,向下取整,绝对值,开放,e的x次幂
random库
print(random.random())
print(random.randint(1,10))
# [0,1)的随机数 [0,10)随机整数
random.seed(10)
print(random.random())
random.seed(10)
print(random.random())
# 设置种子,使之随机数完全相同
string
print('this \t is a tab.')
print('I\'m going to the movies.')
# print('''I'm going to the movies.''')
str1 = 'world'
str2 = 'hello!'
print(str2+str1)
new_str = '-'.join(str1)
print(new_str)
列表
lst = [1,2,'a','b','c']
print(lst[0], lst[1], lst[-1], lst[-5])
print(lst[len(lst)-1]) # 访问最后一个元素
# 列表查询
flag = 0
for num in lst:
if num == 2:
print('2 in arr.')
flag = 1
break
if flag == 0:
print('num not in arr.')
if 2 in lst:
print('2 in arr.')
lst = [1,2,'a','b','c']
lst[-2] = 'bb'
print(lst)
for i in range(len(lst)):
# if 'c' in lst[i]:
# TypeError: argument of type 'int' is not iterable
if 'c' in str(lst[i]):
lst[i] = 'cc'
break
print(lst)
lst = [1, 2, 'a', 'b', 'c']
lst.append(1)
print(lst)
lst.extend(['aaa','bbb'])
print(lst)
lst.insert(2,'sdc')
print(lst)
del lst[0] # 删指定序号
print(lst)
lst.remove('sdc') # 删指定值
print(lst)
rturn = lst.pop(2) # 删指定序号,返回值
print(lst,'\n',rturn)
lst = [1,2,3,4,5,6,7,8]
print(lst[1:3])
print(lst[-1:])
print(lst[-len(lst)::2])
# [2, 3]
# [8]
# [1, 3, 5, 7]
元组
tuple1 = ()
print(type(tuple1))
tuple2 = ('a',)
print(type(tuple2)) # tuple
tuple3 = ('a') # parentheses are redundant
print(type(tuple3)) # str
# 列表转元组,生成元组(因为不可修改)
ran = []
for i in range(10):
ran.append(random.randint(1,20))
print(ran)
ran_tuple = tuple(ran)
print(ran_tuple)
print(ran_tuple[::-1]) #倒序
装包、拆包
# 装包与拆包
t = 1, 2, 3, 4, 5
print(t, type(t)) # tuple 不可修改元组值
t = (1, 2, 3, 4, 5)
print(t, type(t))
a, b, *c = t
print(a, b, c, type(c)) # type(c)=list
a, *b, c = t
print(b) # [2, 3, 4]
字典
dict1 = {}
dict2 = dict()
dict3 = {'name': 111, 'hh': 222}
dict4 = dict()
dict4['name'] = 111
dict4['age'] = 22
dict4['he'] = 100
print(dict4)
for key,value in dict4.items():
if value > 10:
print(key)
print(dict4.keys())
print(dict4.values())
del dict4['he']
print(dict4)
dict4.pop('name')
print(dict4)
类与继承
class Animal:
def __init__(self, name):
self.name = name
print('动物名称实例化')
def eat(self):
print(self.name + 'is eating.')
cat = Animal('cat') # 实例化
print(cat.name)
cat.eat()
class Cat(Animal):
def __init__(self, name):
super().__init__(name)
print('调用子类构造方法')
def drink(self):
print('调用子类构造方法')
json
# json序列化 python对象转化为json字符串
data = [{'a': 1, 'c': 3, 'd': 4, 'b': 2}]
j = json.dumps(data)
print(j)
j_format = json.dumps(data, sort_keys=True, indent=4, separators=(',',': '))
print(j_format)
# [{"a": 1, "c": 3, "d": 4, "b": 2}]
# [
# {
# "a": 1,
# "b": 2,
# "c": 3,
# "d": 4
# }
# ]
# json反序列化
jsondata = '{"a": 1, "b": 2, "d": 4}'
text = json.loads(jsondata)
print(text, type(text))
#{'a': 1, 'b': 2, 'd': 4} <class 'dict'>
异常处理
try:
pass
except:
pass
else:
pass
finally:
pass