Question
num1 = int(input("Please enter a dividend: "))
num2 = int(input("Please enter a divisor: "))
print("The result is: ", num1/num2)
how to prevent runtime error
num2 = int(input("Please enter a divisor: "))
print("The result is: ", num1/num2)
how to prevent runtime error
Answers
Answered by
GPT-4o mini
To prevent a runtime error in your division operation, particularly a `ZeroDivisionError` that occurs when the divisor (`num2`) is zero, you can add error handling to your code. Here’s one way to do it using a simple `if` statement to check for zero before performing the division:
```python
num1 = int(input("Please enter a dividend: "))
num2 = int(input("Please enter a divisor: "))
if num2 == 0:
print("Error: Cannot divide by zero.")
else:
print("The result is: ", num1 / num2)
```
In this version, the code checks if `num2` is zero before attempting the division. If it is zero, it prints an error message instead of proceeding to calculate the result.
Alternatively, you can use exception handling with a `try` and `except` block to catch the error:
```python
try:
num1 = int(input("Please enter a dividend: "))
num2 = int(input("Please enter a divisor: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter numerical values.")
else:
print("The result is: ", result)
```
This version will catch both `ZeroDivisionError` and a `ValueError` if the user inputs something that's not an integer.
```python
num1 = int(input("Please enter a dividend: "))
num2 = int(input("Please enter a divisor: "))
if num2 == 0:
print("Error: Cannot divide by zero.")
else:
print("The result is: ", num1 / num2)
```
In this version, the code checks if `num2` is zero before attempting the division. If it is zero, it prints an error message instead of proceeding to calculate the result.
Alternatively, you can use exception handling with a `try` and `except` block to catch the error:
```python
try:
num1 = int(input("Please enter a dividend: "))
num2 = int(input("Please enter a divisor: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter numerical values.")
else:
print("The result is: ", result)
```
This version will catch both `ZeroDivisionError` and a `ValueError` if the user inputs something that's not an integer.
There are no human answers yet. A form for humans to post answers is coming very soon!