Python编程练习22-30

22.随机数生成两个整数 ab,然后通过循环计算这两个整数的最大公约数和最小公倍数,并分别输出结果。

import random
a=random.randint(0,100)
b=random.randint(0,100)
i=a
j=b
print('a=',a)
print('b=',b)
while(a):
   if a<b:
      t=a
      a=b
      b=t
   a%=b
print("这两个整数的最大公约数为:",b)
c=i
while (not(c%i==0 and c%j==0)):
   c+=1

print("这两个整数的最小公倍数为:",c)

23.执行函数后,九九乘法表将会按照规范的格式生成,并保存到名为 "9981.txt" 的文件中。

def generate_multiplication_table():
   with open("9981.txt","w") as file:
      for i in range(1,10):
         for j in range(1,i+1):
            equation = f"{j} x {i} = {i * j}"
            file.write(equation.ljust(10))
         file.write("\n")

generate_multiplication_table()

24.判断输入的数n是否为素数,并打印相应的结果。

def IsPrime(n):
    a = int(n/2+1)
    j=0
    for i in range(2,a):
        if n%i==0:
            j+=1
    if j>0:
        print('%d不是素数'%n)
    else:
        print('%d是素数'%n)
n = int(input('请输入一个正整数:'))
IsPrime(n)

25.输入一个月份,判断该月份所属的季度,并输出结果。

i=1
while i:
    m=float(input('请输入一个月份:'))
    if m>12 or m<=0 or m%1!=0:
        i=1
        print('输入的数据为非法数据,请重新输入!')
    else:
        i=0
if m>0 and m<=3:
    print('%d月所属第一季度'%m)
elif m>=4 and m<=6:
    print('%d月所属第二季度' % m)
elif m>=7 and m<=9:
    print('%d月所属第三季度' % m)
elif m>=10 and m<=12:
    print('%d月所属第四季度' % m)

26.输入的18位身份证号码中提取出生日期,并将其打印输出。

m = input('请输入一个18位的身份证号:')
if len(m)<18:
    print("输入错误!")
else:
    a=int(m[6:10])
    b=int(m[10:12])
    c=int(m[12:14])
    print("出生日期是%d年%d月%d日"%(a,b,c))

27.输入手机号判断是否为中国移动手机号。

import re

pattern = r'(13[4-9]\d{8})|(15[01289]\d{8})$'
mobile = input('请输入手机号码:')
match = re.match(pattern, mobile)
if match is None:
    print(mobile, '不是有效的中国移动手机号码。')
else:
    print(mobile, '是有效的中国移动手机号码。')

28.进制转换器。

print("=======程序员计算器========")
number = int(input('请输入一个十进制的整数:'))
b = bin(number)
o = oct(number)
h = hex(number)
print('十进制数',number,'的二进制数为',b)
print('十进制数',number,'的八进制数为',o)
print('十进制数',number,'的十六进制数为',h)

29.输入身高体重,打印输出BMI。

height = float(input("请输入你的身高(单位为米):"))
weight = float(input("请输入你的体重(单位为千克):"))
bmi = weight/(height*height)
print("您的BMI指数为:"+ str(bmi))

if bmi<18.5:
    print("您的体重过轻")
if bmi>=18.5 and bmi<24.9:
    print("正常范围,注意保持")
if bmi>=24.9 and bmi<29.9:
    print("您的体重过重")
if bmi>=29.9:
    print("肥胖")

30.将一首古诗写入文件,并将该文件内容复制到另一个文件中。

def write_opem(filename):
    try:
        with open(filename,'w',encoding='utf-8') as file:
            poem = '''登鹳雀楼
白日依山尽,黄河入海流。
欲穷千里目,更上一层楼。'''
            file.write(poem)
            print("古诗写入成功")
    except IOError:
        print("写入文时出错")
def copy_file(source,destination):
    try:
        with open(source,'r',encoding='utf-8') as source_file:
            content = source_file.read()
            with open(destination,'w',encoding='utf-8') as dest_file:
                dest_file.write(content)
                print("复制完毕")
    except IOError:
        print("文件操作出错")

write_opem("gushi.txt")
copy_file("gushi.txt","copy.txt")

猜你喜欢

转载自blog.csdn.net/m0_74972727/article/details/131495433
今日推荐