2014-01-11 63 views
-1

我有以下python代碼。Python 2中的錯誤函數

def nhap(a, b): 
    a = input("Enter number a: ") 
    b = input("ENter number b: ") 


def plus(a, b): 
    nhap(a, b) 
    print "Sum 2 so la: ", a + b 

def minus(a, b): 
    nhap(a, b) 
    print "Minus 2 so la: ", a - b 

def asterisk(a, b): 
    nhap(a, b) 
    print "Asterisk 2 so la: ", a*b 

def slash(a, b): 
    nhap(a, b) 
    print "Slash 2 so la: ", a/b 

def start(): 
    while True: 
     print "===================" 
     print "[0] Enter number" 
     print "[1] Sum" 
     print "[2] except" 
     print "[3] asterisk" 
     print "[4] slash" 
     print "[5] exit" 
     print "===================" 
     num = raw_input().strip() 
     if num == '0': 
     nhap(a, b) 
     elif num == '1': 
     cong(a, b) 
     elif num == '2': 
     tru(a, b) 
     elif num == '3': 
     nhan(a, b) 
     elif num == '4': 
     chia(a, b) 
     elif num == '5': 
     exit() 
start() 

當我運行我的程序時,我收到以下輸出和錯誤。

=================== 
[0] Enter number 
[1] Sum 
[2] except 
[3] asterisk 
[4] slash 
[5] exit 
=================== 
0 


Traceback (most recent call last): 

File "abc.py", line 46, in <module> 

start() 

File "abc.py", line 35, in start 

nhap(a, b) 

NameError: global name 'a' is not defined 

我如何調用該函數nhap()正確接受兩個數字,並執行正確的數學運算?

+2

在你的'start'函數中你沒有這兩個變量的實例化。 – varnie

回答

0

在函數nhap中獲得ab。請注意,它不接受ab,但從控制檯輸入並返回它們。我們需要的是使它作爲一個元組返回。在這裏,我們去:

#!/usr/bin/python 

def nhap(): 
    a = input("Enter number a: ") 
    b = input("ENter number b: ") 
    return (a, b) 

def plus(): 
    (a,b) = nhap() 
    print "Sum 2 so la: ", a + b 

def minus(): 
    (a, b) = nhap() 
    print "Minus 2 so la: ", a - b 

def asterisk(): 
    (a, b) = nhap() 
    print "Asterisk 2 so la: ", a*b 

def slash(): 
    (a, b) = nhap() 
    print "Slash 2 so la: ", a/b 

def start(): 
    while True: 

     print "Enter number" 
     print "===================" 
     print "[1] Sum" 
     print "[2] except" 
     print "[3] asterisk" 
     print "[4] slash" 
     print "[nother button] exit" 
     print "===================" 

     num = raw_input().strip()   
     if num == '1': 
      plus() 
     elif num == '2': 
      minus() 
     elif num == '3': 
      asterisk() 
     elif num == '4': 
      slash() 
     else: 
      exit() 
start() 

什麼應該添加/固定:在nhap功能處理非數字輸入。我把它留給你;)

+0

好的,謝謝varnie – KevinKien

+0

@KevinKien現在是一切? – varnie