I have this code from following this tutorial on YouTube. I cannot wrap my head around why div(10, 2) would give the same output as div(10, 0), in both cases None. Can someone tell me what is wrong with it and what is the way to make it work with a result of 5 when dividing 10/2?
def check(func):
def inside(a, b):
if b == 0:
print ("Can't divide by 0")
return
func(a, b)
return inside
@check
def div(a, b):
return a/b
print(div(10, 2))
>Solution :
In the code you posted, the div function returns the result of a/b without printing it. However, the inside function in the check decorator does not return this result. Instead, it prints a message and returns None if b is 0. This is why calling div(10, 2) and div(10, 0) both print the message and return None.
To make the code work as intended, you can add a return statement to the inside function that returns the result of calling func(a, b). This will return the result of the division instead of None when b is not 0.
Here is an example of how you could modify the code to do this:
def check(func):
def inside(a, b):
if b == 0:
print("Can't divide by 0")
return
return func(a, b) # Return the result of the division
return inside
@check
def div(a, b):
return a/b
print(div(10, 2))
With this change, calling div(10, 2) will return the result of the division, which is 5. Calling div(10, 0) will print the message and return None, as before.