Python语法(序列、循环、正则、函数、文件操作)
第一章 基础知识
编程,用户输入一个三位以上的整数,输出其百位以上的数字,例如输入1234,输出12
x=input('Please input an integer of more than 3 digits:')
try:
x=int(x)
x=x//100
if x==0:
print('you must input an integer of more than 3 digits')
else:
print(x)
except BaseException:
print('you must input an integer.')
第二章 Python序列
编程,生成包含1000个0到100之间的随机整数,并统计每个元素的出现次数
import random
x=[random.randint(0,100) for i in range(1000)]
d=set(x)
for v in d:
print(v,';',x.count(v))
编写程序,用户输入一个列表和2个整数作为下标,然后输出列表中介于2个下标之间的元素组成的子列表,例如输入【1,2,3,4,5,6】和2,5,程序输出【3,4,5,6】
x=input('Please input a list:')
x=eval(x)
start,end=eval(input('Please input the start position and the end position:'))
print(x[start:end])
设计一个字典,用户输入内容作为键,输出字典中对应的键值,如果用户输入的键不存在,则输出“您输入的键不存在!”
d={1:'a',2:'b',3:'c',4:'d'}
v=input('Please input a key:')
v=eval(v)
print(d.get(v,'您输入的键不存在')
编写程序,生成包含20个随机数的列表,然后将前10个元素升序排列,后10个元素降序排列并输出结果
import random
x=[random.randint(0,100) for i in range(20)]
print(x)
y=x[0:10]
y.sort()
x[0:10]=y
y=x[10:20]
y.sort(reverse=True)
x[10:20]=y
print(x)
第三章 选择与循环
编写程序,用户输入4位整数作为年份,判断其是否为闰年,如果年份能够被400整除,则为闰年,若年份能被4整除但不能被100整除也为闰年
x=input('please input an integer of 4 digits meaning the year:')
x=eval(x)
if x%100 ==0 or (x%4==0 and not x%100 ==0):
print('Yes')
else:
print('No')
编写一个程序,生成一个包含50个随机整数的列表,然后删除其中所有的奇数
Import random
x=[random.randint(0,100) for i in range(50)]
print(x)
i=len(x)-1
while i>=0:
if x[i]%2 ==1:
del x[i]
i-=1
print(x)
编写程序,生成一个包含随机整数的列表,对偶数下标的元素进行降序排列,奇数下标的元素不变(使用切片)
import random
x=[random.randint(0,100) for i in range(20)]
print(x)
y=x[::2]
y.sort(reverse=True)
x[::2]=y
print(x)
编写程序,用户从键盘输入小于1000的整数,对它进行因式分解,例如10=2 X 5
x=input ('please input an integer less than 1000:")
x=eval(x)
t=x
i=2
result=[]
while True:
if t==1:
break
if t%i==0:
result.append(i)
t=t/i
else:
i+=1
print(x,'=','*'.join(map(str,result)))
用两种不同的方法计算100以内所有奇数的和
x=[i for i in range(1,100) if i%2 ==1]
print(sum(x))
print(sum(range(1,100)[::2]))
输出由1234四个数字组成的素数,并且每个素数中每个数字只使用一次
def num_list():
list=[1,2,3,4]
list1=[]
for i in list:
for j in list:
if i==j:
continue
for k in list:
if(i==k) or (j==k):
continue
for n in list:
if(i==n) or(j==n)or(k==n):
continue
num=1000*i+100*j+10*k+n
list1.append(num)
return list1
def sushu(num):
for i in range(2,num):
if num % i ==0:
return 'false'
else:
continue
return 'true'
if __name__=='__main__':
list1=num_list()
for i in range(len(list1)):
num=int (list1[i])
if (sushu(num)=='true'):
print(num)
分段函数
x=input('please input x:')
x=eval(x)
if x<0 or x>=20:
print(0)
elif 0<=x<5:
print(x)
elif 5<=x<10:
print(3*x-5)
elif 10<=x<20:
print(0.5*x-2)
第四章 字符串与正则表达式
将大写字母I误写为i,编程纠正
x='i am a teacher,i am a man,and i am 38 years old,I am not a businessman'
x=replace('i','I')
x=replace('i','I')
print(x)
或者使用正则表达式:
x='i am a teacher,i am a man,and i am 38 years'
import re
pattern =re.compile(r'(?:[^\w|\b)i(?:[^\w])')
//小写误写为大写时:
pattern =re.compile(r'(?:[\w])I(?:[\w])')
while True:
result =pattern.search(x)
if result:
if result.start(0)!=0:
x=x[:result.start(0)+1]+'I'+x[result.end(0)-1:]
//大I变小i
else:
x=x[:result.start(0)]+'I'+x[result.end(0)-1]
else:
break
print(x)
检查重复的单词并且只保留一个
import re
x='This is a desk'
pattern =re.compile(r'\b(\w+)(\s+\1){1,}\b')
matchResult=pattern.search(x)
x=pattern.sub(matchResult.group(1),x)
print(x)
输入一段英文,输出其中所有长度为3个字母的单词
import re
x=input('Please input a string')
pattern =re.compile(r'\b[a-zA-Z]{3}\b')
print(pattern.findall(x))
第五章 函数设计与使用
判断一个整数是否为素数,并编写主程序调用该函数
import math
def IsPrime(v):
n=int(math.sqrt(v)+1)
for i in range(2,n)
if v%i ==0:
return 'No'
else:
return 'Yes'
print(IsPrime(37))
print(IsPrime(60))
print(IsPrime(114))
编写一个函数,接收一个字符串,分别统计大写字母,小写字母,数字,其他字符的个数,并以元组的形式返回结果
def demo(v):
capital=little=digt=other=0
for i in v:
if 'A'<=i<='Z':
capital+=1
elif 'a'<=i<='z':
little+=1
elif '0'<=i<='9':
dight+=1
else:
other+=1
return (capital,little,digit,other)
x=capital=little=digt=other=0
print(demo(x))
编写函数接收任意多个整数并输出其中的最大值和所有整数之和
def demo(*v):
print(v)
print(max(v))
print(sum(v))
demo(1,2,3)
demo(1,2,3,4)
demo(1,2,3,4,5)
编写函数,模拟内置函数sum()
def Sum(v):
s=0
for i in v:
s+=i
return s
x=[1,2,3,4,5]
print(Sum(x))
x=(1,2,3,4,5)
print(Sum(x))
编写函数模拟内置函数sorted()
def Sorted(v):
t=v[::]
r=[]
while t:
tt=min(t)
r.append(tt)
t.remove(tt)
return r
x=[1,2,4,6,2,4]
print(x)
print(Sorted(x))
第六章 面向对象程序设计
继承Person类生成Student类,填写新的函数来设置学生专业,然后生出该类对象并显示信息
import types
class Person(object):
def__init__(self,name='',age=20,sex='man'):
self.setName(name)
self.setAge(age)
self.setSex(sex)
def setName(self,name):
if not isinstance(name,str)
print('name must be string:')
return self__name=name
def setAge(self,age):
if not isinstance(age,int):
print('age must be integer:')
return self_age=age
def setSex(self,sex):
if sex!='man' and sex!='woman':
print('sex must be "man" or "woman"')
retun self_sex=sex
def show(self):
print(self_name)
print(self_age)
print(self_sex)
class Student(Person):
def __init__(self,name='AMY',age=20,sex='
man',major='computer')
super(Student,self)_init_(name,age,sex)
self.setMajor(major)
def setMajor(self,major):
if not isinstance(major, str):
print('major must be a string.')
return self.__major = major
def show(self):
super(Student, self).show()
print(self.__major)
if __name__ =='__main__':
zhangsan = Person('Zhang San', 19, 'man')
zhangsan.show()
lisi = Student('Li Si',32, 'man', 'Math')
lisi.show()
class Vecter3:
def __init__(self, x=0, y=0, z=0):
self.X = x
self.Y = y
self.Z = z
def __add__(self, n):
r = Vecter3()
r.X = self.X + n.X
r.Y = self.Y + n.Y
r.Z = self.Z + n.Z
return r
def __sub__(self, n):
r = Vecter3()
r.X = self.X - n.X
r.Y = self.Y - n.Y
r.Z = self.Z - n.Z
return r
def __mul__(self, n):
r = Vecter3()
r.X = self.X * n
r.Y = self.Y * n
r.Z = self.Z * n
return r
def __truediv__(self, n):
r = Vecter3()
r.X = self.X / n
r.Y = self.Y / n
r.Z = self.Z / n
return r
def __floordiv__(self, n):
r = Vecter3()
r.X = self.X // n
r.Y = self.Y // n
r.Z = self.Z // n
return r
def show(self):
print((self.X,self.Y,self.Z))
v1 = Vecter3(1,2,3)
v2 = Vecter3(4,5,6)
v3 = v1+v2
v3.show()
v4 = v1-v2
v4.show()
v5 = v1*3
v5.show()
v6 = v1/2
v6.show()
第七章 文件操作
有一个英文文本文件,编写程序读取其内容,将其中的大写字母变为小写字母,小写字母变为大写字母
f=open(r'd:\1.txt','r')
s=f.readlines()
f.close()
r=[i.swapcase() for i in s]
f=open(r'd:\2.txt','w')
f.writelines(r)
f.close()
编程,将包含学生成绩的字典保存为二进制文件,读取内容并显示
import pickle
d='张三‘:98,'李四’:90,‘王五’:100}
print(d)
f=open('score.dat','wb')
pickle.dump(1,f)
pickle.dump(d,f)
f.close
f=open('score.dat','rb')
pickle.load(f)
d=pickle.load(f)
f.close()
print(d)
编程,用户输入一个目录和一个文件名,搜索该目录及其子目录中是否存在该文件
import sys
import os
directory =sys.argv[1]
filename=sys.argv[2]
paths=os.walk(directory)
for root,dirs,files in paths:
if filename in files:
print('Yes')
break
else:
print('No')
本文地址:https://blog.csdn.net/weixin_45011930/article/details/107111737
上一篇: 葡萄和提子的区别有哪些,这四点你要明白
下一篇: 整合前装与后装,华为给出全屋智能新路径