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
364 views
in Technique[技术] by (71.8m points)

python - How to use if else statements inside a try and except condition to find whether a not a number is positive, negative, or zero?

def algop(num):
    try:
        if num == 0:
            return "The number is neither positive nor negative"
    except:   
        sally = num + 1
        if num - sally == -1:
           return int(num), str("is positive")
        else:
           return int(num), str("Is negative")

print(algop(10))

The answer I get is "none". How can I get this to work?

question from:https://stackoverflow.com/questions/65837900/how-to-use-if-else-statements-inside-a-try-and-except-condition-to-find-whether

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

1 Answer

0 votes
by (71.8m points)

Don't use try and except, they are for error handling. Instead try:

def algop(num):
    if num == 0:
        return "The number is neither positive nor negative"
    sally = num + 1
    if num - sally == -1:
        return int(num), str("is positive")
    else:
        return int(num), str("Is negative")

print(algop(10))

Also you don't need to do that code for checking positive or negative, just do < and >, also you could just do f-strings:

def algop(num):
    if num == 0:
        return "The number is neither positive nor negative"
    if num > 0:
        return f'{num} is positive'
    else:
        return f'{num} is negative'

print(algop(10))

Both codes output:

10 is positive

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

...