PYTHON: 2 books in 1 : Learn python programming for beginners and machine learning by Sanders Willard D

PYTHON: 2 books in 1 : Learn python programming for beginners and machine learning by Sanders Willard D

Author:Sanders, Willard D. [Sanders, Willard D.]
Language: eng
Format: epub
Published: 2020-10-27T16:00:00+00:00


The picture above is going to be a good example of what is going to show up when we try to divide by zero. We can change up the message to make it work with what we should see within the code.

When you take a look at this example, your compiler is going to bring up an error, simply because you or the user is trying to divide by zero. This is not allowed with the Python code so it will raise that error. Now, if you leave it this way and you run the program exactly how it is, you are going to get a messy error message showing up, something that your user probably won't be able to understand. It makes the code hard to understand, and no one will know what to do next. A better idea is to look at some of the different options that you can add to your code to help prevent some of the mess from before. You want to make sure that the user understands why this exception is being raised, rather than leaving them confused in the process. A different way that you can write out this code to make sure that everyone is on the same page includes:

x = 10

y = 0

result = 0

try:

result = x/y

print(result)

except ZeroDivisionError:

print(“You are trying to divide by zero.”)

As you can see, the code that we just put into the compiler is going to be pretty similar to the one that we wrote above. But we did go through and change up the message to show something unless the user raises this exception. When they do get this exception, they will see the message "You are trying to divide by zero" come up on the screen. This isn't a necessary step, but it definitely makes your code easier to use!



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.