1.编写程序输入三个整数,按升序输出
思路1:使用if-else结构进行大小比较,将三个数进行从小到大的排序
num1 = int(input("请输入第一个整数:"))
num2 = int(input("请输入第二个整数:"))
num3 = int(input("请输入第三个整数:"))
if num1 <= num2 and num1 <= num3:
a = num1
if num2 <= num3:
b = num2
c = num3
else:
b = num3
c = num2
elif num2 <= num1 and num2 <= num3:
a = num2
if num1 <= num3:
b = num1
c = num3
else:
b = num3
c = num1
else:
a = num3
if num1 <= num2:
b = num1
c = num2
else:
b = num2
c = num1
print("按升序排列的整数是:", a, b, c)
思路二:使用 sort()
方法对列表进行排序
num1 = int(input("请输入第一个整数: "))
num2 = int(input("请输入第二个整数: "))
num3 = int(input("请输入第三个整数: "))
numbers = [num1, num2, num3]
numbers.sort()
print("按升序排列的整数是:", numbers)
2.输入年份及 1-12月份,判断月份属于大月、小月、闰月、平月,并输出本月天数
思路:初学python只接触到单分支,多分支循环结构,此类问题可以使用if-elif循环结构判断年份是闰年还是平年,在后面的学习中接触函数定义后,可以使用函数定义直接判断
两端代码如下
year = int(input("请输入年份: "))
month = int(input("请输入月份 (1-12): "))
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
month_type = "大月"
elif month in [4, 6, 9, 11]:
days = 30
month_type = "小月"
elif month == 2:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
days = 29
month_type = "闰年2月"
else:
days = 28
month_type = "平年2月"
else:
print("月份无效,请输入1到12之间的数字。")
exit()
print(f"{year}年{month}月是{month_type},有{days}天。")
def is_leap_year(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
def main():
year = int(input("请输入年份: "))
month = int(input("请输入月份 (1-12): "))
if month < 1 or month > 12:
print("月份无效,请输入1到12之间的数字。")
return
if month in [1, 3, 5, 7, 8, 10, 12]:
days = 31
month_type = "大月"
elif month in [4, 6, 9, 11]:
days = 30
month_type = "小月"
elif month == 2:
if is_leap_year(year):
days = 29
month_type = "闰年2月"
else:
days = 28
month_type = "平年2月"
else:
print("未知错误")
return
print(f"{year}年{month}月是{month_type},有{days}天。")
main()
3.输入一个整数,显示其所有素数因子
num = int(input("请输入一个整数: "))
prime_factors = []
num = abs(num)
if num % 2 == 0:
prime_factors.append(2)
while num % 2 == 0:
num //= 2
factor = 3
while factor * factor <= num:
if num % factor == 0:
prime_factors.append(factor)
while num % factor == 0:
num //= factor
factor += 2
if num > 2:
prime_factors.append(num)
print("素数因子有:", prime_factors)