Python 如何在try-and-except条件中使用if-else语句来查找非数字是正数、负数还是零?
我得到的答案是“没有”。我如何才能让它工作?不要使用Python 如何在try-and-except条件中使用if-else语句来查找非数字是正数、负数还是零?,python,if-statement,except,Python,If Statement,Except,我得到的答案是“没有”。我如何才能让它工作?不要使用try和,除了,它们是用于错误处理的。相反,请尝试: def algop(num): try: if num == 0: return "The number is neither positive nor negative" except: sally = num + 1 if num - sally == -1:
try
和,除了,它们是用于错误处理的。相反,请尝试:
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))
此外,您不需要执行该代码来检查正或负,只需执行
,也可以执行f字符串:
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))
两个代码都输出:
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))
仅当脚本因错误而停止时,才应使用Try:except:
)
只需删除即可尝试除之外的/?另外,为什么不使用<0
和>0
?sally
变量似乎没有任何意义。您正在有效地测试-1==-1
。堆栈溢出不是为了替换现有的教程和文档。请在上重复您的材料,尝试除此之外的内容,以便您了解它们的功能和使用时间。
10 is positive
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))