整数四则运算python代码
时间: 2023-07-03 10:10:44 浏览: 65
以下是一个简单的整数四则运算的 Python 代码示例:
```python
# 定义函数,输入两个整数和运算符,返回计算结果
def calculate(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
# 判断除数是否为 0
if num2 == 0:
return "除数不能为 0!"
else:
return num1 / num2
else:
return "运算符错误!"
# 测试
num1 = 10
num2 = 5
operator = '+'
result = calculate(num1, num2, operator)
print(result)
```
你可以根据需要修改输入和输出的方式以及错误处理的策略。
相关问题
整数四则运算Python
整数四则运算是指对整数进行加法、减法、乘法和除法运算。在Python中,可以使用加号(+)进行加法运算,减号(-)进行减法运算,星号(*)进行乘法运算,斜杠(/)进行除法运算。
下面是一个示例代码,演示了整数四则运算的实现:
```python
a = int(input('请输入第一个整数:'))
b = int(input('请输入第二个整数:'))
# 加法运算
addition = a + b
print('两数相加的结果为:', addition)
# 减法运算
subtraction = a - b
print('两数相减的结果为:', subtraction)
# 乘法运算
multiplication = a * b
print('两数相乘的结果为:', multiplication)
# 除法运算
if b != 0:
division = a / b
print('两数相除的结果为:', division)
else:
print('除数不能为0')
```
请注意,以上代码中使用了`input`函数来获取用户输入的两个整数。运行代码时,会提示用户输入两个整数,然后进行四则运算并输出结果。
python模拟整数四则运算
以下是Python模拟整数四则运算的示例代码:
```python
# 定义四则运算函数
def calc(num1, num2, operator):
if operator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
if num2 == 0:
return '除数不能为0'
else:
return num1 / num2
else:
return '不支持的运算符'
# 测试四则运算函数
print(calc(1, 2, '+')) # 输出:3
print(calc(3, 2, '-')) # 输出:1
print(calc(2, 3, '*')) # 输出:6
print(calc(4, 2, '/')) # 输出:2.0
print(calc(4, 0, '/')) # 输出:除数不能为0
print(calc(1, 2, '%')) # 输出:不支持的运算符
```