2013-04-04 22 views
0

一旦我明白了這一點,就會感到啞巴。如何解析輸入的字符串以提取單個數字

我正在編寫的程序提示操作(例如9 + 3),然後打印結果。

實施例運行:

>>>Enter an operation: 9+3 
>>>Result: 12 

我將具有用於運營商+,四個單獨的功能 - ,*,/和另一個功能,以接收用戶輸入和適當的功能返回後打印結果。

這是到目前爲止我的代碼(我只包括一個運營商功能):

def add(n, y): 
    result = "" 
    result = n + y 
    return result 

def main(): 
    op = input("Enter an operation: ") 
    for i in range(1,len(op)): 
     n = n[0] 
     y = y[2] 
     if (i == "+"): 
      result = add(n, y) 
    print("Result: ", result) 
    print("Bye") 

我在shell狀態n和y誤差不分配,所以我不從輸入它們解析正確。

回答

1

因爲他們沒有在函數體分配並在全球範圍內不可用:

def main(): 
    op = input("Enter an operation: ") 
    for i in range(1,len(op)): 
     n = n[0] # no n here yet so n[0] won't work 
     y = y[2] # no y here yet so y[2] won't work 

我想你的目標來解析輸入,然後使用這些值來執行加法,像即:

def main(): 
    op = input("Enter an operation: ") 
    i = op[1] 
    n = int(op[0]) 
    y = int(op[2]) 

    if i == "+": 
     result = add(n, y) 
    print("Result: ", result) 
    print("Bye") 

但它只會工作一個數字參數,所以你可能會考慮使用正則表達式一些適當的解析,不過那是另外一個問題。

+0

啊,謝謝。是的,你是正確的使用正則表達式,這可能會在這些基礎之後。 – Rac 2013-04-04 10:26:23

+0

你爲什麼進口重新使用它? – pradyunsg 2013-04-04 10:33:23

+0

這是一個剩餘的,我刪除它。 – 2013-04-04 10:37:33

0

有問題的代碼:

main,在n = n[0],你不會有任何n明確限定。所以你會得到一個錯誤。 y = y[2]也一樣。 在add您正在添加字符串。所以你會得到'93'作爲答案。

對於正確解析使用正則表達式
或者,如果你想快速的工作,少編碼版本(不推薦,如果你正在學習)
試試這個:

def main(): 
    while True: 
     # just a variable used to check for errors. 
     not_ok = False 

     inp = input("Enter an operation: ") 
     inp = inp.replace('\t',' ') 

     for char in inp: 
      if char not in '\n1234567890/\\+-*().': # for eval, check if the 
       print 'invalid input' 
       not_ok = True # there is a problem 
       break 
     if not_ok: # the problem is caught 
      continue # Go back to start 

     # the eval 
     try: 
      print 'Result: {}'.format(eval(inp)) # prints output for correct input. 
     except Exception: 
      print 'invalid input' 
     else: 
      break # end loop 

一些正則表達式鏈接:12

+0

'除了例外情況:打印'無效輸入''可能是一個壞主意,當出現一些意外的異常時,因爲它不一定意味着輸入錯誤。所以我不會把這段代碼推薦給正在學習的人。 – 2013-04-04 11:55:01