Python 核心编程练习-chapter 5

Q: 1. 讲讲Python普通整形和长整型的区别。

A: 一般情况长整型用来表示非常大的数字,和计算机支持的内存大小有关。而普通整形则代表C语言中的整形和长整型。

Q: 2. 写一个函数,计算并返回两个数的乘积。

A:

1
2
3
4
5
def multiply(x, y):
if isinstance(x, (int, float)) and isinstance(y, (int, float)):
return x * y
else:
print('Please enter a int or float.')

Q: 3. 写一段脚本,输入一个测验成绩,根据下面的标准,输出他的评分成绩(A-F)
A:90 - 100;B: 80 - 89; C: 70 - 79; D: 60 - 69; F: < 60

A:

1
2
3
4
5
6
7
8
9
10
def score(s):
if s >= 90:
return A
elif s >= 80:
return B
elif s >= 70:
return C
elif s >= 60:
return D
return F

Q: 4. 判断给定年份是否是闰年,使用下面的公式:一个闰年就是指它可以被4整除,但不能被100整除,或者它既可以被4又可以被100整除。

A:

1
2
3
4
5
6
def isLeapYear(x):
if x % 4 == 0 and x % 100 == 0:
return True
elif x % 4 == 0:
return True
return False

Q: 5. 取一个任意小于1美元的金额,然后计算可以换成最少多少枚硬币。硬币有1美分,5美分,10美分,25美分4种。1美元等于100美分。0.76美元换算成结果应该是3枚25美分,1枚1美分。

A:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def changeCent(x):
if x < 1 and x >= 0.25:
i = x * 100
a, b = divmod(i, 25)
if b >= 10:
c, d = divmod(b, 10)
if d >= 5:
e, f = divmod(d, 5)
return a + c + e + f
return a + c + d
return a + b
elif x >= 0.1:
i = x * 100
a, b = divmod(i, 10)
if b >= 5:
c, d = divmod(b, 5)
return a + c + d
return a + b
elif x >= 0.05:
i = x * 100
a, b = divmod(i, 5)
return a + b
elif x > 0:
i = x * 100
return i

Q: 6. 写一个计算器程序,你的代码可以接受这样的表达式,两个操作数加一个运算符: N1 运算符 N2,其中 N1 和 N2 为整数或浮点数,运算符可以是 +,-,*,//,%,\分别表示加法,减法,乘法,整除,取余和幂计算。计算这个表达式的结果,然后显示出来。提示:可以使用字符串 split(),但不可以使用内建函数 eval()。**

A:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def calculator(s):
new_s = str(s).split()
if len(new_s) == 3:
a, b, c = new_s
if '.' in a or '.' in c:
d, e = float(a), float(c)
if b == "+":
return (d + e)
elif b == "-":
return (d - e)
elif b == "*":
return (d * e)
elif b == "//":
return (d // e)
elif b == "%":
return (d % e)
elif b == "**":
return (d ** e)
d, e = int(a), int(c)
if b == "+":
return (d + e)
elif b == "-":
return (d - e)
elif b == "*":
return (d * e)
elif b == "//":
return (d // e)
elif b == "%":
return (d % e)
elif b == "**":
return (d ** e)
print("Please enter correct format, e.g: '1 + 2'")

Q: 7. 为什么 17+32 等于49, 而 017+32 等于 47,017+032 等于41?

A: 17+32 是十进制运算,结果是49,017+32 是把 017 先转成十进制,int(‘017’, 8)可以得到15,15+32等于47,同理 017+032, int(‘032’, 8)等于26,15+26 等于41

Q: 8. 为什么下面这个表达式得到的结果是 134L,而不是1342?>>>56l + 78l; 134L

A: 因为是 56L + 78L,两个长整型相加所以得到长整型。