2015-12-02 79 views
-1

我想做一個高級訂購功能。代碼是好的。 但我不太確定爲什麼它輸出3次具有相同的值。 假設它應該是如果用戶輸入1,它會打印第一行代碼,等等。我一直得到相同的輸出。高級訂購功能 - 打印三次

def double(x): 
    return 2*x 

def square(x): 
    return x*x 

def cube(x): 
    return x*x*x 

def getInput(): 
    while True: 
     userInput = input("Enter the number you want to test") 
     try: 
      if (userInput <= 0): 
       print ("Please enter a valid number") 
     except ValueError: 
       print("Please enter a valid number") 
     else: 
      return userInput 
      break 

def getInput2(): 
    while True: 
     userInput2 = input("Choose your options\n 1 - double \n 2 - square \n 3 - cube") 
     try: 
      if (userInput2 <= 0): 
       print ("Please enter a valid number") 
     except ValueError: 
       print("Please enter a valid number") 
     else: 
      return userInput2 
      break 

userInputNum = getInput(); 
userInputOption = getInput2(); 

def doTwice(func,x): 

    if func(x== 1): 
     return double(double(userInputNum)) 
    elif func(x== 2): 
     return square(square(userInputNum)) 
    elif func(x== 3): 
     return cube(cube(userInputNum)) 
    else: 
     print ("Please enter only 1,2 or 3") 

print doTwice(double,userInputOption) 
print doTwice(square,userInputOption) 
print doTwice(cube,userInputOption) 

輸出給定的(因爲我的輸入選項1,和數字I鍵在計算爲4):

16 
16 
16 

輸出我想要的(因爲我的輸入選項1,和數量我密鑰計算爲4):

16 
256 
262144 
+1

你的函數'doTwice(FUNC,X)'從來沒有使用'func'或'x' ... – Cyrbil

+0

你永遠不會改變'userInputOption'所以由於參數相同,輸出總是相同的。 – Arc676

+0

編輯我的問題,請再次看看代碼 – stack

回答

3

這裏是與呼叫發生了什麼:doTwice(double, 4)

if double(4 == 1): 
    print "bla" 

Python會評估4 == 1表達式,找到一個True值並將其傳遞給double()True * 2仍然是True,因此除非您輸入1(我認爲),否則第一行將一直進行評估。

你可能想的代碼更是這樣的:

def doTwice(func,userInputNum): 
    return func(func(userInputNum) 

def selectFunction(userChoice, userInputNum): 
    if userChoice == 1: 
     return doTwice(double, userInputNum) 
    if userChoice == 2: 
     return doTwice(square, userInputNum) 
    if userChoice == 3: 
     return doTwice(cube, userInputNum) 
    else: 
     print("Please enter only 1,2 or 3") 

userInputNum = getInput() 
userInputOption = getInput2() 


print selectFunction(userInputOption) 
0

這是因爲doTwice總是選擇基於userInputOption功能。你可能會想是:

def doTwice(func, x): 
    return func(func(x)) 

,如果你想使用userInputOption你可以使用,但你應該將它作爲一個參數:

def doTwice(option, x): 
    if option == 1: 
     func = double 
    elif option == 2: 
     func = square 
    elif option == 3: 
     func = cube 
    else: 
     print("Bad option:{0}".format(option)) 
     return 
    print("{0}".format(func(x))) 

或者你可以使用一個dict

def doTwice(option, x): 
    try: 
     func = { 
      1 : double, 
      2 : square, 
      3 : cube, 
     }[option] 
     print("{0}".format(func(x))) 
    except KeyError: 
     print("Invalid option: {0}".format(option))