Theory

2. Review

2.3 Error Message

Error TypesDescriptions
SyntaxErrorContained improper syntax (e.g. missing a colon after an if statement or forgetting to close parentheses/quotes)
IndentationErrorContained improper indentation (e.g. inconsistent indentation of a function body)
TypeErrorAttempted operation on incompatible types (e.g. trying to add a function and a number) or called function with the wrong number of arguments
ZeroDivisionErrorAttempted division by zero

Example:

>>> square(3, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: square() takes 1 positional argument but 2 were given

  • The last line of an error message tells us the type of the error. In the example above, we have a TypeError.
  • The error message tells us what we did wrong -- we gave square 2 arguments when it can only take in 1 argument. In general, the last line is the most helpful.
  • The second to last line of the error message tells us on which line the error occurred. This helps us track down the error. In the example above, TypeError occurred at line 1.

3. Warm up:What-would-python-display?

Question 1:Control

  • Hint: Make sure your while loop conditions eventually evaluate to a false value, or they'll never stop! Type Ctrl-C will stop infinite loops in the interpreter.
>>> def xk(c, d):
...     if c == 4:
...         return 6
...     elif d >= 4:
...         return 6 + 7 + c
...     else:
...         return 25
>>> xk(10, 10)
______  

>>> xk(10, 6)
______

>>> xk(4, 6)
______

>>> xk(0, 0)
______

  • 23 23 6 25
>>> def how_big(x):
...     if x > 10:
...         print('huge')
...     elif x > 5:
...         return 'big'
...     elif x > 0:
...         print('small')
...     else:
...         print("nothin'")
>>> how_big(7)
______

>>> how_big(12)
______

>>> how_big(1)
______

>>> how_big(-1)
______

  • big,huge,small,nothin
>>> n = 3
>>> while n >= 0:
...     n -= 1
...     print(n)
______

  • -1
>>> positive = 28
>>> while positive:
...     print("positive?")
...     positive -= 3
______

  • 9 个positive?后输出-2
    • 是错误的
  • 因为 python 中 任何非零整数 在布尔上下文中都被视为真,while positive 语句会导致 while 条件始终为真,所以会一直循环输出 positive?
>>> positive = -9
>>> negative = -12
>>> while negative:
...     if positive:
...         print(negative)
...     positive += 3
...     negative += 3
______

  • 上述代码不会为零
    • 因为 negative 和 positive 最终会减到 0,当其值为 0 时代表布尔值为 False,会停止循环
    • 而上上段代码不会减到 0,会直接减到负数,而非零整数被视为真,故循环输出

Question 2:Veritasiness 真实性

>>> True and 13
13

>>> False or 0
0

>>> not 10
False

>>> not None
True
`None` 是一个特殊的值,用来表示空值或没有值。`None` 在布尔上下文中被视为假值

>>> True and 1/0 and False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
# 在Python中,逻辑运算符`and`遵循短路求值规则。但是,当表达式中的操作数是算术表达式时,Python 会首先计算这些表达式,然后再应用逻辑运算符。
在表达式 `True and 1/0 and False` 中:

1. `True` 是真值,所以 Python 继续评估下一个操作数。
2. `1/0` 是一个算术表达式,Python 会先尝试执行这个除法操作,而不管前面的逻辑值。
3. 由于除以零是不允许的,Python 抛出了一个 `ZeroDivisionError` 异常。

>>> True or 1/0 or False
True

表达式从左至右运算
若 or 的左侧逻辑值为 True ,则短路 or 后所有的表达式(不管是 and 还是 or),直接输出 or 左侧表达式 。
若 or 的左侧逻辑值为 False ,则输出or右侧的表达式,不论其后表达式是真是假,整个表达式结果即为其后表达式的结果。

>>> True and 0
0

表达式从左至右运算
若 and 的左侧逻辑值为 False ,则短路其后所有 and 表达式,直到有 or 出现,输出 and 左侧表达式到 or 的左侧,参与接下来的逻辑运算。
若 and 的左侧逻辑值为 True,则输出其后的表达式,不论其后表达式是真是假,整个表达式结果即为其后表达式的结果

>>> False or 1
1
>>> 1 and 3 and 6 and 10 and 15
15
如果一直为 True 直至结束,则返回最后一个值

>>> 0 or False or 2 or 1/0
2

>>> not 0
True

>>> (1+1) and 1
1

>>> 1/0 or True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

>>> (True or False) and False
False

Question 3:What if?

>>> def ab(c,d):
...     if c>5:
...             print(c)
...     elif c>7:
...             print(d)
...     print('foo')
...
>>> ab(10,20)
10
foo
>>> def bake(cake,make):
...     if cake ==0:
...             cake = cake +1
...             print(cake)
...     if cake ==1:
...             print(make)
...     else:
...             return cake
...     return make
...
>>> bake(0,29)
1
29
29

>>> bake(1,"mashed potatoes")
mashed potatoes
'mashed potatoes'

4. Required Problems

def both_odd(a, b):  
    """Returns True if both a and b are odd numbers.  
  
    >>> both_odd(-1, 1)  
    True    
    >>> both_odd(2, 1)  
    False    """    
    
    return (a % 2 == 1) and (b % 2 == 1)  
    # You can replace this line!  
  
  
def factorial(n):  

    """Return the factorial of a positive integer n.  
  
    >>> factorial(3)  
    6    
    >>> factorial(5)  
    120    """    
    
    if n == 1:  
        return 1  
    return n * factorial(n - 1)  
  
  
def is_triangle(a, b, c):  

    """Given three integers (may be nonpositive), judge whether the three  
    integers can form the three sides of a triangle.  
    >>> is_triangle(2, 1, 3)  
    False    
    >>> is_triangle(5, -3, 4)  
    False    
    >>> is_triangle(2, 2, 2)  
    True    """    
    
    if a>0 and b>0 and c>0 and a+b>c and a+c>b and b+c>a:  
  
        return True  
    else:  
        return False  
  
  
def number_of_six(n):  
    """Return the number of 6 in each digit of a positive integer n.  
  
    >>> number_of_six(666)  
    3    
    >>> number_of_six(123456)  
    1    """    
    '''  
    # 使用字符串来计算
    n_str = str(n)    # 计算字符串中字符 '6' 出现的次数  
    count = n_str.count('6')    return count
    '''  
    
    
    count = 0  
    while n > 0:  
        # 检查当前最低位是否为6  
        if n % 10 == 6:  
            count += 1  
        # 去掉当前最低位,继续检查下一位  
        n //= 10  
        
#在Python中,//= 是整除赋值运算符。它将左边变量的值替换为该变量与右边表达式进行整除的结果。整除运算符 // 返回除法运算的结果,但结果会被截断为整数。  
    return count  
     # YOUR CODE HERE  
  
  
def max_digit(x):  
    """Return the max digit of x.  
  
    >>> max_digit(10)  
    1    
    >>> max_digit(4224)  
    4    
    >>> max_digit(1234567890)  
    9    
    >>> # make sure that you are using return rather than print    		>>> a = max_digit(123)    
	>>> a  
    3    """      
    # YOUR CODE HERE  
    count = 0  
    n = 0  
    while x > 0:  
        n = x % 10  
  
        x = x // 10  
        if n >= count:  
            count = n  
  
    return count