这个是我自己学习的时候编写的代码,有看到错误的地方可以留言指正哟,我们一起进步呀
目录
01 输入输出
NP1 Hello World!
str = 'Hello World!'
print(str)
NP2 多行输出
str1 = 'Hello World!'
str2 = 'Hello Nowcoder!'
print(str1+'\n'+str2) # \n 是换行符
NP3 读入字符串
str = input()
print(str)
NP4 读入整数数字
a = int(input()) # 输入一个字符串
print(a) # 输出字符串
print(type(a)) # type函数查询变量类型
NP5 格式化输出(一)
name = str(input())
# 1.f-字符串输出
# print(f"I am {name} and I am studying Python in Nowcoder!")
# 2.format字符串格式化输出
# print("I am {} and I am studying Python in Nowcoder!".format(name))
# 3.占位符 格式化输出
print("I am %s and I am studying Python in Nowcoder!"%name)
NP6 牛牛的小数输出
num = float(input())
# %.2f 将浮点数四舍五入保留小数点后两位
# print('%.2f' % num)
# round返回浮点数x的四舍五入值
print(round(num, 2))
02 类型转换
NP7 小数化整数
num = float(input())
# 强制转转换格式:数据类型(变量名)
print(int(num))
NP8 为整数增加小数点
num = int(input()) # 输入一个int型数据
num_float = float(num) # 强制转换为浮点型
print(num_float) # 输出num_float
print(type(num_float)) # type函数查询变量的数据类型
NP9 十六进制数字的大小
a = input() # 输入一个数字
b = int(a, 16) # 按照十六进制进行转换为整数
print(b) # 输出转换后的数据
03 字符串
NP10 牛牛最好的朋友们
str1 = input()
str2 = input()
# 1.+号连接符输出
# print(str1 + str2)
# 2.join方法
print("".join([str1, str2]))
NP11 单词的长度
str = input() # 输入字符串
length = len(str) # len方法获取长度
print(length) # 输出长度值
NP12 格式化输出(二)
str = input() # 输入一个字符串
print(str.lower()) # 全部小写
print(str.upper()) # 全部大写
print(str.title()) # 首字母大写
NP13 格式化输出(三)
name = input()
# strip方法删除首尾空格
print(name.strip())
NP14 不用循环语句的重复输出
str = input()
print(str*100)
NP15 截取用户名前10位
str = input()
# 变量名[起始下标:终点下标]
print(str[:10])
知识点:
- 起始下标不标明的默认是0,终点下标不标明的默认最后一个字符的下标+1
- 切片包头不包尾,如上例子就不包含下标10的字符
04 列表
NP16 发送offer
# 定义一个列表
offer_list = ["Allen", "Tom"]
# 遍历列表的名称并输出相关信息
for i in offer_list:
print(f'{i}, you have passed our interview and will soon become a member of our company.')
# 将TOM修改为Andy
offer_list[1] = "Andy"
# 遍历列表并输出相关信息
for i in offer_list:
print(f'{i}, welcome to join us!')
NP17 生成列表
list = input()
# split方法拆分字符串
print(list.split())
NP18 生成数字列表
# 以空格为分隔符将输入分割成多个字符串,再转换成整型
s = map(int,input().split())
print(list(s))
map函数知识点:
基本语法:map(function, iterable, ...)
- function:函数名,用于对每个可迭代对象的元素执行操作。
- iterable:一个或多个可迭代对象,可以是range函数、字符串、列表、元组、集合、字典等。(Tip:字典被操作的是字典的键)。
NP19 列表的长度
# 输入字符串,以空格为间隔
str1 = input().split()
# 将str1转换成列表
str2 = list(str1)
# 输出列表的长度
print(len(str2))
NP20 增加派对名单(一)
name = input()
# 将name转换成列表,以空格为间隔
name_list = list(name.split())
# 添加列表元素Allen
name_list.append('Allen')
# 输出列表
print(name_list)
NP21 增加派对名单(二)
# 输入字符串,因为下面以空格为分隔符,所以输入的时候也要以空格输入多个字符
name = input()
# 将name转换成列表,以空格为间隔
name_list = list(name.split())
# insert(下标, 插入的元素)
name_list.insert(0,'Allen')
# 输出列表
print(name_list)
NP22 删除简历
name = input()
name_list = list(name.split())
# 删除列表的下标为0的元素
del name_list[0]
print(name_list)
NP23 删除好友
name1 = input().split()
name2 = input()
# 将name1输入的名字转换为列表
name_list = list(name1)
# remove方法删除name2这个名字
name_list.remove(name2)
print(name_list)
NP24 淘汰排名最后的学生
name = input().split()
name_list = list(name)
# for遍历删除前三个名字,也就是列表下标0 1 2的元素
for i in range(3):
name_list.pop()
# 输出列表
print(name_list)
NP25 有序的列表
my_list = ['P','y','t','h','o','n']
# sorted一般是按照字母顺序(ASCII)、数值大小顺序来排序的
my_list2 = sorted(my_list)
print(my_list2) # 输出排序后的列表
print(my_list) # 输出原列表
# reverse=True降序, reverse= False升序(默认就是升序)
my_list.sort(reverse=True)
print(my_list)
NP26 牛牛的反转列表
num = [3, 5, 9, 0, 1, 9, 0, 3]
num.reverse()
print(num)
NP27 朋友们的喜好
name = ['Niumei', 'YOLO', 'Niu Ke Le', 'Mona']
friends = []
# 将name列表添加到friends里
friends.append(name)
food = ['pizza', 'fish', 'potato', 'beef']
number = [3, 6, 0, 3]
# 将food列表添加到friends末尾
friends.append(food)
# 将number列表添加到friends末尾
friends.append(number)
# 输出friends列表
print(friends)
NP28 密码游戏
# 输入四位整型的密码
num = int(input())
# 将num保留为4位数
num_int = "{:04d}".format(num)
# 定义一个字符串变量存放计算好的数字
pw = str()
# 讲计算好的数字存放到列表
result = []
# 遍历计算num_int的数字
for i in range(len(num_int)):
# 将计算好的值存放到pw里面
pw = str((int(num_int[i]) + 3) % 9)
# 将pw添加到列表存放
result.append(pw)
# 第1位和第3位数字交换,第2位和第4位数字交换(每个位置一一对应)
result[0], result[1], result[2], result[3] = result[2], result[3], result[0], result[1]
# 将列表的元素不间隔输出
pw_result = "".join(result)
# 输出破解的密码
print(pw_result)
NP29 用列表实现栈
stack = [1, 2, 3, 4, 5]
# pop删除元素(括号不标明下标默认删除最后一个)
stack.pop()
print(stack)
stack.pop()
print(stack)
# 添加一个整型数字
stack.append(int(input()))
print(stack)
NP30 用列表实现队列
queue = [1, 2, 3, 4, 5]
# pop删除下标为0的元素
queue.pop(0)
print(queue)
# pop删除下标为0的元素
queue.pop(0)
print(queue)
# 输入一个数字,并添加到queue列表末尾
num = int(input())
queue.append(num)
print(queue)
NP31 团队分组
group_list = ['Tom', 'Allen', 'Jane', 'William', 'Tony' ]
# 切片包头不包尾
print(group_list[0:2])
print(group_list[1:4])
print(group_list[3:5])
05 运算符
NP32 牛牛的加减器
x = int(input())
y = int(input())
print(x+y)
print(x-y)
NP33 乘法与幂运算
x = int(input())
y = int(input())
print(x*y)
print(x**y)
NP34 除法与取模运算
x = int(input())
y = int(input())
a = x//y # 整除
b = x%y # 取余
print(a,b)
c = x/y # 除
print('%.2f'%c) # 保留小数点后两位数
NP35 朋友的年龄是否相等
age_niuniu, age_friend = input().split()
print(age_niuniu==age_friend)
NP36 谁的数字大
num1, num2 = input().split()
print(num1 > num2)
print(num1 < num2)
NP37 不低于与不超过
k, x, y = input().split()
k, x, y = float(k), float(x), float(y)
print(k <= x)
print(k >= y)
NP38 牛牛的逻辑运算
x, y = input().split()
x, y = int(x), int(y)
print(x and y)
print(x or y)
print(not x)
print(not y)
NP39 字符串之间的比较
str1 = input()
str2 = input()
print( str1==str2 )
print( (str1.lower()) == (str2.lower()) )
NP40 俱乐部的成员
list1 = input().split()
name = input()
print(name in list1)
NP41 二进制位运算
x, y = input().split()
x, y = int(x), int(y)
print(x&y)
print(x|y)
NP42 公式计算器
x, y, z, k = input().split()
x, y, z, k = int(x), int(y), int(z), int(k)
print( (x+y)*(z-k) )
06 条件语句
NP43 判断布尔值
num = bool(int(input()))
if num==1:
print("Hello World!")
else:
print("Erros!")
NP44 判断列表是否为空
my_list = []
if len(my_list) == 0:
print('my_list is empty!')
else:
print('my_list is not empty!')
NP45 禁止重复注册
current_users = ['Niuniu','Niumei','GURR','LOLO']
new_users = ['GurR','Niu Ke Le','LoLo','Tuo Rui Chi']
# 遍历current_users将数据全部小写输出
for i in range(len(current_users)):
current_users[i] = current_users[i].lower()
# 遍历new_users
for k in new_users:
# 判断new_users全部小写之后是否存在于current_users
if k.lower() in current_users:
print(f'The user name {k} has already been registered! Please change it and try again!')
else:
print(f'Congratulations, the user name {k} is available!')
这里需要注意一下题目说的(注:用户名的比较不区分大小写),我们就可以将两个列表都全部大写或者全部小写之后在进行判断。
NP46 菜品的价格
str1 = input()
if str1 == 'pizza':
print(10)
elif str1 == 'rice':
print(2)
elif str1 == 'yogurt':
print(5)
else:
print(8)
NP47 牛牛的绩点
dict1 = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F': 0}
score_num, grade_num, grade_nums = 0, 0, 0
while True:
# 输入等级
grade = input()
# 判断输入的为False就跳出while循环
if grade == 'False':
break
# 输入分数
score = float(input())
# 每门课学分乘上单门课绩点
grade_num = dict1[grade]*score
# print(grade_num)
# 每门课学分乘上单门课绩点,多门学科求和
grade_nums += grade_num
# print(grade_nums)
# 学分求和
score_num += score
# print(score_num)
# 输出均绩,结果保留两位小数
print('%.2f' % (grade_nums/score_num))
NP48 验证登录名与密码
user_name = input()
password = input()
# 判断用户名ID和密码是否一致
if user_name == 'admis' and password == 'Nowcoder666':
print("Welcome!")
else:
print("user id or password is not correct!")
07 循环语句
NP49 字符列表的长度
my_list = ['P','y','t','h','o','n']
print('Here is the original list:')
print(my_list, '\n')
print('The number that my_list has is:')
print(int(len(my_list)))
NP50 程序员节
user_list = ['Niuniu', 'Niumei', 'Niu Ke Le']
# 遍历user_list
for name in user_list:
print(f'Hi, {name}! Welcome to Nowcoder!')
print( "Happy Programmers' Day to everyone!")
NP51 列表的最大与最小
# 创建一个空列表
list1 = []
# 遍历添加10到50的数字
for num in range(10, 51):
list1.append(num)
# 输出列表
print(list1)
# 输出列表的首尾元素
# print(f'{list1[0]} {list1[-1]}')
print(list1[0], list1[-1], end=' ')
NP52 累加数与平均值
num = input().split()
res = 0
# 遍历num的元素
for age in num:
# 将年龄累加起来
res += int(age)
# 求年龄的平均数
ave = res/len(num)
# 输出总年龄总和和平均数
print('%d %.1f'%(res,ave))
NP53 前10个偶数
my_list = []
# 现在题目求的是0到19的偶数,所以我的终点值还是用的19,大家可以用20,都是可以的
for i in range(0, 19, 2):
my_list.append(i)
# 输出偶数
for i in my_list:
print(i)
NP54 被5整除的数字
my_list = []
# 遍历1到50
for i in range(1,51):
# 判断数值能否被5整除
if i%5 == 0:
my_list.append(i)
# 遍历输出能被5整除的数字
for i in my_list:
print(i)
NP55 2的次方数
my_list = []
# 遍历1到10
for i in range(1, 11):
# 将次方数添加到列表
my_list.append(2**i)
# 遍历输出次方数
for i in my_list:
print(i)
NP56 列表解析
# 列表推导式创建一个列表
list1 = [i for i in range(0,10)]
print(list1)
代码理解:
[i for i in range(0,10)]
表示对于 range(0,10)
这个序列中的每一个元素 i
,都将其作为列表中的一个元素。range(0,10)
会生成从 0 到 9 的整数序列,所以最终得到的 list1
就是包含 0 到 9 这 10 个整数的列表。
NP57 格式化清单
list1 = ['apple', 'ice cream', 'watermelon', 'chips', 'hotdogs', 'hotpot']
i = 0
# 判断是否在list1的长度里面
while i<len(list1):
# 删除末尾的元素
list1.pop()
# 输出列表
print(list1)
NP58 找到HR
users_list = ["Niuniu", "Niumei", "HR", "Niu Ke Le", "GURR", "LOLO"]
# 遍历users_list
for name in users_list:
# 判断是不是HR
if name == "HR":
print("Hi, HR! Would you like to hire someone?")
else:
print(f"Hi, {name}! Welcome to Nowcoder!")
NP59 提前结束的循环
num_list = [3, 45, 9, 8, 12, 89, 103, 42, 54, 79]
# 输入一个数字
x = int(input())
# 遍历num_list
for i in num_list:
# 判断x在不在num_list里面
if i == x:
break # 结束循环
else:
print(i)
NP60 跳过列表的某个元素
list1 = []
# 遍历1到15
for i in range(1, 16):
if i == 13:
continue # 跳出本次循环
else:
list1.append(str(i))
# 以空格为间隔输出列表元素
print(' '.join(list1))
NP61 牛牛的矩阵相加
list1 = [[1,2,3],[4,5,6],[7,8,9]]
# 输入一个数字
n = int(input())
# 定义一个空列表存放计算后的元素
list2 = []
for item in list1:
# 子列表的每个元素通过[i*n for i in item]生成新的列表,每个元素都乘n
list2.append([i*n for i in item])
# 输出列表list2
print(list2)
08 元组
NP62 运动会双人项目
name1 = input()
name2 = input()
print((name1, name2))
NP63 修改报名名单
entry_form = ('Niuniu','Niumei')
print(entry_form)
# try-except 异常处理
try:
entry_form[1] = 'Niukele'
except TypeError:
print('The entry form cannot be modified!')
NP64 输出前三同学的成绩
name = input().split()
# 截取元组下标0 1 2的元素
print(tuple(name[:3]))
NP65 名单中出现过的人
tuple1 = ('Tom', 'Tony', 'Allen', 'Cydin', 'Lucy', 'Anna')
name = input()
# 输出元组
print(tuple1)
# 判断name是否存在元组里
if name in tuple1:
print('Congratulations!')
else:
print('What a pity!')
NP66 增加元组的长度
# 创建一个1到5的元组
tuple1 = (1, 2, 3, 4, 5)
# 创建一个6到10的元组
tuple2 = tuple(range(6, 11))
# 输出1到5的元组
print(tuple1)
# 输出元组的长度
print(len(tuple1))
# 元组1和元组2拼接起来
print(tuple1+tuple2)
# 输出拼接后的元组的长度
print(len(tuple1+tuple2))
09 字典
NP67 遍历字典
# 创建字典operators_dict
operators_dict = { '<': 'less than', '==': 'equal' }
# 按题目要求输出
print('Here is the original dict:')
# 遍历临时排序后的operators_dict的键
for i in sorted(operators_dict.keys()):
# 输出相应的信息,i是键,operators_dict[i]是键值
print(f'Operator {i} means {operators_dict[i]}.')
# 在末尾增加键值对
operators_dict['>'] = 'greater than'
# 按题目要求输出
print('\nThe dict was changed to:')
# 遍历临时排序后的operators_dict的键
for j in sorted(operators_dict.keys()):
# 输出相应的信息,j是键,operators_dict[j]是键值
print(f'Operator {j} means {operators_dict[j]}.')
NP68 毕业生就业调查
# 创建列表survey_list
survey_list = ['Niumei','Niu Ke Le','GURR','LOLO']
# 创建字典result_dict
result_dict = {'Niumei': 'Nowcoder','GURR': 'HUAWEI'}
# 遍历survey_list
for i in survey_list:
# 判断是否在result_dict的键里面
if i in result_dict.keys():
print(f'Hi, {i}! Thank you for participating in our graduation survey!')
else:
print(f'Hi, {i}! Could you take part in our graduation survey?')
NP69 姓名与学号
# 按要求创建my_dict_1、my_dict_2、my_dict_3
my_dict_1 = {'name': 'Niuniu','Student ID': 1}
my_dict_2 = {'name': 'Niumei','Student ID': 2}
my_dict_3 = {'name': 'Niu Ke Le','Student ID': 3}
# 创建一个空列表
dict_list = []
# 将字典添加到列表里面
dict_list.append(my_dict_1)
dict_list.append(my_dict_2)
dict_list.append(my_dict_3)
# 遍历输出信息
for i in dict_list:
print(f"{i['name']}'s student id is {i['Student ID']}.")
NP70 首都
cities_dict = { 'Beijing': {'Capital': 'China'},'Moscow': {'Capital': 'Russia'},'Paris': {'Capital': 'France'} }
# 遍历输出临时排序后的cities_dict的信息
for i in sorted(cities_dict.keys()):
print(f"{i} is the capital of {cities_dict[i]['Capital']}!")
NP71 喜欢的颜色
# 创建字典result_dict
result_dict = { 'Allen': ['red', 'blue', 'yellow'],'Tom': ['green', 'white', 'blue'],'Andy': ['black', 'pink'] }
# 遍历临时排序后的result_dict
for i in sorted(result_dict.keys()):
# 输出语句
print(f"{i}'s favorite colors are:")
# 遍历每个字典对应的键的键值
for j in range(len(result_dict[i])):
print(result_dict[i][j])
NP72 生成字典
key = input().split()
value = input().split()
print(dict(zip(key, value)))
zip()函数知识点:
-
函数用于将可迭代的对象(如列表、元组、字符串等)作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象。
-
如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表
语法格式:zip([iterable, ...]),iterable是可迭代对象(如列表、元组、字符串等)。
NP73 查字典
dict1 = {'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
# 输入一个字母
char1 = input()
# 判断是否在dict1的键里
if char1 in dict1.keys():
# 遍历dict1键值长度
for i in range(len(dict1[char1])):
# 输出对应的键值元素
print(dict1[char1][i], end=' ')
NP74 字典新增
dict1 = {'a': ['apple', 'abandon', 'ant'], 'b': ['banana', 'bee', 'become'], 'c': ['cat', 'come'], 'd': 'down'}
letter = input()
word = input()
# 添加字典键值对
dict1[letter] = word
print(dict1)
NP75 使用字典计数
# 输入一个单词
word = input()
# 定义一个空字典来存放字符串的字符和次数
dict1 = {}
# 遍历字符串
for i in word:
# 判断i在不在字典里面
# 如果在字典里
if i in dict1:
# 字典对应的键值+1
dict1[i] = dict1[i] + 1
# 如果不在字典里
else:
# 添加字典键值对
dict1[i] = 1
# 输出字典
print(dict1)
10 内置函数
NP76 列表的最值运算
num = input().split()
list1 = list(map(int,num))
print(f"{max(list1)}\n{min(list1)}")
NP77 朋友的年龄和
# 输入一串年龄,以空格间隔
age = input().split()
# 将年龄转换为整型存放到列表
list1 = list(map(int, age))
# sum计算列表元素总和
print(sum(list1))
NP78 正数输出器
num = int(input())
print(abs(num))
NP79 字母转数字
char1 = input()
print(ord(char1))
NP80 数字的十六进制
num = int(input())
print(hex(num))
NP81 数字的二进制表示
num = int(input())
print(bin(num))
NP82 数学幂运算
x, y = input().split()
x = int(x)
y = int(y)
print(pow(x, y))
print(pow(y, x))
NP83 错误出现的次数
# 输入数字,空格为间隔
num = input().split()
# 将输入的数字存入列表
list1 = list(map(int,num))
# 计算出现的0出现的次数
print(list1.count(0))
NP84 列表中第一次出现的位置
name = input().split()
name_list = list(name)
print(name_list.index('NiuNiu'))
NP85 字符的类型比较
str1 = input()
# 判断是否含字母
print(str1.isalpha())
# 判断是否含数字
print(str1.isdigit())
# 判断是否含空格
print(str1.isspace())
NP86 字符子串的查找
long_str = input()
print(long_str.find('NiuNiu'))
# 没有找到就会返回-1
NP87 子串的数量
patten = input()
print(patten.count('Niu'))
# 这个没找到就返回0
NP88 句子拆分
str1 = input()
# 以空格为间隔拆分str1字符串并返回一个列表
print(str1.split())
NP89 单词造句
# 定义一个空列表存放输入的单词
res = []
# 循环输入单词
while True:
word = input()
# 如果判断到输入为0,结束循环
if word == '0':
break
else:
res.append(word)
# 以空格为间隔输出res列表
print(' '.join(res))
NP90 修正错误的字母
str1 = input()
print(str1.replace('a*', 'ab'))
NP91 小数位修正
num = float(input())
print(round(num, 2))
NP92 公式计算器
res = input()
print(eval(res))
NP93 创建集合
# 以空格为间隔 输入多个字符串
name = input().split()
# 将字符串转换成集合存储
name_set = set(name)
# 输出排序后的集合
print(sorted(name_set))
11 面向对象
NP94 函数求差
# 输入两个整数x y
x = int(input())
y = int(input())
# 定义函数计算差值
def cal(a, b):
return a-b
# 调用函数输出结果
print(cal(x,y))
print(cal(y,x))
NP95 兔子的数量
def f(n):
# n是1的时候,只有2只兔子
if n == 1:
return 2
# n是2的时候,只有3只兔子
elif n == 2:
return 3
# 后面的就是f(n)=f(n-1)+f(n-2)
else:
return f(n-1) + f(n-2)
# 输出计算结果
print(f(int(input())))
NP96 球的表面积
# 导入math库
import math
# 定义球的半径列表
r_list = [1, 2, 4, 9, 10, 13]
# 定义一个函数计算球的表面积
def v(r):
return 4*math.pi*(r**2)
# 遍历半径,输出球的表面积
for i in r_list:
print(round(v(i), 2))
NP97 班级管理
# 定义一个Student类
class Student:
# 初始化方法
def __init__(self, name, studentID, score, grade) -> None:
self.name = name
self.studentID = studentID
self.score = score
self.grade = grade
# 定义putStr方法输出学生的信息
def putStr(self):
print(f"{self.name}'s student number is {self.studentID}, and his grade is {self.score}. He submitted {len(self.grade)} assignments, each with a grade of {' '.join(self.grade)}")
# 输出对应的信息
name = input()
studentID = input()
score = input()
grade = input().split()
# 实例化对象
student = Student(name, studentID, score, grade)
# 输出对象的信息
student.putStr()
NP98 修改属性1
# 定义一个Employee类
class Employee:
# 初始化方法
def __init__(self, name, salary) -> None:
self.name = name
self.salary = salary
# 定义printclass方法
def printclass(self):
# try-except异常处理
try: # 编写会报错的代码
print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")
except: # 对应的措施
print("Error! No age")
# 输入对应的信息
name = input()
salary = int(input())
age1 = int(input())
# 实例化对象
e = Employee(name, salary)
# 输出对应的信息
e.printclass()
# 添加age属性
e.age = age1
# 输出信息
e.printclass()
NP99 修改属性2
# 定义Employee类
class Employee:
# 初始化方法
def __init__(self, name, salary) -> None:
self.name = name
self.salary = salary
# 定义printclass方法
def printclass(self):
# try-except异常处理
# try 可能报错的语句
try:
print(f"{self.name}'salary is {self.salary}, and his age is {self.age}")
# 执行措施
except:
# 检验实例有没有属性age,返回True或False
print(hasattr(e, 'age'))
# 实例化对象
e = Employee(input(), int(input()))
# 检验实例有没有属性age,返回True或False
print(hasattr(e, 'age'))
# 判断实例有没有属性age
if hasattr(e, 'age'):
e.printclass()
else:
# 为实例e添加属性age,并输入值
setattr(e, 'age', input())
# 输出相关信息
e.printclass()
NP100 重载运算
# 定义Coordinate类
class Coordinate:
# 初始化方法
def __init__(self, x, y):
self.x = x
self.y = y
# 输出坐标(x, y)
def __str__(self):
return f"({self.x}, {self.y})"
# 横坐标+横坐标,纵坐标+纵坐标c
def __add__(self, c):
return Coordinate(self.x + c.x, self.y+c.y)
# 输入相关数据
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
# 实例化对象c1和c2
c1 = Coordinate(x1, y1)
c2 = Coordinate(x2, y2)
c3 = c1.__add__(c2)
print(c3)
12 正则表达式
NP101 正则查找网址
import re
str1 = input()
print(re.match('https://www', str1).span()) # 在起始位置匹配
# re.match(匹配的正则表达式, 需要匹配的字符)
NP102 提取数字电话
import re
str1 = input()
# 将非数字的都匹配为空字符
print(re.sub(r'\D', '', str1))
# r'\D':匹配任何非数字字符
NP103 截断电话号码
import re
text = input()
# 将#和#后面的字符替换为空字符
new_text = re.sub(r'#.*', '', text)
# 输出新的文本
print(new_text)