Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check If String is Integer in Python
Next article icon

Zerodivisionerror Integer by Zero in Python

Last Updated : 06 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python, a versatile and powerful programming language, is widely used for various applications, from web development to data analysis. One common issue that developers often encounter is the ZeroDivisionError, which occurs when attempting to divide a number by zero. In this article, we will explore the causes of this error and provide practical solutions to fix it.

What is Zerodivisionerror In Python?

ZeroDivisionError is raised when a program attempts to perform a division operation where the denominator is zero. This situation is mathematically undefined, and Python, like many programming languages, raises an exception to signal the error.

Syntax :

ZeroDivisionError: division by zero

Why does Zerodivisionerror occur?

There, are some reasons that's why Zerodivisionerror Occurs those are following.

  • Direct Division by Zero
  • Variable Initialization Issue
  • Conditional Statements Issue

Direct Division by Zero

In this example, below code is perform a division operation (`numerator / denominator`), but it will raise a `ZeroDivisionError` since the denominator is set to zero, which is mathematically undefined.

Python3
numerator = 10 denominator = 0 result = numerator / denominator 

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 3, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero

Variable Initialization Issue

If a variable used as the divisor is initialized with a value of zero, subsequent division operations involving that variable will lead to a ZeroDivisionError

Python3
denominator = 0 result = 20 / denominator   

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero

Conditional Statements Issue

In this example , below code incorrectly attempts a division operation without checking if the denominator is zero, leading to a `ZeroDivisionError` due to the unmet condition.

Python3
denominator = 0 if denominator != 0:     result = 25 / denominator   

Output:

Hangup (SIGHUP)
Traceback (most recent call last):
File "Solution.py", line 2, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero

Approach/Reason to Solve Zerodivisionerror

Below, are the ways to solve the Zerodivisionerror error

  • Using if-else Condition
  • Using Try-Except Block
  • Using Conditional Expression

Using if-else Condition

In this code example, a division operation is performed only if the denominator is not zero; otherwise, an error message is printed to prevent a ZeroDivisionError.

Python3
numerator = 10 denominator = 0  if denominator != 0:     result = numerator / denominator else:     print(&quot;Error: Cannot divide by zero.&quot;) 

Output
Error: Cannot divide by zero.    

Using Try-Except Block

In this example below code is perform a division operation (`numerator / denominator`), but if the denominator is zero, it catches the resulting `ZeroDivisionError` and prints an error message stating, "Error: Cannot divide by zero."

Python3
numerator = 10 denominator = 0  try:     result = numerator / denominator except ZeroDivisionError:     print(&quot;Error: Cannot divide by zero.&quot;) 

Output
Error: Cannot divide by zero.    

Using Conditional Expression

In this approach, the division operation is performed only if the denominator is not zero. If the denominator is zero, it returns an error message instead.

Python3
numerator = 10 denominator = 0  result = numerator / denominator if denominator != 0 else &quot;Error: Denominator cannot be zero.&quot; print(result) 

Output
Error: Denominator cannot be zero.    

Conclusion

In conclusion, addressing ZeroDivisionError in Python is essential for maintaining robust and error-free programs. Developers can employ effective strategies such as validating user input, checking variable values, and structuring conditional statements carefully. Implementing try-except blocks offers a graceful way to handle division by zero scenarios, preventing crashes and providing opportunities for custom error messages


Next Article
Check If String is Integer in Python

O

oceanofknow6flv
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
  • Python Errors
Practice Tags :
  • python

Similar Reads

  • ZeroDivisionError: float division by zero in Python
    In this article, we will see what is ZeroDivisionError and also different ways to fix this error. What is ZeroDivisionError?A ZeroDivisionError in Python occurs when we try to divide a number by 0. We can't divide a number by 0 otherwise it will raise an error. Let us understand it with the help of
    2 min read
  • How to convert signed to unsigned integer in Python ?
    Python contains built-in numeric data types as int(integers), float, and complex. Compared to C programming, Python does not have signed and unsigned integers as data types. There is no need to specify the data types for variables in python as the interpreter itself predicts the variable data type b
    2 min read
  • How To Convert Unicode To Integers In Python
    Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five dif
    2 min read
  • Convert Hex String To Integer in Python
    Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this tas
    2 min read
  • Check If String is Integer in Python
    In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding. Example: Input2 : "geeksforgeeks"Output2 : geeksforgeeks is not an IntigerExplanation : "g
    4 min read
  • How to take integer input in Python?
    In this post, We will see how to take integer input in Python. As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function. Let us see the examples: E
    3 min read
  • numpy.trim_zeros() in Python
    numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence. Syntax: numpy.trim_zeros(arr, trim) Parameters: arr : 1-D array or sequence trim : trim is an optional parameter with default value to be 'fb'(front and back) we can either select 'f'(front) and
    2 min read
  • How to convert string to integer in Python?
    In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
    3 min read
  • How to Add leading Zeros to a Number in Python
    In this article, we will learn how to pad or add leading zeroes to the output in Python. Example:Input: 11 Output: 000011 Explanation: Added four zeros before 11(eleven).Display a Number With Leading Zeros in PythonAdd leading Zeros to numbers using format() For more effective handling of sophistica
    3 min read
  • numpy.zeros() in Python
    numpy.zeros() function creates a new array of specified shapes and types, filled with zeros. It is beneficial when you need a placeholder array to initialize variables or store intermediate results. We can create 1D array using numpy.zeros(). Let's understand with the help of an example: [GFGTABS] P
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences