计算机科学与Python编程导论_MIT 学习笔记(四)

函数

语法:

函数语法

返回none 或者指定值
函数内部为一个黑盒
封装(encapsulating)一个环境局部,不影响全局环境,便于调试

全局变量和局部变量

例:幂函数

def iterativePower(x,p):
    result=1
    for turn in range(p):
        print('iteration: '+str(turn)+' current result: '+str(result))
        result*=x
    return result

例:求根1(只能求正的、大于一的)

def findRoot1(x,power,epsilon):
    low=0
    high=x
    ans=(low+high)/2
    while abs(ans**power-x)>epsilon:
        if ans**power<x:
            low=ans
        else:
            high=ans
        ans=(low+high)/2
    return ans

例:求根2(只能求绝对值大于1的)

def findRoot2(x,power,epsilon):
    low=min(0,x)
    high=max(0,x)
    ans=(low+high)/2
    while abs(ans**power-x)>epsilon:
        if ans**power<x:
            low=ans
        else:
            high=ans
        ans=(low+high)/2
        print(ans)
    return ans

例:求根3(针对所有实数)

"""x and epsilon int or float,power an int
   epsilon>0 & power>=1
   return a float y s.t. y^power is within epsilon of x.
   If such a float does not exist, it returns None
"""
def findRoot3(x,power,epsilon):
    if x<0 and power%2==0:
        return None
#can't find even powered root of negative number       
    else:
        low=min(-1,x)
        high=max(1,x)
        ans=(low+high)/2
        while abs(ans**power-x)>epsilon:
            if ans**power<x:
                low=ans
            else:
                high=ans
            ans=(low+high)/2
        return ans

好的代码应该有对于输入的假设和输出的描述,以及不同输入下的报错说明。

上面三个例子说明,封装函数便于更改算法实施。

函数可以由使用者重新创造并作为原语使用
函数可以将问题分解成小的模块,分别解决问题的一部分或者一个步骤
函数可以隐藏细节,让用户直接调用于解决其他的问题

引入py文件

可以用py文件装载具有某种共性的一系列函数

1 import X

在使用X.py中的函数x(y)时,要写:

X.x(y)
2 form X import *

在使用X.py中的函数x(y)时,要写:

x(y)

针对字符型的一些函数

.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

>>> str3='aBBN'
>>> str3.capitalize()
'Abbn'
.find(sub[, start[, end]])

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

>>> str2 = 'number one - the larch'
>>> str2.find('e',5,)
9
.index(sub[, start[, end]])

Like find(), but raise ValueError when the substring is not found.

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值