删除None并在python中终止?

2024-04-25 05:02:39 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的代码:

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

然而,当我运行我的代码时,我得到了一个None:

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命令应该导致程序终止。那么我该如何解决这个问题呢?你知道吗


Tags: and代码nonetruedatelenifdef
3条回答

您看到的None是display\u stats()函数的结果。所有Python函数都返回一个值,即使函数没有显式的return语句;如果它们没有return语句,它们返回的值也是None。这是打印None的行:

            print display_stats(d[1])

改为:

            display_stats(d[1])

None应该消失了。你知道吗

至于你的另一个问题,请替换为:

    elif c == 'q':

使用:

    elif c in ('q', 'x'):

这应该是你想要的。你知道吗

如果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

要使程序退出并删除“无”,请执行以下操作:

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

None出现是因为display\u stats已经进行了打印,然后返回了一些东西-所有函数都会这样做,很可能它返回None,然后在interact函数中打印出来:我只是在display\u stats调用之前删除了打印。你知道吗

相关问题 更多 >