Throw ZeroDivisionError: division by zero in Python 3.x

Dung Do Tien Oct 07 2021 127

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have some lines of code and I want to learn about get input from console and calculate them. My block of code as below:

one = int(input("Number 1: "))
two = int(input("Number 2: "))
three = int(input("Number 3: "))

random = (one + two) / three
print(random)

But I get an exception throw ZeroDivisionError: division by zero when I run code above.

Number 1: 23
Number 2: 34
Number 3: 0
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    random = (one + two) / three
ZeroDivisionError: division by zero

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any suggestions.

Have 2 answer(s) found.
  • V

    Việt Trọng Đỗ Oct 07 2021

    You can use try-except block to handle exception throw. You can see example below:

    try:
        one = int(input("Number 1: "))
        two = int(input("Number 2: "))
        three = int(input("Number 3: "))
        
        random = (one + two) / three
    except ZeroDivisionError:
        random = 0
    
    print(random)

    when you type number 3 is 0, it'll print 0 and no exception throw.

    Note: any number device for 0, you will get exception above.

  • D

    Dan Danny Oct 07 2021

    You can fix by code as below:

    try:
        one = int(input("Number 1: "))
        two = int(input("Number 2: "))
        three = int(input("Number 3: "))
        
        random = (one + two) / three
    except ZeroDivisionError:
        random = 0
    finally:
        print(random)

    Using try-except-finally to handle exception.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close