2014-09-01 44 views
0

下面是我的代碼:刪除無並終止在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 

然而,當我運行我的代碼,我得到一個無以下幾點:

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

'None'是否來自display_stats函數?這是什麼代碼? – 2014-09-01 06:59:26

回答

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

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'): 

而且應該做你要找的內容。

+0

謝謝!有效! – Yoo 2014-09-01 07:03:44

+0

只是問爲什麼這個「elif c in('q','x'):」而不是elif c =='q':? – Yoo 2014-09-01 07:08:41

+0

@Pythonaddict - 我假設你想用*'q'或'x'作爲命令退出,所以我向你展示瞭如何一次檢查多個值的字符串。如果你只想'x'退出程序而不是'q',那麼你應該只有'elif c =='q':'(基本上,用你現有的行中的'q'替換'x')。 – rmunn 2014-09-01 10:12:01

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 ,然後將其打印在您的交互功能中:我只是在display_stats調用之前刪除了該打印。