python - 我不明白为什么这个函数总是返回 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新手,所以如果错误看起来很明显,这就是为什么)有人可以告诉我出了什么问题吗?
解决方案
如评论中所述,您不应在函数中定义函数。这些辅助函数确实返回值,尽管您的原始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
推荐阅读
- javascript - javascript,对于函数,var 似乎表现得很奇怪
- powershell - 可重用的 SteppablePipeline 代码随机中断
- c - 警告:“...”的声明在此函数之外不可见 [-Wvisibility]
- haskell - 如何将镜头对准作为多态函数的记录字段?
- powershell - 将窗口置于前台的正确方法
- c# - Xamarin ListView UI 刷新留下空白行
- javascript - 使用 Promises 并行读取数字数组
- c# - CreateSQLQuery(string) 抛出 System.ArgumentException
- php - 如何在浏览器关闭或 url 更改后创建不过期的 cookie 或会话
- python - Django - 通过 id 获取对象并克隆它