Python 脚本返回意外的“无"函数执行后 [英] Python Script returns unintended "None" after execution of a function
问题描述
背景:Python 初学者;搜索了这个问题,但我找到的答案更多是关于什么"的比为什么";
我打算做什么:创建一个函数,该函数从用户输入测试分数并根据等级量表/曲线输出字母等级;代码如下:
score = input("请输入考试成绩:")分数 = 整数(分数)def letter_grade(分数):如果 90 <= 分数 <= 100:打印(A")elif 80 <= 分数 <= 89:打印(B")elif 70 <= 分数 <= 79:打印(C")elif 60 <= 分数 <= 69:打印(D")elif分数<60:打印(F")打印(字母等级(分数))
这在执行时返回:
请输入考试成绩:45F没有任何
None
不是故意的.我发现如果我使用 letter_grade(score)
而不是 print (letter_grade(score))
, None
不再出现.>
我能找到的最接近的答案说的是python 中的函数返回 None ,除非明确指示否则".但我确实在最后一行调用了一个函数,所以我在这里有点困惑.
所以我想我的问题是:是什么导致了 None
的消失?我确信这是非常基本的东西,但我找不到任何解释幕后"的答案.机制.因此,如果有人可以对此有所了解,我将不胜感激.谢谢!
在python中,函数的默认返回值是None
.
所以,只需使用:
letter_grade(score) #去除打印
另一种选择是用 return
替换所有打印:
def letter_grade(score):如果 90 <= 分数 <= 100:返回A"elif 80 <= 分数 <= 89:返回B"elif 70 <= 分数 <= 79:返回C"elif 60 <= 分数 <= 69:返回D"elif分数<60:返回F"别的:#如果不满足所有其他条件则返回返回无效标记"
现在使用print()
:
Background: total beginner to Python; searched about this question but the answer I found was more about "what" than "why";
What I intended to do: Creating a function that takes test score input from the user and output letter grades according to a grade scale/curve; Here is the code:
score = input("Please enter test score: ")
score = int(score)
def letter_grade(score):
if 90 <= score <= 100:
print ("A")
elif 80 <= score <= 89:
print ("B")
elif 70 <= score <= 79:
print("C")
elif 60 <= score <= 69:
print("D")
elif score < 60:
print("F")
print (letter_grade(score))
This, when executed, returns:
Please enter test score: 45
F
None
The None
is not intended. And I found that if I use letter_grade(score)
instead of print (letter_grade(score))
, the None
no longer appears.
The closest answer I was able to find said something like "Functions in python return None unless explicitly instructed to do otherwise". But I did call a function at the last line, so I'm a bit confused here.
So I guess my question would be: what caused the disappearance of None
? I am sure this is pretty basic stuff, but I wasn't able to find any answer that explains the "behind-the-stage" mechanism. So I'm grateful if someone could throw some light on this. Thank you!
In python the default return value of a function is None
.
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not printed.
>>>
So, just use:
letter_grade(score) #remove the print
Another alternative is to replace all prints with return
:
def letter_grade(score):
if 90 <= score <= 100:
return "A"
elif 80 <= score <= 89:
return "B"
elif 70 <= score <= 79:
return "C"
elif 60 <= score <= 69:
return "D"
elif score < 60:
return "F"
else:
#This is returned if all other conditions aren't satisfied
return "Invalid Marks"
Now use print()
:
>>> print(letter_grade(91))
A
>>> print(letter_grade(45))
F
>>> print(letter_grade(75))
C
>>> print letter_grade(1000)
Invalid Marks
这篇关于Python 脚本返回意外的“无"函数执行后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!