python(递归+斐波那契+迭代函数)

用递归函数计算n的阶层

def fac(n):
    if n==1:
        return 1
    else:
        return n*fac(n-1)

print(fac(5))

斐波那契函数

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

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位,个数进行四舍五入
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']
#可以像这样用函数代替遍历循环

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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值