【问题标题】:Output of a Python program doesn't make sensePython 程序的输出没有意义
【发布时间】:2016-01-08 05:26:08
【问题描述】:

我用python编写了一个程序,它最多显示三个数字。虽然程序很简单,但输出提出了一个问题。这是我编写的代码:::

 #Program to find maximum of three numbers using function
def max_of_three(a,b,c):
    if(a>b and a>c):
        print("a is greater")
    elif(b>a and b>c):
        print("b is greater")
    else:
        print("c is greater")
print("Enter three numbers...")
a=int(input())
b=int(input())
c=int(input())
print(max_of_three(a,b,c))

现在当我运行这个程序并在运行时提供输入后得到这个输出时::

Enter three numbers...
58
45
12
a is greater
None

结果很好..但我不明白为什么要打印“无”这个词?我的意思是什么意思?

【问题讨论】:

  • 删除最后一个打印,即max_of_three(a,b,c) 就足够了,因为您在该函数中添加了print func。
  • Python 还允许您在条件下丢失and,即如果 a > b > c:

标签: python function python-3.x


【解决方案1】:

print(max_of_three(a,b,c)) 正在尝试打印 max_of_three 的结果 - 但没有 - 因此是 None

看起来您打算 max_of_three 返回一个字符串,而不是直接打印该值。这是“更好的”,因为它将“状态”的显示与计算分开。

替代方案是只调用max_of_three(不带print),即max_of_three(a,b,c); 这可行,但现在您的计算始终会打印结果(即使您不想打印)

【讨论】:

  • 即Python 函数隐式返回 None。见books.google.com.au/…
  • 谢谢你..这消除了我的疑问..我实际上没有考虑过...函数实际上是打印的,我将函数放在打印语句中..我不应该做到了...谢谢您的回复.. :)
【解决方案2】:

由于您没有在函数max_of_three(a,b,c) 中返回任何值,因此该函数不返回任何值,因此输出为None

假设您的评论#Program to find maximum of three numbers using function,您的意思可能是返回最大值:

def max_of_three(a,b,c):
    if(a>b and a>c):
        print("a is greater")
        return a
    elif(b>a and b>c):
        print("b is greater")
        return b
    else:
        print("c is greater")
        return c

现在,函数应该返回最大值,即 58:

Enter three numbers...
58
45
12
a is greater
58

【讨论】:

  • 非常感谢您的澄清...帮助很大.. :)
猜你喜欢
  • 1970-01-01
  • 2017-05-19
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
相关资源
最近更新 更多