【问题标题】:Returning function values to determine what will be printed返回函数值以确定将打印的内容
【发布时间】:2018-06-14 23:59:20
【问题描述】:

我将创建一个带有参数“n”的函数。我想要一个函数将“n”返回为 0 或 1。如果为 0,则用户输入将被视为小于或等于 0。如果为 1,则用户输入将被视为大于 0。

这是我目前所拥有的,我不知道如何纠正我的错误。

def main():
    n = int(input("Enter a value: "))
    integer(n) 
def integer(n):
    if n <= 0:
        return n*0
    elif n > 0:
        return n*0 + 1
def integer(n=0):
    print("That value is less than or equal to 0")
def integer(n=1):
    print("That value is greater than 0")
main()

【问题讨论】:

  • 为什么不返回布尔值而不是 1 或 0?
  • 这是否总是输出“那个值大于0”?

标签: python


【解决方案1】:

您的问题是您已经覆盖了整数的定义。以下脚本工作正常。此外,n*0 是不必要的,因为它的计算结果始终为 0。

def main():
    n = int(input("Enter a value: "))
    fb=integer(n)
    if fb == 0:
        print("That value is less than or equal to 0")
    else:
        print("That value is greater than 0")
def integer(n):
    if n <= 0:
        return 0
    elif n > 0:
        return 1

main()

【讨论】:

    【解决方案2】:

    试试下面的代码,它更短:

    def main():
        d = {0:'That value is less than or equal to 0',1:"That value is greater than 0"}
        n = int(input("Enter a value: "))
        fb=integer(n)
        print(d[fb])
    def integer(n):
        return 0 if n <= 0 else 1
    
    main()
    

    我只是简单地创建一个字典

    【讨论】:

    • 如果你真的想的话,整个事情可以用lambda定义的函数浓缩成一行……但它失去了清晰度。
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2020-01-26
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    相关资源
    最近更新 更多