赞
踩
本文为牛客的在线编程的python入门题集的个人解析
本人主语言C/C++ 来这边刷一下python的入门语法题,这个题库很基础很入门真的就是纯考python语法
本文虽然是展示AC代码,但实际是为了记录python的各种基础语法,便于以后遗忘了可以查看
本文代码默认在python3环境
牛客的环境是版本:Python3.9,支持大部分的常用库。Numpy库与SciPy库默认不支持,请根据题目要求查看是否支持。
# python 中的字符串
# 用单引号或者双引都可以
# 结尾加不加;都可以
# 这两点和JavaScript很像
print("Hello World!")
str1 = "Hello World!"
str2 = 'Hello Nowcoder!'
print(str1)
print(str2);
##################################
# print默认换行,中间可以用转移符\n换行
print("Hello World!\nHello Nowcoder!")
# python的输入input()默认输入的就是字符串
str = input()
print(str)
#########################
# 可以直接在输入作为输出的参数
print(input())
这里输出
<class 'int'>
猜测python中所有类型都封装成了类
# 将读入的字符串强转成数值型
num = int(input())
print(num)
# type()函数,返回变量的类型
print(type(num))
name = input()
# 单纯的字符串拼接
print("I am " + name + " and I am studying Python in Nowcoder!")
# 都号分割,默认每两个之间有一个空格
print("I am", name, "and I am studying Python in Nowcoder!")
# 类似于C语言的printf输出
print('I am %s and I am studying Python in Nowcoder!' %name)
# .format() 默认
print('I am {} and I am studying Python in Nowcoder!' .format(name))
# .format() 加上位置
print('I am {0} and I am studying Python in Nowcoder!' .format(name))
# .format() 指定参数
print('I am {str} and I am studying Python in Nowcoder!' .format(str = name))
# 字符串前加个f则可直接将变量嵌入输出
print(f'I am {str} and I am studying Python in Nowcoder!')
num = float(input())
# 用C语言式方便
print("%.2f" %num)
# f用冒号加入参数 注意冒号后不要加空格
print(f"{num :.2f}")
# .format() 型类似
print("{:.2f}".format(num))
fnum = float(input())
inum = int(fnum)
print(inum)
#################################
# 调用math的trunc()函数,截取整数部分
import math
print(math.trunc(float(input())))
num = int(input())
print("%.1f" %num)
# 直接float()也行 这样会返回一个0.0
print(type(float()))
# python没有字符型变量,至于长度为1的字符串
num = input()
# 第二个参数指定进制
print(int(num, 16))
str1 = input()
str2 = input()
print(str1 + str2)
str = input()
# len函数
print(len(str))
# 类函数__len__()
print(str.__len__())
name = input()
# 首字母大写
print(name.lower())
# 全大写
print(name.upper())
# 全小写
print(name.title())
str = input()
# 去除两侧的空格
print(str.strip())
str = input()
# 直接用*复制
print(str * 100)
str = input()
# [begin, end)
print(str[0 : 10])
# 默认从0开始
print(str[: 10])
list = ["Allen", "Tom"] for str in list : print("{s}, you have passed our interview and will soon become a member of our company." .format(s = str)) # 移除 list.remove("Tom") # 末尾添加 list.append("Andy") for str in list : print("%s, welcome to join us!" %str) ######################## # 多行字符串 ,这个居然不能过 print('''Allen, you have passed our interview and will soon become a member of our company. Andy, you have passed our interview and will soon become a member of our company. Allen, welcome to join us! Andy, welcome to join us!''')
str = input();
# 分割,默认按照空格生成列表
print(str.split())
# 可以添加分割的参数
print(str.split(' '))
# 分割出来默认式字符串,本题要数字
arr = [int(x) for x in input().split()]
print(arr)
list = input().split()
# len函数
print(len(list))
# 内置__len__()
print(list.__len__())
list = input().split()
list.append("Allen")
print(list)
list = input().split()
# insert(位置, 内容)
list.insert(0, "Allen")
print(list)
myList = input().split()
# 删除第一个
del myList[0]
# [begin, end)
# del myList[0 : 1]
# 指定移除
#myList.remove(myList[0])
print(myList)
list = input().split()
str = input()
# 指定移除
# myList.remove(str)
# index(data, begin, end)
idx = list.index(str)
del list[idx]
print(list)
myList = input().split()
# 切片 负数表示倒着来
del myList[-3 : ]
print(myList)
#################
# 指定倒数输出的位置
print(lis[:-3])
my_list = [x for x in "Python"]
# sorted不改变远列表,有返回值
print(sorted(my_list))
print(my_list)
print(sorted(my_list, reverse = True))
num = [3, 5, 9, 0, 1, 9, 0, 3]
# reversed()函数
print(list(reversed(num)))
#################
# 步长为-1,表示倒着
print(num[::-1])
name = ['Niumei', 'YOLO', 'Niu Ke Le', 'Mona']
food = ['pizza', 'fish', 'potato', 'beef']
num = [3, 6, 0, 3]
list = []
# list任何东西都能append进去
# 类似JavaScript中的一个对象
list.append(name)
list.append(food)
list.append(num)
print(list)
list = [int(x) for x in input()]
# 这里的遍历是非引用型
for i in range(len(list)):
# list[i]是引用
list[i] = (list[i] + 3) % 9
# 一点计算机思维都没有
list[0], list[1], list[2], list[3] = list[2], list[3], list[0], list[1]
# 根据前面的串连接
print("".join(map(str, list)))
# 列表模拟栈
stack = [1, 2, 3, 4, 5]
# pop可以指定位置
stack.pop(-1)
print(stack)
# 默认pop最后一个
stack.pop()
print(stack)
num = int(input())
stack.append(num)
print(stack)
# pop(0) 或者remove queue = [1, 2, 3, 4, 5] queue.pop(0) print(queue) queue.remove(queue[0]) print(queue) num = int(input()) queue.append(num) print(queue) ########## # 用双端队列 from collections import deque queue = deque([1, 2, 3, 4, 5]) queue.popleft() print(list(queue)) queue.popleft() print(list(queue)) num = int(input()) queue.append(num) print(list(queue))
# 就是练分片
arr = ['Tom', 'Allen', 'Jane', 'William', 'Tony']
print(arr[0 : 0 + 2])
print(arr[len(arr) // 2 - 1 : len(arr) // 2 - 1 + 3])
print(arr[-2: ])
num1 = int(input())
num2 = int(input())
print(num1 + num2)
print(num1 - num2)
x = int(input())
y = int(input())
print(x * y)
print(x y)
x = int(input())
y = int(input())
# // 整数除法
print(x // y, x % y)
# / 浮点数除法
print("%.2f" %(x / y))
# 这里用字符串比较一样
a, b = input().split()
print(a == b)
# 化成列表比较单个元素
list = input().split()
print(list[0] == list[1])
# 分割后用map函数转化成指定的类型赋值
x, y = map(int, input().split())
print(x > y)
print(x < y)
x, maxx, minn = map(float, input().split())
print(x <= maxx)
print(x >= minn)
x, y = map(int, input().split())
# python 中逻辑运算是用关键词
print(x and y) # 与
print(x or y) # 或
print(not x) # 非
print(not y)
str1 = input()
str2 = input()
print(str1 == str2)
print(str1.lower() == str2.lower())
list = input().split()
name = input()
# 关键词 in
print(name in list)
x, y = map(int, input().split())
# 38题这么写就不行
print(x & y)
print(x | y)
x, y, z, k = map(int, input().split())
print((x + y) * (z - k))
num = int(input())
# 非0即1
if num :
print("Hello World!")
else :
print("Erros!")
my_list = []
# 判空的方式比较多
# if my_list == [] :
# if not my_list:
if len(my_list) == 0 :
print("my_list is empty!")
else :
print("my_list is not empty!")
current_users = ['Niuniu', 'Niumei', 'GURR', 'LOLO']
new_users = ['GurR', 'Niu Ke Le', 'LoLo', 'Tuo Rui Chi']
for name in new_users :
if name.lower() in [s.lower() for s in current_users] :
print("The user name %s has already been registered! Please change it and try again!" %name)
else :
print("Congratulations, the user name %s is available!" %name)
# elif 不是 else if
# 当然本题可以用字典来写
str = input()
if str == 'pizza':
print(10)
elif str == 'rice':
print(2)
elif str == 'yogurt':
print(5)
else:
print(8)
# 阅读理解题 endInput = 'False' sum1, sum2 = 0.0, 0.0 flag = 0.0 # 读到endInput截止 for line in iter(input, endInput): if line == 'A': flag = 4.0 elif line == 'B': flag = 3.0 elif line == 'C': flag = 2.0 elif line == 'D': flag = 1.0 elif line == 'F': flag = 0.0 else: sum1 += float(line) sum2 += float(line) * flag print("%.2f" %(sum2 / sum1))
username = input()
password = input()
if username == 'admis' and password == 'Nowcoder666':
print('Welcome!')
else:
print("user id or password is not correct!")
list = ['P', 'y', 't', 'h', 'o', 'n']
print("Here is the original list:")
print(list, end="\n\n")
print("The number that my_list has is:")
print(len(list))
users_list = ['Niuniu', 'Niumei', 'Niu Ke Le']
# 复制列表中的每个元素
for str in users_list :
print("Hi, {A}! Welcome to Nowcoder!" .format(A = str))
print("Happy Programmers' Day to everyone!")
list = []
for num in range(10, 50 + 1) :
list.append(num)
print(list)
# 首部 尾部
print(list[0], list[-1])
arr = [int(x) for x in input().split()]
sum = sum(arr)
# 多个参数都写到%后的括号中 %()
print("%d %.1f" %(sum, sum/len(arr)))
# 第三个参数是步长
my_list = [x for x in range(0, 19, 2)]
for x in my_list:
print(x)
# 根据for后面的if的布尔值生成
my_list = [x for x in range(1, 50+1) if x % 5 == 0]
for x in my_list:
print(x)
# 生成的时候再加工
my_list = [2x for x in range(1, 10+1) ]
for x in my_list:
print(x)
print([x for x in range(0, 9+1)])
list = ['apple', 'ice cream', 'watermelon', 'chips', 'hotdogs', 'hotpot']
while len(list):
list.pop()
print(list)
users_list = ['Niuniu', 'Niumei', 'HR', 'Niu Ke Le','GURR', 'LOLO']
for name in users_list:
if name == 'HR':
print('Hi, HR! Would you like to hire someone?')
else :
print(f'Hi, {name}! Welcome to Nowcoder!')
list = [3, 45, 9, 8, 12, 89, 103, 42, 54, 79]
num = int(input())
for x in list :
if x == num :
break
else :
print(x)
# 遍历range默认是数字
for x in range(1, 15 + 1):
if x != 13:
print(x, end=' ')
# 二维数组
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
num = int(input())
for i in range(len(matrix)):
for j in range(len(matrix[i])):
matrix[i][j] *= num
print(matrix)
# print([[x*num for x in i] for i in [[1,2,3],[4,5,6],[7,8,9]] ])
str1 = input()
str2 = input()
tup = (str1, str2)
# 元组不能修改
# ('NiuNiu', 'NiuMei')
print(tup)
entry_form = ("Niuniu", "Niumei")
print(entry_form)
# 异常捕获
try:
# 元组不可修改
entry_form[1] = 'Niukele'
except TypeError:
print("The entry form cannot be modified!")
tup = tuple(input().split())
print(tup[:3])
tup = ('Tom', 'Tony', 'Allen', 'Cydin', 'Lucy', 'Anna')
print(tup)
name = input()
if name in tup :
print("Congratulations!")
else :
print("What a pity!")
tup = tuple(range(1,6))
print(tup)
print(len(tup))
# 可以用 += 猜测还是对象覆盖
tup += tuple(x for x in range(6, 10 + 1))
print(tup)
print(len(tup))
字典说白了就是键值对
operators_dict = {
'<': 'less than',
'==': 'equal'
}
print("Here is the original dict:")
# 默认遍历key
for key in sorted(operators_dict) :
print("Operator %s means %s." %(key, operators_dict[key]))
# 动态添加
operators_dict['>'] = 'greater than'
print("\nThe dict was changed to:")
# .items() 遍历key,val
for key, val in sorted(operators_dict.items()):
print("Operator %s means %s." %(key, val))
survey_list = ['Niumei', 'Niu Ke Le', 'GURR', 'LOLO']
result_dict = {
'Niumei': 'Nowcoder',
'GURR': 'HUAWEI'
}
for name in survey_list :
# 根据key来in
if name in result_dict:
print("Hi, %s! Thank you for participating in our graduation survey!" %name)
else :
print("Hi, {}! Could you take part in our graduation survey?" .format(name))
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 it in dict_list:
print("%s's student id is %d." %(it["name"], it["Student ID"]))
# 键值对套键值对
cities_dict = {
'Beijing': {'Capital': 'China'},
'Moscow': {'Capital': 'Russia'},
'Paris': {'Capital': 'France'}
}
for it in sorted(cities_dict) :
print(f"{it} is the capital of {cities_dict[it]['Capital']}!")
result_dict = {
'Allen': ['red', 'blue', 'yellow'],
'Tom': ['green', 'white', 'blue'],
'Andy': ['black', 'pink']
}
# 指定遍历key
for it in sorted(result_dict.keys()):
print(f"{it}'s favorite colors are:")
for color in result_dict[it]:
print(color)
name = input().split()
language = input().split()
# zip() 函数
word = dict(zip(name, language))
print(word)
words = {
'a': ['apple', 'abandon', 'ant'],
'b': ['banana', 'bee', 'become'],
'c': ['cat', 'come'],
'd': ['down']
}
str = input()
for word in words[str]:
print(word, end=" ")
letter = input()
word = input()
words = {
"a": ["apple", "abandon", "ant"],
"b": ["banana", "bee", "become"],
"c": ["cat", "come"],
"d": "down",
# 最后的,可加可不加
letter: word,
}
print(words)
str = input()
word = {}
for ch in str :
# 也可以用in判断
try :
word[ch] += 1
except :
# 初始必须设置值
word[ch] = 1
print(word)
arr = [int(x) for x in input().split()]
print(max(arr))
print(min(arr))
arr = [int(x) for x in input().split()]
print(sum(arr))
# 然而0不算正数
print(abs(int(input())))
# ord 十进制
print(ord(input()))
# hex 十六进制
print(hex(int(input())))
# bin 二进制
print(bin(int(input())))
x, y = map(int, input().split())
print(x y)
print(pow(y, x))
list = input().split()
print(list.count('0'))
list = input().split()
# 不存在返回非法值
print(list.index('NiuNiu'))
str = input()
print(str.isalpha())
print(str.isdigit())
print(str.isspace())
long_str = input()
# 三个参数指定搜索范围,一个参数默认全范围
print(long_str.find('NiuNiu', 0, len(long_str)))
str = input()
print(str.count('Niu', 0, len(str)))
# 默认分割成字符串
print(input().split())
arr = []
endstr = '0'
# 直到endstr位置,每行接收的东西
for line in iter(input, endstr):
arr.append(line)
print(" ".join(arr))
str = input();
# 默认全部替换
print(str.replace("a*", "ab"))
# 指定,最多替换cnt次
# print(str.replace("a*", "ab", cnt))
num = float(input())
# 四舍五入保留至最多两位小数
print(round(num, 2))
str = input()
# 根据表达式计算 这个挺强大的
print(eval(str))
st = set(input().split())
print(sorted(st))
# 可以不指点类型和返回值
# 不return的话默认返回None
def cal(a, b) :
return a - b
x = int(input())
y = int(input())
print(cal(x, y))
print(cal(y, x))
# 指定参数类型和返回值
def fib(n : int) -> int :
if n <= 2 :
return n + 1
else :
return fib(n-1) + fib(n-2)
n = int(input())
print(fib(n))
import math
def calBall(n) :
# 需要导入math包
# pow可以不用math.
return 4 * math.pi * math.pow(n, 2)
arr = [1,2,4,9,10,13]
for num in arr :
print("%.2f" %calBall(num))
name = input()
id = input()
score = int(input())
list = input().split()
print("%s's student number is %s, and his grade is %d. He submitted %d assignments, each with a grade of " %(name, id, score, len(list)) , end="")
for ch in list :
print(ch, end=" ")
class Employee(): # 构造 def __init__(self, name: str, salary: int): self.name = name self.salary = salary # 第一个参数必须是self 当然可以写成别的名称 def setAge(self, age: int): self.age = age def printclass(self): try: print("%s'salary is %d, and his age is %d" % (self.name, self.salary, self.age)) except: print("Error! No age") name = input() salary = int(input()) e = Employee(name, salary) e.printclass() age = int(input()) e.setAge(age) e.printclass()
class Employee(): def __init__(self, name: str, salary: int): self.name = name self.salary = salary def printclass(self): print("%s'salary is %d, and his age is %d" % (self.name, self.salary, self.age)) name = input() salary = int(input()) age = int(input()) e = Employee(name, salary) # hasattr 是否有该成员变量 print(hasattr(e, 'age')) if not hasattr(e, 'age'): # 添加成员变量 setattr(e, 'age', age) e.printclass()
class Coordinate(): x, y = 0, 0 def __init__(self, x: int, y: int): self.x = x self.y = y # to_string 重载 def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")" # 根据需求返回lhs还是rhs还是新值 def __add__(self, rhs): return Coordinate(self.x + rhs.x, self.y + rhs.y) x1, y1= map(int, input().split()) point1 = Coordinate(x1, y1) x2, y2= map(int, input().split()) point2 = Coordinate(x2, y2) point3 = point1 + point2 print(point3)
正则表达之我不熟悉,基本都是cv的
import re
cmp = 'https://www'
str = input()
# 从开头匹配到第一位不匹配的范围
# 元组的形式
print(re.match(cmp, str).span())
import re
str = input()
# r表示纯字符串
# 全部数字信息
# 0-9的数字
print(re.sub(r'[^0-9]', '', str))
# \D 等价于 数字
# \d 等价于 非数字
print(re.sub(r'\D', '', str))
import re
str = input()
# 提取的仅包含数字和-的电话号码
res = re.match(r'[0-9|-]*', str)
print(res.group())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。