1. 根据输入的日期,计算该日期是这一年的第几天
def is_leap_year(year): # 判断这一年是否为闰年
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return True
else:
return False
def function1(year, month, day): # 计算给定日期是这一年的第几天
leap_year = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
no_leap_year = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year):
result = sum(leap_year[:month - 1]) + day
else:
result = sum(no_leap_year[:month - 1]) + day
return result
s = input('请输入日期:') # 输入 2020/5/6
s = s.split("/")
days = function1(int(s[0]), int(s[1]), int(s[2]))
print('该日期是这一年的第{}天'.format(days))
2. 猜数游戏
import random
flag = True
while flag:
n = random.randint(100, 999) # 生成一个三位的随机数n
count = 0 # 记已猜的次数
while True:
m = int(input("请输入一个数:"))
if m > n:
print("你输入的数大了")
count += 1
elif m < n:
print("你输入的数小了")
count += 1
elif m == n:
if count <= 8:
print("太聪明了")
elif count <= 15:
print("还不错")
elif count > 15:
print("终于猜对了,不容易啊!")
print("*" * 25, "\n还想再玩一局吗? \n 1.继续请输入yes \n 2.结束请输入no\n", "*" * 25)
order = input("请输入你的选择: ")
if order == "yes":
break # 退出内层循环 开始下一局
elif order == 'no':
flag = False # 结束整个循环
break
3.输入一组数到列表nums,请找到列表中任意两个元素相加能够等于9的元素,形成一个元组,使其小数在前大数在后,如:(2,7),(1,8)。重复的元组元素只保留一个,结果按元组第一个元素从小到大顺序输出
def get_tuple(num_list):
temp_list = []
for i in num_list:
if (9 - i) in num_list:
min_ = (9 - i) if (i >= (9 - i)) else i
max_ = i if min_ == (9 - i) else (9 - i)
if (min_, max_) not in temp_list:
temp_list.append((min_, max_))
return temp_list
nums = input("numbers:")
# 列表推导式
num_list = [int(i) for i in nums.split(',')]
result_list = get_tuple(num_list)
# 按列表里每个元组的第一个元素从小到大排序
result_list = sorted(result_list, key=lambda i: i[0])
print(result_list)
4. 求输入一组数据的平均值、方差、中位数
nums = input('请输入一组数据:')
data = nums.split(',')
# 算平均值
data = [eval(i) for i in data] # 转成数字类型
average = sum(data) / len(data)
print('这组数据平均值为:{:.2f}'.format(average))
# 方差计算
total = 0
for value in data:
total += (value - average) ** 2
stddev = (total / len(data)) ** 0.5
print('这组数据方差为:{:.2f}'.format(stddev))
# 中位数计算
data.sort() # 从小到大排序
mid = len(data) // 2 # 找中位数的索引
if len(data) % 2 == 0:
median = (data[mid - 1] + data[mid]) / 2
else:
median = data[mid]
print('这组数据中位数为:{:.2f}'.format(median))
for i in range(1, 10):
for j in range(1, i+1):
num = j * i
print("{}*{}={:<2}".format(j, i, num), end=" ")
if i == j:
print(" ")
break
# ax²+bx+c=0
a = float(input('输入 a:'))
b = float(input('输入 b:'))
c = float(input('输入 c:'))
if a == 0:
x = -c / b
print('方程的解为:x={}'.format(x))
else:
delta = b ** 2 - 4 * a * c
if delta < 0:
print('No solution!')
elif delta == 0:
x = -b / (2 * a)
print('方程的解为:x={}'.format(x))
else:
root = delta ** 0.5
x1 = (-b + root) / (2 * a)
x2 = (-b - root) / (2 * a)
print('方程的两个解为 x1={} x2={}'.format(x1, x2))