微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 try 和 except 条件中使用 if else 语句来查找非数字是正数、负数还是零?

如何解决如何在 try 和 except 条件中使用 if else 语句来查找非数字是正数、负数还是零?

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))

我得到的答案是“没有”。我怎样才能让它工作?

解决方法

不要使用 tryexcept,它们用于错误处理。而是尝试:

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))

此外,您无需执行该代码来检查正面或负面,只需执行 <>,您也可以执行 f 字符串:

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))

两个代码输出:

10 is positive
,

如果您的脚本由于错误而停止,您应该只使用 Try: except: ;)

def algop(num):
  if num == 0:
    return "The number is neither positive nor negative"
  elif num > 0:
    return str(num) + "is positive"
  else:
    return str(num) + "Is negative"

print(algop(10))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。