【问题标题】:Python function does not return reuslt when called upon, no output. What am I doing wrongPython函数在调用时不返回结果,没有输出。我究竟做错了什么
【发布时间】:2020-04-05 15:52:34
【问题描述】:

我是 python 新手,编程知识有限。 我试图使用 def 函数来制作指数计算器。 我给它一个数字和一秒作为指数,即:数字^指数。当我调用我的函数时,它不会返回结果:

def power_to(base, power):
   return base ** power

base = int(input("insert base number here: "))       
power = int(input("insert power number here: "))
power_to(base, power)

这是我的代码的输出:

   insert power number here: 3
   Process finished with exit code 0```

【问题讨论】:

  • 您需要打印power_to 输出。
  • print(power_to(2,3))--->8
  • 如果我在没有“print”的情况下调用我的函数意味着什么?
  • 它有效,但据我了解,如果我在函数中输入return,我就不必使用print,我错了吗?
  • 你正在从你的函数中返回一些东西,你应该在一个变量中捕获它然后打印变量或者直接打印你的函数的输出,如上所述

标签: python function return


【解决方案1】:

您必须打印 power_to 函数的输出

def power_to(base, power):
   return base ** power

base = int(input("insert base number here: "))       
power = int(input("insert power number here: "))
print(power_to(base, power))

【讨论】:

    【解决方案2】:

    在你的文件中你可以添加

    if __name__ == '__main__':
    

    声明并从那里调用你的函数,然后打印结果。

     def power_to(base, power):
        return base ** power
    
    
    if __name__ == '__main__':
        base = int(input("insert base number here: "))
        power = int(input("insert power number here: "))
    
        result = power_to(base, power)
        print(result)
    

    【讨论】:

      猜你喜欢
      • 2017-12-27
      • 2016-07-18
      • 2013-08-06
      • 1970-01-01
      • 2022-06-10
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多