1.编写函数,求1+2+3+…N的和
def m_sum(n):
sum1 = 0
for items in range(n+1):
sum1 = sum1 + items
return sum1
print(m_sum(100))
2.编写一个函数,求多个数中的最大值
def m_max(*nums):
max1 = nums[0]
for items in nums:
if items > max1:
max1 = items
return max1
print(m_max(1, 2, 3, 4, 5))
3.编写一个函数,实现摇骰子的功能,打印N个骰子的点数和
import random
def dice(n):
sum1 = 0
num_list = []
while n > 0:
num_list.append(random.randint(1, 6))
n = n - 1
return sum(num_list)
n = int(input("要摇几次骰子?"))
print("总和是:%d" % dice(n))
- 编写一个函数,交换指定字典的key和value。
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def change_dict(dic):
for key in dic:
new_key = dic[key]
new_value = key
dic.pop(key)
dic[new_key] = new_value
return dic
dict1 = {'a': 1, 'b': 2, 'c': 3}
print(change_dict(dict1))
- 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
例如: 传入'12a&bc12d-+' --> 'abcd'
def extract_letters(str1):
new_str = ''
for items in str1:
if 'a' <= items <= 'z' or 'A' <= items <= 'Z':
new_str += items
return new_str
str1 = input('输入字符串')
print("提取字母:%s" % extract_letters(str1))
6.写一个函数,求多个数的平均值
def ave(nums):
aver = sum(nums) / len(nums)
return aver
num_list = []
num_str = input("输入一串数字,空格隔开:")
new_str = []
new_str = num_str.split(' ')
for items in new_str:
num_list.append(int(items))
print("平均值是:%.2f" % ave(num_list))
7.写一个函数,默认求10的阶乘,也可以求其他数字的阶乘
def factorial(n=10):
fac = 1
for num in range(1, n+1):
fac = num * fac
return fac
n = int(input('输入一个数:'))
print("该数的阶乘是:%d" % factorial(n))
- 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如: 'abc' -> 'Abc' '12asd' --> '12asd'
def m_capitalize(str1):
new_str = ''
if 'a' <= str1[0] <= 'z':
new_str += chr(ord(str1[0])-32)
for index in range(1, len(str1)):
new_str += str1[index]
return new_str
str2 = input("输入一串字符")
print("修改后:%s" % m_capitalize(str2))
9.写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False
str1 = input("输入判断的字符串:")
str2 = input("结束的标志是:")
def m_endswith(judge_str, ends_str):
flag = 1
index2 = 0
for index in range(len(judge_str)-len(ends_str),len(judge_str)):
if judge_str[index] != ends_str[index2]:
flag = 0
index2 += 1
if flag == 1:
return True
else:
return False
print("函数结果是%s" % m_endswith(str1, str2))
- 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
例如: '1234921' 结果: True
'23函数' 结果: False
'a2390' 结果: False
num_str = input("输入字符串:")
def m_isdigit(nums_str):
flag = 1
for num in nums_str:
if not('0' <= num <= '9'):
flag = 0
if flag == 1:
return True
else:
return False
print("结果是%s" % m_isdigit(num_str))
- 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
例如: 'abH23好rp1' 结果: 'ABH23好RP1'
str1 = input("输入字符串:")
def m_upper(last_str):
new_str = ''
for char in last_str:
if 'a' <= char <= 'z':
new_str += chr(ord(char)-32)
else:
new_str += char
return new_str
print("新字符串是:%s" % m_upper(str1))
- 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
例如: 原字符:'abc' 宽度: 7 字符:'^' 结果: '^^^^abc'
原字符:'你好吗' 宽度: 5 字符:'0' 结果: '00你好吗'
str1 = input("输入字符串:")
width = int(input("输入宽度:"))
fill_char = input("输入补充字符:")
def m_rjust(last_str, user_width, user_fillchar):
new_str = ''
if len(last_str) < user_width:
for count in range(width - len(last_str)):
new_str += user_fillchar
new_str += last_str
return new_str
print("新字符串是:%s" % m_rjust(str1,width,fill_char))
13.写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0] 元素: 1 结果: 0,4,6
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '赵云' 结果: 0,4
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '关羽' 结果: -1
list_str = input("输入列表,逗号隔开:")
list1 = list_str.split(',')
index1 = input("指定元素:")
def m_index(user_list, user_index):
index_str = ''
flag = 0
for index in range(len(user_list)):
if user_list[index] == user_index:
flag = 1
index_str += str(index)
if flag == 0:
index_str += '-1'
return index_str
print("下标是:%s" % m_index(list1, index1))
14.写一个自己的len函数,统计指定序列中元素的个数
例如: 序列:[1, 3, 5, 6] 结果: 4
序列:(1, 34, 'a', 45, 'bbb') 结果: 5
序列:'hello w' 结果: 7
str1 = (1, 34, 'a', 45, 'bbb')
def m_len(user_str):
count = 0
for char in user_str:
count += 1
return count
print("结果是:%d" % m_len(str1))
15.写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9] 结果: -1
序列:'abcdpzasdz' 结果: 'z'
序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98
str1 = {'小明': 90, '张三': 76, '路飞': 30, '小花': 98}
def m_max(user_str):
if type(user_str) == dict:
for key in user_str:
user_max = user_str[key]
for key in user_str:
if user_max < user_str[key]:
user_max = user_str[key]
else:
user_max = user_str[0]
for char in user_str:
if char > user_max:
user_max = char
return user_max
print("最大值是%s" % m_max(str1))
16.写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
例如: 序列: (12, 90, 'abc') 元素: '90' 结果: False
序列: [12, 90, 'abc'] 元素: 90 结果: True
str1 = [12, 90, 'abc']
judge = 90
def m_in(user_str,user_judge):
flag = 0
for char in user_str:
if char == user_judge:
flag = 1
if flag == 0:
return False
else:
return True
print("结果是:%s" % m_in(str1, judge))
17.写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
例如: 原字符串: 'how are you? and you?' 旧字符串: 'you' 新字符串:'me' 结果: 'how are me? and me?'
str1 = input("输入字符串")
old = input("输入旧字符串")
new = input("输入新字符串")
def m_replace(user_str, user_old, user_new):
new_str = ''
index = 0
while index < len(user_str):
# 如果开头的字符相同则继续往下判断
if user_str[index] == user_old[0]:
flag = 1
for index_again in range(len(user_old)):
# 遇到不同的字符 则flag为0
if user_str[index+index_again] != user_old[index_again]:
flag = 0
# flag为1表示相同,用new替换old 不是就用原字符串替换
if flag == 1:
for char in user_new:
new_str += char
index += len(user_old)
else:
new_str += user_str[index]
index += 1
else:
new_str += user_str[index]
index += 1
return new_str
print("新字符串是:%s" % m_replace(str1, old, new))
18.写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能
list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5, 6]
def intersection(list_one, list_two):
new_list = []
for items in list_one:
if items in list_two:
new_list.append(items)
return new_list
print("交集是%s" % intersection(list1, list2))
def union(list_one: list, list_two):
for items in list_two:
if items not in list_one:
list_one.append(items)
list_two = [1, 2, 3]
return list_one
print("并集是%s" % union(list1, list2), list2)
list1 = [1, 2, 3, 4, 6, 7]
list2 = [2, 3, 4, 5, 6]
def difference(list_one, list_two):
new_list = []
for items in list_one:
if items not in list_two:
new_list.append(items)
return new_list
print("差集是%s" % difference(list1, list2))
def symmetric(list_one, list_two):
new_list = []
for items in list_one:
if items not in list_two:
new_list.append(items)
for items in list_two:
if items not in list_one:
new_list.append(items)
return new_list
print("补集是%s" % symmetric(list1, list2))
- 写一个匿名函数,判断指定的年是否是闰年
leapp = lambda user_year: bool((user_year % 4 == 0 and user_year % 100 != 0) or user_year % 400 == 0)
year = int(input("输入年份"))
print("%d是闰年吗?%s" % (year, leapp(year)))
2.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自带的逆序函数)
list1 = [1, 2, 3]
def reverse(user_list):
new_list=[]
for items in user_list[::-1]:
new_list.append(items)
return new_list
print(reverse(list1))
3.写一个函数,获取指定列表中指定元素的下标(如果指定元素有多个,将每个元素的下标都返回)
例如: 列表是:[1, 3, 4, 1] ,元素是1, 返回:0,3
list1 = [1, 3, 4, 1]
def list_index(user_list, num):
index_list = []
for index in range(len(user_list)):
if user_list[index] == num:
index_list.append(index)
return index_list
print("下标是:%s" % list_index(list1, 1))
4.写一个函数,能够将一个字典中的键值对添加到另外一个字典中(不使用字典自带的update方法)
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e':5}
def m_update(dict_one, dict_two):
for key in dict_two:
if key not in dict_one:
dict_one[key] = dict_two[key]
return dict_one
print(m_update(dict1, dict2))
5.写一个函数,能够将指定字符串中的所有的小写字母转换成大写字母;所有的大写字母转换成小写字母(不能使用字符串相关方法)
str1 = input("输入一串字母:")
def change(user_str):
new_str = ''
for items in user_str:
if 'a' <= items <= 'z':
new_str += chr(ord(items)-32)
elif 'A' <= items <= 'Z':
new_str += chr(ord(items)+32)
else:
new_str += items
return new_str
print("新字符串是:%s" % change(str1))
- 实现一个属于自己的items方法,可以将自定的字典转换成列表。
列表中的元素是小的列表,里面是key和value (不能使用字典的items方法)
例如:{'a':1, 'b':2} 转换成 [['a', 1], ['b', 2]]
dict1 = {'a': 1, 'b': 2}
def m_itemst(user_dict):
out_list = []
for key in user_dict:
in_list = [key, user_dict[key]]
out_list.append(in_list)
return out_list
print(m_items(dict1))
7.写一个函数,实现学生的添加功能:
=============添加学生================
输入学生姓名: 张胜
输入学生年龄: 23
输入学生电话: 15634223
===添加成功!
'姓名':'张胜', '年龄':23, '电话:15634223', '学号':'0001'
=====================================
1.继续
2.返回
请选择: 1
=============添加学生================
输入学生姓名: 李四
输入学生年龄: 18
输入学生电话: 157234423
===添加成功!
'姓名':'张胜', '年龄':23, '电话:15634223', '学号':'0001'
'姓名':'李四', '年龄':18, '电话:157234423', '学号':'0002'
=====================================
1.继续
2.返回
请选择:
number = 1
all_student = []
choose = 1
while choose == 1:
print("=============添加学生================")
stu_name = input("输入学生姓名:")
stu_age = input("输入学生年龄:")
stu_tel = input("输入学生电话:")
stu_number = str(number)
stu_dict = {'姓名': stu_name, '年龄': stu_age, '电话': stu_tel, '学号': stu_number.rjust(3, '0')}
all_student.append(stu_dict)
print(all_student)
print("===添加成功!")
for stu in all_student:
print(stu)
print("=====================================")
print("1.继续")
print("2.返回")
choose = int(input())
number += 1