CS61A Lecture3 Control

Lecture 3

1.1 Print and None

None :None is displayed by the interpreter as the value of an expressiom.

difference between print() and directly input in python3 interpreter:

eg:

>>>'asdf'
'asdf'
>>>print('asdf')
asdf
>>>None
>>>print(None)
None
>>>print(1,1,1)
1 1 1
>>>1,1,1
1,1,1
>>>print(print(1),print(2))
1
2
None None

None can't be computed,or erroe will be returned.

Pure Functions:just return values.eg.abs(),pow()

Non-Pure Functions:have side-effecs.eg.print()

1.2Mutiple Environment

difference between global frame and local frame.

1.3Misscellaneous Python Feature

(1)Mutiple input and mutiple output.

(2)documentation:dockstring

(usually the first line below the def)

eg.

>>> def pressure(v, t, n):
        """Compute the pressure in pascals of an ideal gas.

        Applies the ideal gas law: http://en.wikipedia.org/wiki/Ideal_gas_law

        v -- volume of gas, in cubic meters
        t -- absolute temperature in degrees kelvin
        n -- particles of gas
        """
        k = 1.38e-23  # Boltzmann's constant
        return n * k * t / v

(3)interactive session

if correct, no output,or provide the error information.

if you wnay see more output,use '-v'.

eg.

def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    >>> # a check that you didn't change the return statement!
    >>> import inspect, re
    >>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M)
    ['return f(a, b)']
    """
    if b < 0:
        f = sub
    else:
        f = add
    return f(a, b)

(4)Default values

if no argument bounded,default values are used.

2.1 Conditional Statements

eg.

if x<0:
    return -x
elif x==0:
    return 0
else:
    return x

2.2 Iteration

most important:what information you need to keep track of in order to perform the iteration

e.g.

1	def fib(n):
2	    """Compute the nth Fibonacci number, for n >= 2."""
3	    pred, curr = 0, 1   # Fibonacci numbers 1 and 2
4	    k = 2               # Which Fib number is curr?
5	    while k < n:
6	        pred, curr = curr, pred + curr
7	        k = k + 1
8	    return curr

Appendix

new functions

if elif else   ;   while 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值