python

用递归函数计算n的阶层

python 复制代码
def fac(n):
    if n==1:
        return 1
    else:
        return n*fac(n-1)

print(fac(5))

斐波那契函数

python 复制代码
def fac(n):
    if n==1 or n==2:
        return 1
    else:
        return fac(n-1)+fac(n-2)
print(fac(9))

for i in range(1,10):
    print(fac(i),end='\t')
print()#这一个不能与前一个print对齐
#结果为:1	1	2	3	5	8	13	21	34

常用的数据类型转化函数

bool------跟0有关的还有空的类型布尔值都是False

python 复制代码
print('绝对值:',abs(100),abs(-100),abs(0))
print('商和余数:',divmod(13,4))
print('最大值:',max('hello'))
print('最大值:',max([10,4,56,78,4]))
print('最小值:',min('hello'))
print('最小值:',min([10,4,56,78,4]))

print('求和',sum([10,34,45]))
print('x的y次幂:',pow(2,3))

print(round(3.1415926))#3
print(round(3.9415926))#4
print(round(3.1415926,2))#2表示保留两位小数
print(round(313.415926,-1))#-1位,个数进行四舍五入
python 复制代码
lst=[54,56,77,4,56,34]
#(1)排序操作
asc_lst=sorted(lst)#升序
desc_lst=sorted(lst,reverse=True)#降序
print('原列表:',lst)
print('升序:',asc_lst)
print('降序:',desc_lst)

#(2)reversed 逆序
new_lst=reversed(lst)
print(type(new_lst))#class 'list_reverseiterator'>迭代器对象
print(list(new_lst))

#(3)zip
x=['a','b','c','d']
y=[10,20,30,40,50]
zipobj=zip(x,y)
print(type(zipobj))#<class'zip'>
#print(list(zipobj))#[('a', 10), ('b', 20), ('c', 30), ('d', 40)]
#为元组

#(4)enumerate
enum=enumerate(y,start=1)
print(type(enum))
print(tuple(enum))

#(5)all
lst2=[10,20,30,'']
print(all(lst2))#False,只要有空字符串就位False
print(all(lst))#True

print('-'*20)
#(6)any
print(any(lst2))#True,列表元素的所有值都为False的时候为False

#(7)
#运行时需要将19行的代码注释掉
print(next(zipobj))#('a', 10)
print(next(zipobj))#('b', 20)
print(next(zipobj))#('c', 30)
#运行一次获取一次

def fun(num):
    return num%2==1
obj=filter(fun,range(10))#将range中产生的0~9的数字都执行一遍fun操作
print(list(obj))
#[1, 3, 5, 7, 9]#得到的是奇数

def upper(x):
    return x.upper()

new_lst2=['hello','world','python']
obj2=map(upper,new_lst2)
print(list(obj2))
#['HELLO', 'WORLD', 'PYTHON']
#可以像这样用函数代替遍历循环
python 复制代码
print(format(3.14,'20'))#数值默认右对齐
print(format('hello','20'))#字符串默认左对齐
print(format('hello','*<20'))
print(format('hello','*>20'))
print(format('hello','*^20'))


print(format(3.1415926,'2f'))
print(format(20,'b'))
print(format(20,'o'))
print(format(20,'x'))
print(format(20,'X'))

print('-'*40)
print(id(10))
print(id('helloworld'))
print(type('hello'),type(10))

print(eval('10+30'))
print(eval('10>30'))#False
相关推荐
MOONICK12 小时前
QT元数据
开发语言·qt
卷无止境12 小时前
RAGFlow 项目全景报告:从文档解析引擎到 Agent 原生数据库
后端·python
D e re k ZH13 小时前
C++ 系统学习手记:从语法细节到工程实践
开发语言·数据结构·c++·算法
灿飞屋13 小时前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓
benchmark_cc13 小时前
单只股票五档盘口接入个人研究仓库:QuantDash 读取、校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
xiaoye-duck14 小时前
《C++ 项目:手写大模型接入 SDK》Ollama接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
总要学点什么15 小时前
第98篇:三维特效-材质线效果——给一条线换十种材质,虚线的图案只填了一半
开发语言·前端·javascript·ecmascript·gis·webgl·材质
田甲15 小时前
做一款 Type-C 母座读卡器:GL3224 双卡方案实测
c语言·开发语言
青少儿编程课堂15 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
严肃小白兔15 小时前
MATLAB 绘图与科研论文插图制作:图形设计、统计表达与矢量导出
开发语言·matlab·科研绘图