import random
exp1, exp2 = "", ""
str1, str2 = "", ""
j = 0
count = int(input("请输入出题数量:"))
while j < count:
flag = random.choice(["+", "-"])
if flag == "+":
a = random.randint(0, 50)
b = random.randint(0, 50)
result = a + b
# 如果是减法,被减数和减数都应小于100
else:
a = random.randint(1, 100)
b = random.randint(1, 100)
# ab比较,较大的数为被减数
if a < b:
a, b = b, a
result = a - b
a = str(a).ljust(2, " ")
b = str(b).ljust(2, " ")
exp1 = a + " " + flag + " " + b + " ="
exp2 = a + " " + flag + " " + b + " =" + str(result)
if j % 2 == 0: # j为偶数,不换行
str1 = str1 + exp1 + '\t'
str2 = str2 + exp2 + '\t'
else:
str1 = str1 + exp1 + '\n'
str2 = str2 + exp2 + '\n'
j = j + 1
with open('math.txt', 'w') as f:
f.write(str1)
with open('key.txt', 'w') as f:
f.write(str2)
print(count, "道混合加减法题:")
print(str1)
print(count, "道混合加减法题(带答案):")
print(str2)
知识点:
##1. random 函数用法
a) **random.choice( list )**
从序列中随机抽选一个数
b) random.randint([start],[stop])
随机生成在范围内的整数,两个参数分别表示上限和下限
c) random.random()
随机生成(0,1)之间的浮点数
d) random.randrange([start],[stop],[step])
在指定范围内,按指定基数递增的集合中获得一个随机数。
如:random.randrange( 0,11,2)
随机产生范围为10间隔为2的数中(0,2,4,6,8,10)任意一个
e)random.sample(list,k)
从指定序列中随机获取指定长度的,且不重复出现的片段
如:
reds = [i for i in range(1, 34)]
list1 = random.sample(reds, 6)
随机产生1~33中的6个不重复数
## 内建函数-ljust、rjust、center
a) str.ljust(width,[fillchar]
该函数用于将字符串进行左对齐,并使用空格填充至指定长度的新字符串
str1 = "hello world"
print(str1.ljust(12,"*")) # hello world*
b)str.rjust(width,[fillchar])
该函数用于将字符串进行右对齐,并使用空格填充至指定长度的新字符串
str1 = "hello world"
print(str1.rjust(12,"*")) # *hello world
c) str.center(width,[fillchar])
该函数用于将字符串进行居中对齐,并使用空格填充至指定长度的新字符串
str1 = "hello world"
print(str1.rjust(13,"*")) # *hello world*