Python练习题

Python1作业

1. 人生苦短,我学python

image-20220531153242776

name=input()
print("{}同学,人生苦短,我学python".format(name))
print("{}大侠,学好python,走遍天下也不怕".format(name[0]))
print("{}小盆友,学好python,你最帅".format(name[1:]))

2. 汇率兑换

image-20220531153317146

money=input()
if money[0] == 'R':    
    U=eval(money[1:])/6    
    print("$%.2f" % U)
elif money[0] == '$':   
    R=6*eval(money[1:])    
    print("R%.2f" %R)

3. 求圆面积

image-20220531153403720

import math
a = eval(input())
print("%.2f" % (math.pi*(a**2)))

Python2作业

函数题

1.求m到n之和

image-20220531153819918

def sum(m,n):
    s = 0
    if m < n:
        for i in range(m, n+1):
            s = s + i
    return s

2. 递归求斐波那契数列

image-20220531154054702

def f(n):
    if n == 0:
        return 0
    if n == 1 or n == 2:
        return 1
    else:
        return f(n-2) + f(n-1)  //递归

编程题

1. 企业根据利润提成发放奖金问题

image-20220531154252233

a = int(input())
b = [1000000,600000,400000,200000,100000,0]
c = [0.01,0.015,0.03,0.05,0.075,0.1]
r = 0
for i in range(0,6):
    if a>b[i]:
        r+=(a-b[i])*c[i]  //计算超出部分应发奖金
        a=b[i]    //重置计算标准
print(r)

2. 计算某天距元旦的天数

image-20220531160004629

Leap = (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
DisLeap = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)    #闰年月份天数
result = []


def dayNum(num):
    for i in range(num):
        str1 = input()
        date = str1.split(' ')    #将字符串以空格划分
        try:
            year = int(date[0])
            month = int(date[1])
            day = int(date[2])
            if year % 400 == 0 or year % 4 == 0 and year % 100 != 0:    #判断闰年
                if month <= 12 and month > 0 and day > 0 and day <= Leap[month - 1]:
                    res = 0
                    for j in range(month - 1):     # month - 1
                        res += Leap[j]
                    res += day
                    result.append("Totaldays = " + str(res))
                else:
                    result.append("ErrorInput")
            else:
                if month <= 12 and month > 0 and day > 0 and day <= DisLeap[month - 1]:
                    res = 0
                    for j in range(month - 1):
                        res += DisLeap[j]
                    res += day
                    result.append("Totaldays = " + str(res))
                else:
                    result.append("ErrorInput")
        except:
            result.append("ErrorInput")

    for k in result:
        print(k)


n = eval(input())
if n >= 0:
    dayNum(n)

3. 温度转换

image-20220531161534504

image-20220531161605735

c = input()
ctype = c[-1]   #[-1]指向字符串最后一个字符
if ctype == 'F' or ctype == 'f':
    print("%.2fC" % ((float(c[0 : -1]) - 32) / 1.8))    #c[0:-1] 从0到倒数第一个字符,但不包括最后一个
elif ctype == 'C' or ctype == 'c':
    print("%.2fF" % (float(c[0 : -1]) * 1.8 + 32))
else:
    print("Error")

4. 3,5,7的倍数判定

image-20220531162055414

n = int(input())
if n % 3 == 0 or n % 5 == 0 or n % 7 == 0:
    print("Yes")
else:
    print("No")

5. 计算分段函数f(x)的值

image-20220531163017684

n = float(input())
if n == 0:
    print("f(0.0)=0.000")
else:
    print("f({:.2f})={:.3f}".format(n, 1/n))

6.统计字符串中不同种类的字符个数

image-20220531163409314

letter = 0
digits = 0
spaces = 0
other = 0
str0 = input()
for i in str0:
    if i.isalpha():   #判断是不是字符串  .isalpha()方法
        letter+=1
    elif i.isdigit():  #判断是不是数字   .isdigit()方法
        digits+=1
    elif i.isspace():   #判断是不是空格   .isspace()方法
        spaces+=1
    else:
        other+=1
print('letters=%d,digits=%d,spaces=%d,others=%d'%(letter,digits,spaces,other))

Python 实验1

4. 重复多个星号

image-20220531170326949

a = int(input())
s = ""
for n in range(a):
     s += "*"
print(s)

5. 输入半径(大于0),计算圆面积

image-20220531170432014

n = float(input())
while n <= 0:
    n = float(input())
s = 3.14 * n * n
print('半径为{:g}的圆的面积是%0.1f' . format(n) %s)

