
编写程序1:输入三个整数,按升序输出
# 接收用户输入的三个整数
a = int(input("请输入第一个整数:"))
b = int(input("请输入第二个整数:"))
c = int(input("请输入第三个整数:"))
# 使用sorted函数对整数进行排序
sorted_numbers = sorted([a, b, c])
# 输出排序后的整数
print("按升序排列的整数为:", sorted_numbers)

编写程序2:输入年份及1-12月份,判断月份属于大月、小月、闰月、平月,并输出本月天数
def is_leap_year(year):
# 判断是否为闰年
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
def get_days_in_month(year, month):
# 判断月份类型并返回天数
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31 # 大月
elif month in [4, 6, 9, 11]:
return 30 # 小月
elif month == 2:
if is_leap_year(year):
return 29 # 闰年的2月
else:
return 28 # 平年的2月
else:
return None # 无效的月份
# 接收用户输入的年份和月份
year = int(input("请输入年份:"))
month = int(input("请输入1-12的月份:"))
# 检查月份是否有效
if month < 1 or month > 12:
print("输入的月份无效。")
else:
# 判断月份类型
if month == 2:
if is_leap_year(year):
print(f"{year}年是闰年,{month}月是闰月。")
else:
print(f"{year}年是平年,{month}月是平月。")
elif month in [1, 3, 5, 7, 8, 10, 12]:
print(f"{month}月是大月。")
elif month in [4, 6, 9, 11]:
print(f"{month}月是小月。")
# 输出本月天数
days = get_days_in_month(year, month)
if days is not None:
print(f"{month}月有{days}天。")

编写程序3:输入一个整数,显示其所有素数因子
def prime_factors(n):
# 素数因子列表
factors = []
# 检查最小的素数因子2
while n % 2 == 0:
factors.append(2)
n //= 2
# 从3开始检查奇数因子
for i in range(3, int(n**0.5) + 1, 2):
while n % i == 0:
factors.append(i)
n //= i
# 如果n是一个大于2的素数,则n本身也是一个因子
if n > 2:
factors.append(n)
return factors
# 接收用户输入的整数
num = int(input("请输入一个整数:"))
# 获取素数因子
factors = prime_factors(num)
# 输出所有素数因子
print(f"{num}的素数因子有:{factors}")

647

被折叠的 条评论
为什么被折叠?



