本文是跟着鱼C论坛小甲鱼零基础学习Python3的视频学习的,课后题也是跟随每一课所附属的题目来做的,根据自己的理解和标准答案记录的笔记。
0.请问以下哪个是形参哪个是实参?
def MyFun(x):
return x**3
y = 3
print(MyFun(y))
答:x是形式参数,y是实际参数。函数定义过程中的参数是形参,调用函数过程中的参数是实参。
1.函数文档和直接用“#”为函数写注释有什么不同?
答:函数文档是对函数的解释和描述,可以调用 __.doc__ 进行查看。而 # 所写的函数解释则只是在定义函数的过程中所进行的单行解释。
2.使用关键字参数,可以有效避免什么问题的出现呢?
答:可以有效避免参数使用过程中因为顺序等其他方面原因调用函数时出错的问题出现,使用关键字参数可以在调用函数时对参数定向赋值,以函数参数名引导调用参数,防止出错。
3.使用help(print)查看print()这个BIF有哪些默认参数?分别起到什么作用?
答:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file like object (stream); defaults to the current sys.stdout.
#文件类型对象:默认是sys.stout(标准输出流)
sep: string inserted between values, default a space.
#第一个参数如果有多个值(第一个参数是手收集参数),各个参数之间默认使用空格(space)隔开
end: string appended after the last value, default a newline.
#打印最后一个值之后默认参数一个换行标志符(‘\n’)
flush: whether to forcibly flush the stream.
#是否强制刷新流
4.默认参数和关键字参数表面最大的区别是什么?
答:默认参数是在函数定义时就为形参赋予初始值,若调用函数时没有为形参传递实参,则使用用默认参数。关键字参数是在调用函数时,传递实参时指定对应的形参。
0.编写一个符合以下要求的函数:
a)计算打印所有参数的和乘以基数(base = 3)的结果
b)如果参数中最后一个参数为(base = 5),则设定基数为5,基数不参与求和运算。
答:
a)
def funx3(*numbers,base = 3):
result = 0
for each in numbers:
result += each
result *= base
print("结果:",result)
b)
def funx5(*numbers):
result = 0
for each in numbers[0:-1]:
result += each
result *= numbers[-1]
print("结果:",result)
1.寻找水仙花数
题目要求:如果一个3位数等于其各位数字的立方和,则称这个数为水仙花数。例如153 = 1^3 + 5^3 + 3^3,因此153是一个水仙花数。编写一个程序,找出所有水仙花数。
答:
def sxhnum():
for x in range(100,1000):
hund = x // 100
ten = (x - hund*100) // 10
zero = (x - hund*100 - ten*10)
if x == hund**3 + ten**3 + zero**3:
print(x)
else:
continue
2.编写一个函数findstr(),该函数统计一个长度为2的字符串在另一个字符串出现的次数。例如:假定输入的字符串为“You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.”,字符串为“im”,函数执行后打印“子字符串在目标字符串中共出现3次”。
答:
>>> def findstr(strx,stry):
count = 0
length = len(stry)
if strx not in stry:
print('该字符串未在目标字符串中出现!')
else:
for each in range(length - 1):
if stry[each] == strx[0]:
if stry[each+1] == strx[1]:
count += 1
print('该字符串在目标字符串中出现了%d次'% count)
>>> findstr('im','You cannot improve your past, but you can improve your future. Once time is wasted, life is wasted.')
该字符串在目标字符串中出现了3次
>>>