hak*_*121 3 python printing syntax python-3.x nonetype
规格:Ubuntu 13.04 Python 3.3.1
背景:Python初学者; 搜索了这个问题但我找到的答案更多的是"什么"而不是"为什么";
我打算做什么:创建一个功能,从用户输入测试分数输入,并根据年级比例/曲线输出字母等级; 这是代码:
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))
Run Code Online (Sandbox Code Playgroud)
这在执行时返回:
None
(letter_grade(score)
print (letter_grade(score))
"无"并非意图.而且我发现,如果我使用None而不是None,则"无"不再出现.
我能找到的最接近的答案说"像python中的函数返回None,除非明确指示不这样做".但我确实在最后一行调用了一个函数,所以我在这里有点困惑.
所以我想我的问题是:是什么导致了"无"的消失?我确信这是非常基本的东西,但我无法找到解释"幕后"机制的任何答案.所以,如果有人能对此有所了解,我将不胜感激.谢谢!
在python中,函数的默认返回值是None.
>>> def func():pass
>>> print func() #print or print() prints the return Value
None
>>> func() #remove print and the returned value is not printed.
>>>
Run Code Online (Sandbox Code Playgroud)
所以,只需使用:
letter_grade(score) #remove the print
另一种方法是用以下内容替换所有打印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"
Run Code Online (Sandbox Code Playgroud)
现在使用print():
>>> print(letter_grade(91))
A
>>> print(letter_grade(45))
F
>>> print(letter_grade(75))
C
>>> print letter_grade(1000)
Invalid Marks
Run Code Online (Sandbox Code Playgroud)