根据提示,在右侧编辑器补充代码,完成如下操作: 1、编写函数,完成任意两个数的除法运算,并输出结果。 2、用非0和0作为除数测试上述代码。 3、修改上述函数,要求除数为零时抛出异常。 4、用非0和0作为除数测试上述代
时间: 2024-03-17 12:46:51 浏览: 175
1. 下面是完成除法运算的函数:
```python
def division(x, y):
result = x / y
print("The result of division is: ", result)
```
2. 使用非零和零作为除数来测试上述代码:
```python
division(10, 2)
division(10, 0)
division(0, 10)
```
输出结果:
```
The result of division is: 5.0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-2-3c7d3c40dec9> in <module>()
1 division(10, 2)
----> 2 division(10, 0)
3 division(0, 10)
<ipython-input-1-8b2d4c22b05c> in division(x, y)
1 def division(x, y):
----> 2 result = x / y
3 print("The result of division is: ", result)
ZeroDivisionError: division by zero
The result of division is: 0.0
```
3. 修改上述函数,实现当除数为零时抛出异常:
```python
def division(x, y):
if y == 0:
raise ZeroDivisionError("除数不能为零!")
else:
result = x / y
print("The result of division is: ", result)
```
4. 使用非零和零作为除数来测试上述代码:
```python
division(10, 2)
division(10, 0)
division(0, 10)
```
输出结果:
```
The result of division is: 5.0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-4-3c7d3c40dec9> in <module>()
----> 1 division(10, 0)
<ipython-input-3-fc3c1c8f8a89> in division(x, y)
1 def division(x, y):
2 if y == 0:
----> 3 raise ZeroDivisionError("除数不能为零!")
4 else:
5 result = x / y
ZeroDivisionError: 除数不能为零!
The result of division is: 0.0
```
注意:当除数为零时,程序抛出了 ZeroDivisionError 异常,并给出了提示信息“除数不能为零!”。
阅读全文