6. 按格式输出日期

image-20220531170543045

y = int(input())
m = int(input())
d = int(input())
if m < 13 and d < 32 and m > 0 and d > 0:   #判断输入是否合法
    print("{}-{}-{}" .format(y, m, d))
    print("{}/{}/{}" .format(y, m, d))
    print("{}年{}月{}日" .format(y, m, d))

7. 华氏温度到摄氏温度的转换

image-20220531170658209

f = float(input())
c = 5/9*(f-32)
print("%.1f" % c)

8. 比较大小

image-20220531170745728

numlist=sorted(list(map(eval, input().split())))
print("{:c}<{:c}<{:c}".format(numlist[0], numlist[1], numlist[2])) 

9. 统计字符串中子串出现的次数

image-20220531171452081

str1 = input()
str2 = input()
ncount = str1.count(str2)   #count函数是Python的字符串函数。用于统计字符串中某字符出现的次数。
print(ncount)

Python 实验2

1. 判断点在圆内圆

image-20220531171805676

x, y = input().split(',')
x, y=eval(x), eval(y)
r = float(input())
x1, y1 = input().split(',')
x1, y1=eval(x1), eval(y1)

if (x - x1)**2 + (y - y1)**2 > r**2:
    print("( {} , {} )在圆外".format(x1, y1))
else:
    print("( {} , {} )在圆内".format(x1, y1))

2. 身体质量指数

image-20220531172407234

x, y = input().split(',')
x, y = eval(x), eval(y)
BMI = x / (y**2)
if BMI < 18:
    print("超轻")
elif BMI <= 25:
    print("标准")
elif BMI <= 27:
    print("超重")
else:
    print("肥胖")

3. 两个给定正整数的最大公约数和最小公倍数

image-20220531172513552

x = int(input())
y = int(input())


def gcd(x1, y1):    #最大公约数
    m = max(x1, y1)
    n = min(x1, y1)
    while m % n:
        m, n = n, m % n
    return n


def lcm(x2, y2):   #最小公倍数
    m = max(x2, y2)
    n = min(x2, y2)
    while m % n:
        m, n = n, m % n
    return x2 * y2 // n    #二者只是最后一步不同


print("{} {}".format(gcd(x, y), lcm(x, y)))

4. X教授决策成绩评定

image-20220531173408033

a = int(input())
if a < 60:
    print("E")
elif a < 70:
    print("D")
elif a < 80:
    print("C")
elif a < 90:
    print("B")
else:
    print("A")

5. 统计输入字符个数

image-20220531173503740

str = str(input())
eng=num=bla=oth=zh=0
for i in str:
    if (ord(i)>=97 and ord(i)<=122) or (ord(i)>=65 and ord(i)<=90):   #ord() 将字符转为ASCII值,并返回值
        eng=eng+1
    elif ord(i)>=48 and ord(i)<=57:
        num=num+1
    elif ord(i)==32:
        bla=bla+1
    elif 0x4e00 <= ord(i) <= 0x9fa5:
        zh=zh+1
    else:
        oth=oth+1
print('您输入的字符串中有{}个空格,{}个数字,{}个中文,{}个英文字符,{}个其他字符'.format(bla,num,zh,eng,oth))

6. 判断是否为3和5的倍数

image-20220531174759776

a = int(input())
if a % 3 == 0 and a % 5 == 0:
    print("{}是3和5的倍数".format(a))
else:
    print("{}不是3和5的倍数".format(a))

7. 天天向上的力量

image-20220531174902863

dayup = 1.0
dayfactor = float(input())
if dayfactor > 0:
    for i in range(365):
        if i % 7 in [6, 0]:
            dayup = dayup * (1 - dayfactor)
        else:
            dayup = dayup * (1 + dayfactor)
    print("工作日的力量:{:.2f}".format(dayup))
else:
    print("输入的值应该大于0")

8. 百钱百鸡

image-20220531175640635

n = int(input())           #鸡的总数
for a in range(n):			# a公鸡的总数
    for b in range(n):			#b 母鸡的总数
        c = n - a - b				#c 小鸡的总数
        if a*5+b*3+c/3 == n and c%3==0:
            print('cock={},hen={},chicken={}'.format(a, b, c))

9. 三七二十一

image-20220531180641268

