2015-12-02 82 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))