Python3:If和else运行良好,但当我添加elif时没有输出



我正在尝试运行一个简单的if、elif和else语句。我的代码是:

def main():
x, y = 100, 100

if (x < y):
st = "x is less than y"
elif (x == y):
st = "x is the same as y"
else:
st = "x is greater than y"
print(st)

我从ifelse开始,得到了"x is greater than y"。显然,这是不正确的,所以我添加了一个elif语句来获得"x与y相同"。但是,当我运行上面的代码时,没有输出。它没有出现错误,只是空白。

有人能向我解释为什么会这样,或者我做错了什么吗?

试试这个:

函数main应该在所有之后调用

def main():
x, y = 100, 100

if (x < y):
st = "x is less than y"
elif (x == y):
st = "x is the same as y"
else:
st = "x is greater than y"
print(st)
main()

您需要在定义main之后运行它。

与其他编程语言不同,Python不会
自动运行名为main的函数。

def main():
# your code
main()

elif没有问题。函数需要一个输出,并且必须返回一些内容。另外,你必须在某个地方调用函数,这样它才能工作。所以你可以试试这个:

def main():
x, y = 100, 100
if x < y:
st = "x is less than y"
elif x == y:
st = "x is equal to y"
else:
st = "x is greater than y"
return st

print(main())

代码看起来不错,只是忘记调用函数main((。

最新更新