Python 函数 Noneype
Python function Noneype
华氏大于90度"hot"为return,小于30度为return"cold",但程序为[=21] =] 'None' 作为 return 值。我知道在 python 函数中默认 none 作为 return 值,但是我将华氏温度作为我的 return 值。有人可以解释为什么会这样吗?我是 python 的新手,正在尝试章节练习以更好地理解 python 语言。
# convert2.py
# A program to convert Celsius temps to Fahrenheit
# This version issues heat and cold warning
def temp(fahrenheit):
if fahrenheit > 90:
fahrenheit = "hot"
return fahrenheit
if fahrenheit < 30:
fahrenheit = "cold"
return fahrenheit
def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print()
print("The temperature is", temp(fahrenheit), "degrees Fahrenheit")
main()
如果温度既不高于 90 也不低于 30,则您的函数 returns 什么都没有(因此 returns None
)。
在您的温度函数中,如果华氏温度在 30 到 90 之间,则您没有 returning 任何东西。这意味着它将 return 一个 None 值
def temp(fahrenheit):
if fahrenheit > 90:
fahrenheit = "hot"
return fahrenheit
if fahrenheit < 30:
fahrenheit = "cold"
return fahrenheit
return "nice weather" ###Or something like this
def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print()
print("The temperature is", temp(fahrenheit), "degrees Fahrenheit")
main()
想想你的函数的逻辑。您目前正在处理两种情况:
- 如果温度大于 90 度,你 return 热。
- 如果温度低于 30 度,你 return 感冒。
但是温度不满足以上任何一种情况怎么办?如果温度不大于 90 度 或 低于 30 度怎么办?看,你的问题是你没有考虑第三种可能的情况 - 温度既不大于 90 度也不低于 30,它在 之间 。
在您的函数中,如果前两个条件失败,您需要确定 return 的值:
def temp(fahrenheit):
if fahrenheit > 90:
return "hot"
if fahrenheit < 30:
return "cold"
else: # if 30 < fahrenheit < 90 is True...
return 'error'
华氏大于90度"hot"为return,小于30度为return"cold",但程序为[=21] =] 'None' 作为 return 值。我知道在 python 函数中默认 none 作为 return 值,但是我将华氏温度作为我的 return 值。有人可以解释为什么会这样吗?我是 python 的新手,正在尝试章节练习以更好地理解 python 语言。
# convert2.py
# A program to convert Celsius temps to Fahrenheit
# This version issues heat and cold warning
def temp(fahrenheit):
if fahrenheit > 90:
fahrenheit = "hot"
return fahrenheit
if fahrenheit < 30:
fahrenheit = "cold"
return fahrenheit
def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print()
print("The temperature is", temp(fahrenheit), "degrees Fahrenheit")
main()
如果温度既不高于 90 也不低于 30,则您的函数 returns 什么都没有(因此 returns None
)。
在您的温度函数中,如果华氏温度在 30 到 90 之间,则您没有 returning 任何东西。这意味着它将 return 一个 None 值
def temp(fahrenheit):
if fahrenheit > 90:
fahrenheit = "hot"
return fahrenheit
if fahrenheit < 30:
fahrenheit = "cold"
return fahrenheit
return "nice weather" ###Or something like this
def main():
celsius = float(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print()
print("The temperature is", temp(fahrenheit), "degrees Fahrenheit")
main()
想想你的函数的逻辑。您目前正在处理两种情况:
- 如果温度大于 90 度,你 return 热。
- 如果温度低于 30 度,你 return 感冒。
但是温度不满足以上任何一种情况怎么办?如果温度不大于 90 度 或 低于 30 度怎么办?看,你的问题是你没有考虑第三种可能的情况 - 温度既不大于 90 度也不低于 30,它在 之间 。
在您的函数中,如果前两个条件失败,您需要确定 return 的值:
def temp(fahrenheit):
if fahrenheit > 90:
return "hot"
if fahrenheit < 30:
return "cold"
else: # if 30 < fahrenheit < 90 is True...
return 'error'