Lab 1: Variables & Functions, Control
Boolean Operators
This is because boolean operators, like arithmetic operators, have an order of operation:
- not has the highest priority
- and
- or has the lowest priority
Python values such as 0, None, '' (the empty string), and [] (the empty list) are considered false values. All other values are considered true values.
ZeroDivisionError:
1/0
WWPD:Control
>>> def xk(c, d):
... if c == 4:
... return 6
... elif d >= 4:
... return 6 + 7 + c
... else:
... return 25
>>> xk(10, 10)
23
>>> xk(10, 6)
23
>>> xk(4, 6)
6
>>> xk(0, 0)
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)
'big'
>>> how_big(12)
huge
>>> how_big(1)
small
>>> how_big(-1)
nothin'
>>> n = 3
>>> while n >= 0:
... n -= 1
... print(n)
2
1
0
-1
>>> positive = 28
>>> while positive:
... print("positive?")
... positive -= 3
Infinite Loop
>>> positive = -9
>>> negative = -12
>>> while negative:
... if positive:
... print(negative)
... positive += 3
... negative += 3
-12
-9
-6
WWPD: Veritasiness
and和or计算规则:
- 在纯and语句中,如果每一个表达式都为真,则返回最后一个真的值。如果有真有假,则返回第一个假的值。
- 在纯or语句中,如果全假,返回最后一个假的值。如果有真有假,则返回第一个真的值。
>>> True and 13
13
>>> False or 0
0
>>> not 10
False
>>> not None
True
>>> True and 1 / 0 and False
Error
>>> True or 1 / 0 or False
True
>>> True and 0
0
>>> False or 1
1
>>> 1 and 3 and 6 and 10 and 15
15
>>> -1 and 1 > 0
True
>>> 0 or False or 2 or 1 / 0
2
>>> not 0
True
>>> (1 + 1) and 1
1
>>> 1/0 or True
Error
>>> (True or False) and False
False
Q4: Falling Factorial
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
if k == 0:
return 1
return reduce(mul, range(n, n-k, -1))
Q5: Sum Digits
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"
ans = 0
while y:
ans += y % 10
y //=10
return ans
Q6: WWPD: 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'
Q7: Double Eights
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
if n // 10 == 0:
return False
while n:
last = n % 10
n //= 10
if last == 8 == (n % 10):
return True
return False