n = int(input())
for i in range(n):
    sum = 0
    m1, m2 = map(int, input().split())
    for i in range(m1, m2 + 1):
        if i % 3 == 2 and i % 7 == 1:
            if sum >= 1:
                print(" %d" % i, end='')
            else:
                print(i, end='')
            sum += 1
 
    if sum == 0:
        print("none")
    else:
        print()

10. 亲和数的判断

image-20220531180942414

try:    #注意异常处理   try: except EoFError
    while True:
        a, b = input().split()
        a = int(a)
        b = int(b)
        sum0 = 0
        sum1 = 0
        for i in range(1, a):
            if a % i == 0:
                sum0 = sum0+i
        for y in range(1, b):
            if b % y == 0:
                sum1 = sum1+y
        if sum0 == b and sum1 == a:
            print("YES")
        else:
            print("NO")
except EOFError:
    pass

注意异常问题

Python 实验3

1. 求整数的位数以及各位数字之和

image-20220601110805554

n=input()
num=list(n)
print(len(num),sum(int(i) for i in num))

2. 任意多行字符串拆分数值求和

image-20220601112202592

try:
    while True:
        str1 = input()
        str2 = ''
        for i in str1:
            if i.isdigit():
                str2 += i     #将所有数字串进行提取
            else:
                str2 += ' '   #用空格代替字符,并对数字串进行划分
        list1 = list(map(int, str2.split()))   # 将数字字符串进行划分 调整为list列表
        print("%s:%s"%(str1,sum(list1)))
except EOFError:
    pass

3. 数据提取

image-20220601112502328

studs= [{'sid':'103','Chinese': 90,'Math':95,'English':92},{'sid':'101','Chinese': 80,'Math':85,'English':82},{'sid':'102','Chinese': 70,'Math':75,'English':72}]

scores = {}
for stud in studs:
    sv = stud.items() 
    v = []
    for it in sv:
        if it[0] =='sid':
            k = it[1]
        else:
            v.append(it[1])
    scores[k]  = v

so = list(scores.items())
so.sort(key = lambda x:x[0],reverse = False)
for l in so:
    print('{}:{}'.format(l[0],l[1]))

4. 汉字表示的大写数字金额

image-20220601114206512

s=str(input())
s=list(s)
length=len(s)
zd={0:"零",1:"壹",2:'贰',3:'叁',4:'肆',5:'伍',6:'陆',7:'柒',8:'捌',9:'玖'}
for i in range(len(s)):
   print(zd[ord(s[i])-48],end="")
   if len(s)-i==9:
    print("亿",end="")
    continue
   if len(s)-i==5:
    print("万",end="")
    continue
   if  (len(s)-i)==7 or (len(s)-i)==3 or (len(s)-i)==11:
    print("佰",end="")
   elif  (len(s)-i)==8 or (len(s)-i)==4 or (len(s)-i)==12:
    print("仟",end="")
   elif  (len(s)-i)==6 or (len(s)-i)==2 or (len(s)-i)==10:
    print("拾",end="")
print("圆")

5. 字母替换

image-20220601114327816

s=input()
for i in s:
    if i.isupper():   #.isupper()如果是大写字母,返回True
        tmp1=ord(i)-65
        tmp2=90-tmp1
        i=chr(tmp2)
    print(i,end="")

6. 查验身份证

image-20220601115621907

image-20220601115636666

def is_digits(ss):
    for s in ss:
        if not s.isdigit():
            return False
    return True


weights = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]  
M_codes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']  
wrong_ids = []  
n = int(input())
for i in range(n):
    id = input()
    if len(id) != 18:  
        wrong_ids.append(id)
        continue

    if not is_digits(id[:17]):  
        wrong_ids.append(id)
        continue
	#计算验证码
    total = 0
    for j in range(17):
        total += int(id[j]) * weights[j]

    z = total % 11
    if M_codes[z] != id[17]:  
        wrong_ids.append(id)

if len(wrong_ids) == 0:
    print("All passed")
else:
    for id in wrong_ids:
        print(id)

7. 字典合并

image-20220601153552040

dict1 = dict(eval(input()))
dict2 = dict(eval(input()))
list1 = []
for i in dict1:
    if i in dict2:
        dict2[i] += dict1[i]
    else:
        dict2[i] = dict1[i]
for i in dict2:
    list1.append(i)
list2 = list(set(list1))
list3 = []
list4 = []
for i in list2:
    if isinstance(i, str):
        list3.append(i)
        list4.append(ord(i))
    else:
        list4.append(i)
dict3 = {}
for i in dict2:
    if isinstance(i, str):
        dict3[ord(i)] = dict2[i]
    else:
        dict3[i] = dict2[i]
