1.四则运算
编写一个Python程序,生成“加减乘除”四则运算的练习,并能判断结果是否正确。程序可以选择进行哪种运算,根据输入的数据判断运算结果是否正确,最后给出正确性统计。
- 代码:
import random
right=0
count=0
print("输入1为加法")
print("输入2为减法")
print("输入3为乘法")
print("输入4为除法(结果为.0)")
n=int(input())
while True:
m = random.randint(1, 100)
p = random.randint(1, 100)
if n == 2:
if m > p:
print('%d-%d=' % (m, p))
question = input('请输入你的答案(q或者Q退出):')
if question == 'q' or question == 'Q':
if (question == 'q' or question == 'Q') and (count == 0):
count += 1
break
elif question == str(m - p):
print('正确')
right += 1
count += 1
else:
print('错误')
count += 1
else:
continue
if n==1:
print('%d+%d=' %(m,p))
question = input('请输入你的答案(q或者Q退出):')
if question == 'q' or question == 'Q':
if (question == 'q' or question == 'Q') and (count == 0):
count += 1
break
elif question==str(m+p):
print('正确')
right += 1
count += 1
else:
print('错误')
count += 1
if n==3:
print('%d*%d=' % (m, p))
question = input('请输入你的答案(q或者Q退出):')
if question == 'q' or question == 'Q':
if (question == 'q' or question == 'Q') and (count == 0):
count += 1
break
elif question == str(m * p):
print('正确')
right += 1
count += 1
else:
print('错误')
count += 1
if n==4:
if p!=0:
if not m % p == 0:
x= random.randint(1, 20)
m = p * x
print('%d/%d=' % (m, p))
question = input('请输入你的答案(q或者Q退出):')
if question == str(m / p):
print('正确')
right += 1
count += 1
elif question == 'q' or question == 'Q':
if (question == 'q' or question == 'Q') and (count == 0):
count += 1
break
else:
print('错误')
count += 1
percent = right/count
print('结束,共%d道题,正确%d,正确率为%f'%(count,right,percent))
- 结果:
3.分析:
import random
m = random.randint(1, 100)
p = random.randint(1, 100)
引入random库,引入两个随机数,先根据输入的数字确定运算,主要是q和count,right的逻辑关系。
主要是除法运算,要使被除数为除数的倍数,方便运算
if not m % p == 0:
x= random.randint(1, 20)
m = p * x
print('%d/%d=' % (m, p))
标签:count,random,randint,python,四则运算,question,---,right,print From: https://blog.csdn.net/2302_81279069/article/details/139898149