以下是我的代码:
def interact():
d = c.split()
while True:
if d[0] =='date' and len(d) == 2:
print display_stats(d[1])
elif c == 'q':
return
else:
print "Unknown Command: ",c
break
然而,当我运行我的代码时,我得到以下的无:
Welcome to calculator
Maximum Power Outputs:
Building 1 351.2kW
Building 2 7.0kW
Building 3 275.9kW
Building 4 269.1kW
None
请帮助修复代码并删除无!同样在elif
中,如果raw_input = 'x'
,x命令应该导致程序终止。那么我该如何解决这个问题?
答案 0 :(得分:2)
您看到的None
是您的display_stats()函数的结果。所有Python函数都返回一个值,甚至是没有明确return
语句的函数;如果他们没有return
语句,则返回的值为None
。这就是打印None
:
print display_stats(d[1])
将其更改为:
display_stats(d[1])
并且None
应该消失。
关于您的其他问题,请替换:
elif c == 'q':
使用:
elif c in ('q', 'x'):
那应该做你正在寻找的事情。
答案 1 :(得分:1)
如果Python中的方法没有return
语句,则返回的默认值为None
。这就是你所看到的。
要阻止这种情况发生,只需添加一个返回值即可。对于你的另一部分,要退出应用程序,只需先检查是否有人想要退出,然后再开始循环。
import sys
def interact():
print "Welcome to calculator"
print
c = raw_input("Command: ")
# Just do the check here, so you don't bother running the rest of the code
if c == 'x':
sys.exit()
print
d = c.split()
while True:
if d[0] =='date' and len(d) == 2:
print display_stats(d[1])
elif c == 'q':
return
else:
print "Unknown Command: ",c
break
return '' # Return a blank string
答案 2 :(得分:1)
要退出程序,请删除无:
import sys
def interact():
print "Welcome to calculator"
print
c = raw_input("Command: ")
print
d = c.split()
while True:
if d[0] =='date' and len(d) == 2:
display_stats(d[1])
elif c == 'q':
return
elif c == 'x':
sys.exit()
else:
print "Unknown Command: ",c
break
由于display_stats已经打印,因此返回None,然后返回一些东西 - 所有函数都会执行,并且很可能它返回None,然后打印在interactive函数中:我只是在display_stats之前删除了print调用