Python基本语法复习——嗯...貌似很久没写过博客了

本文介绍了Python中math和random库的使用,包括基本数学运算、随机数生成,以及字符串、列表、元组、字典和类的深入讲解,还涵盖了json序列化与反序列化以及异常处理的相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入包

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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风起风里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值