-
将函数部分知识点,整理到自己笔记中。(搞明白课上讲的案例。)
-
写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回。
def get_odd_value(data): return list(data[0::2]) print(get_odd_value((1,2,3,4,5,6)))
-
写函数,判断用户传入的一个对象(字符串或列表或元组任意)长度是否大于5,并返回真假。
def len_morethan5(data): return True if len(data)>5 else False print(len_morethan5("12"))
-
写函数,接收两个数字参数,返回比较大的那个数字。
def bigger(one,two): return one if one>two else two print(bigger(1,2))
-
写函数,函数接收四个参数分别是:姓名,性别,年龄,学历。用户通过输入这四个内容,然后将这四个内容传入到函数中,此函数接收到这四个内容,将内容根据"*"拼接起来并追加到一个student_msg文件中。
def insert_values(name,sex,age,education): list = [name,sex,age,education] with open('student_msg.txt',mode='w',encoding='utf-8') as f1: f1.write('*'.join(list)) insert_values('frantiChow','male','24','本科')
-
写函数,在函数内部生成如下规则的列表 [1,1,2,3,5,8,13,21,34,55…](斐波那契数列),并返回。
注意:函数可接收一个参数用于指定列表中元素最大不可以超过的范围。
#方法一
def Fibonacci_Sequence(value):
list = [1,1]
return_list = []
if value == 1:
return list
else:
for i in range(1,value+1):
list.append(list[i]+list[i-1])
for i in list:
if i <= value:
return_list.append(i)
else:
return return_list
print(Fibonacci_Sequence(50))
#方法二
def Fibonacci_Sequence(max_range):
result = [1,1]
while True:
val = result[-1]+result[-2]
if val > max_range:
break
result.append(val)
return result
print(Fibonacci_Sequence(50))
-
写函数,验证用户名在文件 data.txt 中是否存在,如果存在则返回True,否则返回False。(函数有一个参数,用于接收用户输入的用户名)
data.txt文件格式如下:
1|alex|123123 2|eric|rwerwe 3|wupeiqi|pppp
def exist_user(user):
with open('data.txt',mode='r',encoding='utf-8') as f1:
for line in f1:
if user == line.split('|')[1]:
return True
else :
return False
print(exist_user('alexs'))