Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

python - How can a function only take positive number?

I'm new to python and currently learning about error handling in python. There is an exercise that I want to solve but can't figure out how.

The function receives the value of r and returns the volume of the sphere. In the event that a r equal to or less than zero is passed to the function, the function returns a notification of incorrect data entry.

Protect the function from crashing. In case of exceptions during execution, the function must return an error message.

My code

import math
def vol(r):
    try:
        return (4/3*math.pi*r**3)           
      
    except TypeError:
        return "A type error has occurred."
    

When I test print(vol(-3)) it gives me -113.09733552923254 as result but it should warn me that number is less than 0.

question from:https://stackoverflow.com/questions/65651920/how-can-a-function-only-take-positive-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Of course, it will return a number even if you input the negative value. Because there is no expectation to occur error when you input negative value.

if you want to make it occur the error, use raise with if

here is example

import math
def vol(r):
    try:
        if r <= 0:
            raise TypeError
        return (4/3*math.pi*r**3)           
      
    except TypeError:
        return "A type error has occurred."

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...