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
相关推荐
爱吃牛肉的大老虎1 小时前
rust基础之环境搭建
java·开发语言·rust
openKylin1 小时前
与全球技术演进同频,openKylin 3.0从C迈向Rust
c语言·开发语言·rust·开源·开放原子·openkylin
用户8356290780512 小时前
使用 Python 在 Excel 中添加和自定义文本框
后端·python
疯狂打码的少年2 小时前
【软件工程】结构化设计:模块独立性与耦合内聚
java·开发语言·笔记·软件工程
总裁余(余登武)2 小时前
python多个py文件打包【解决exe不能移动运行bug】
python
程高兴2 小时前
PMSM基于在线转动惯量辩识的滑模负载转矩观测器MATLAB-SIMULINK仿真模型
开发语言·matlab
kisloy3 小时前
【python零基础教程第24讲】代码规范与质量管控
开发语言·python
C++、Java和Python的菜鸟3 小时前
第4章 后端Web基础(基础知识)
java·开发语言
芷栀夏3 小时前
Java教育平台实战复盘:课程、考试与学习行为分析系统设计
java·开发语言·学习
从零开始的代码生活_3 小时前
C++ 多态详解:虚函数、动态绑定、抽象类与虚表原理
开发语言·c++·后端·学习·算法