for i in sorted(list4):
    if chr(i) not in list3:
        print("%s:%s" % (i, dict3[i]))
    else:
        print("'%s':%s" % (chr(i), dict3[i]))

8. 单词统计

image-20220601153706741

n = input().split()
print(len(n))

9.集合A-B

image-20220601153800589

t = eval(input())
for i in range(t):
    a, b = [], []
    s = list(map(int, input().split(" ")))
    n, m = s[0], s[1]
    a = s[2:2 + n]
    b = s[2 + n:]
    # c = [item for item in a if item not in b]
    c = set(a)-set(b)
    c = sorted(c)
    try:
        for y in range(len(c) - 1):
            print(c[y], end=" ")
        print(c[-1])
    except:
        print("NULL")

10.奇特的四位数

image-20220601153907317

def digitSum(v):                    
    lis = list(str(v))
    lis = list(map(int, lis))
    return sum(lis)
 
 
def digitsame(v):                  
    lis = list(str(v))
    lis = list(map(int, lis))
    lis1 = list(set(lis))
    if len(lis1) == 4:
        return True
    return False
 
 
lis = []
for i in range(1000, 10000):
    if digitSum(i) == 6 and i % 11 == 0 and digitsame(i):
        lis.append(i)
print(6)
print(lis)

Python 实验四

1. 列表推导生成随机数矩阵

image-20220601154340330

def generateMatrix(m,n):
    return [[random.randint(0,20) for x in range(n)] for y in range(m)]

2.整数数位和

image-20220601154652291

def digitSum(v):
    sum=0
    while v:
        sum+=v%10
        v//=10
    return int (sum)

4. 编写生成斐波那契数列的函数并调用。

image-20220601154936145

def fib(n):
    n=eval(n)
    if n < 0:
        print("输入数据错误!")
    else:
        if n>0 and n<3:
            print("1 1")
        else:
            num1, num2, string, i = 1, 1, "1 1 ", 0
            while True:
                i = i + 1
                if i % 2 == 0:
                    num2 += num1
                    if num2 > n:
                        break
                    string += str(num2) + " "
                else:
                    num1 += num2
                    if num1 > n:
                        break
                    string += str(num1) + " "
            print(string)

5.判断素数的函数

image-20220601155043001

def prime(n):
    if n <= 1:
        return "1"
    num = int(n ** 0.5)
    for i in range(2,num + 1):
       if n % i == 0:
            return False
    return True

6.定义并实现身体质量指数类

image-20220601155224766

image-20220601155247128

class BMI:
    def __init__(self,sName,iAge,fHeight,fWeight):
        self.name=sName
        self.age=iAge
        self.height=fHeight
        self.weight=fWeight
    def getStatus(self):
        m=fWeight/(fHeight**2)
        if m<18:
            return ("超轻")
        elif m>=18 and m<25:
            return ("标准")
        elif m>=25 and m<27:
            return ("超重")
        else:
            return ("肥胖")
    def getBMI(self):
        n=fWeight/(fHeight**2)
        return n

9.类的定义

class Pet:
    def __init__(self,Name,Age):
        self.Name=Name
        self.Age=Age
    def getName(self):
            return (self.Name)
    def getAge(self):
            return (self.Age)
    def setName(self,Name):
        self.Name=Name
        return (self.Age)
    def setAge(self,Age):
        self.Age=Age
        return (self.Age)
    def __str__(self):
        return self.Name + ' is ' + str(self.Age) + ' age!'
class Fan:
    
	def __init__(self,speed=1,radius=5,color='white',on=False):
		self.__speed=speed
		self.__radius=radius
		self.__color=color
		self.__on=on
    
	def getSpeed(self):
		if self.__speed==1:
			return 'SLOW'
		elif self.__speed==2:
			return 'MEDIUM'
		else:
			return 'FAST'
	def geton(self):
		if self.__on:
			return 'on'
		else:
			return 'off'
	def getradius(self):
		return self.__radius
	def getcolor(self):
		return self.__color
	def setSpeed(self,speed):
		self.__speed=speed
	def setOn(self,on):
		self.__on=on
	def setRadius(self,radius):
		self.__radius=radius

	def setColor(self,color):
		self.__color=color
    
	def __str__(self):
		return 'speed ' + str(self.__speed) +'\n' +'color '+self.__color + '\n'+'radius '+str(self.__radius)+'\n'+'fan is '+str(self.geton())

版权声明:本文为qq_48157192原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。