用python编写:四则运算
时间: 2023-09-16 21:10:22 浏览: 104
Python简单的四则运算
以下是一个简单的四则运算程序,可以进行加减乘除:
```python
import random
# 生成随机数
def generate_num(min_num, max_num):
return random.randint(min_num, max_num)
# 生成随机运算符
def generate_operator():
operators = ['+', '-', '*', '/']
return random.choice(operators)
# 计算表达式结果
def calculate(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 == 0:
raise ValueError('除数不能为零')
return num1 / num2
# 生成表达式
def generate_expression(min_num, max_num):
num1 = generate_num(min_num, max_num)
num2 = generate_num(min_num, max_num)
operator = generate_operator()
expression = '{} {} {}'.format(num1, operator, num2)
try:
result = calculate(num1, num2, operator)
except ValueError as e:
return generate_expression(min_num, max_num)
return expression, result
# 主函数,可以生成多个表达式
def main(num_expressions=10, min_num=0, max_num=100):
for i in range(num_expressions):
expression, result = generate_expression(min_num, max_num)
print('{} = {}'.format(expression, result))
if __name__ == '__main__':
main()
```
使用示例:
```python
>>> main(num_expressions=5, min_num=1, max_num=10)
6 - 1 = 5
4 * 7 = 28
4 / 2 = 2.0
7 / 2 = 3.5
2 + 10 = 12
```
阅读全文