How to Make Division by Zero to Zero in Python?

In Python, division by zero generates the exception ZeroDivisionError:  division by zero.  This is because in mathematics, division by zero is undefined. Today we’ll go over some ways to avoid the zero division error in Python and force it to return a zero. First, we’ll look into exception handling in Python. Second, we’ll examine different … Read more

Python Count Characters Except Empty Spaces

In Python, a string includes not only the alphanumeric characters and symbols, but also all whitespaces.  Consider this simple example: We have a variable called mystring, and it is assigned to 3 characters a, b, and c.  Note we have separated each character with a space, so when calling the len() function we get the … Read more

How to Generate a Random String in Python?

Problem Formulation You are tasked with writing Python code to generate a random string.  The string should contain any of the printable characters on your keyboard.  Letters, numbers, and punctuation marks are valid, and we’ll leave out any whitespace characters. What’s the best way to solve this in Python? Method 1: List Comprehension and random.randint() … Read more