首页 > 解决方案 > 我不明白为什么这个函数总是返回 none

问题描述

非常感谢每个回答的男孩。我非常感谢您的建议:) 我做了这个函数,它应该返回摄氏度/华氏度或公斤/磅之间转换的转换值:

def convert (nr1, nr2, ctype):
    if ctype == 1:
        if nr2 == " ":
            def kg_lbs (nr1):
                return nr1 * 2.2046
        if nr1 == " ":
            def lbs_kg (nr2):
                return nr2 / 2.2046
    if ctype == 2:
        if nr2 == " ":
            def cel_far (nr1):
                return nr1 * 1.80000000 + 32
        if nr1 == " ":
            def far_cel (nr2):
                return (nr2 - 32)/1.8000000

你给它第一个数字(摄氏度或公斤)和第二个数字(华氏或磅)(你指出你想用空格转换的方式),在给出数字 1 和数字 2 之后,你给它转换类型(即在 F/C 或 Kg/Lbs 之间转换)。

问题是:无论我提供什么值,它都只返回None.

(我是python新手,所以如果错误看起来很明显,这就是为什么)有人可以告诉我出了什么问题吗?

标签: python

解决方案


如评论中所述,您不应在函数中定义函数。这些辅助函数确实返回值,尽管您的原始convert()函数没有返回值。如果您删除所有第二个函数定义并正确缩进,那么您的函数应该按预期工作。

def convert(nr1, nr2, ctype):
  '''This function converts inputed units to another measurement system
  lbs to kg or Celsius to Fahrenheit depending on a passed through integer
  for conversion type'''
  if ctype == 1:
    if nr2 == " ":
        return nr1 * 2.2046
    if nr1 == " ":
        return nr2 / 2.2046

  if ctype == 2:
    if nr2 == " ":
        return nr1 * 1.80000000 + 32
    if nr1 == " ":
        return (nr2 - 32)/1.8000000

print(convert(1, ' ', 1))

这将按预期返回 2.2046。我不想在你的语法上走得太远,因为你还在学习,但这是一个好的开始。尝试看看如何合并 elif/else 语句而不是背靠背 ifs


推荐阅读