2014-02-23 4 views
12

사전을 사용하여 파이썬으로 간단한 계산기를 만들려고합니다. 내 코드는 다음과 같습니다.사전을 파이썬에서 switch 문으로 사용하기

def default(): 
    print "Incorrect input!" 

def add(a, b): 
    print a+b 

def sub(a, b): 
    print a-b 

def mult(a, b): 
    print a*b 

def div(a, b): 
    print a/b 

line = raw_input("Input: ") 
parts = line.split(" ") 
part1 = float(parts[0]) 
op = parts[1]; 
part3 = float(parts[2]) 

dict = { 
    '+': add(part1, part3), 
    '-': sub(part1, part3), 
    '*': mult(part1, part3), 
    '/': div(part1, part3) 
    } 

try: 
    dict[op] 
except KeyError: 
    default() 

그러나 모든 기능이 활성화되었습니다. 뭐가 문제 야?

답변

8

양식 str : function 쌍처럼 사전을 정의합니다

my_dict = {'+' : add, 
      '-' : sub, 
      '*' : mult, 
      '/' : div} 

한 다음, 작업을 호출하는 기능을 얻을 수 my_dict[op]를 사용하고 해당 매개 변수로 전화를 전달하려면 :

my_dict[op] (part1, part3) 
|___________| 
     | 
    function (parameters) 

참고 : 변수의 이름으로 파이썬 내장 이름을 사용하지 마십시오. 예를 들어 dict 대신 my_dict을 사용하십시오.

+0

메모를 인쇄 : : 그리고 당신이 할 일 다른 개선 I 조언 번 결과를 인쇄하고, 기능 람다를 만드는 것입니다'dict'은 *하지 * 파이썬 키워드 :''dict '이 keyword.kwlist'에 없습니다. 그것은 내장 이름이지만 :''dir (d 내장 (__ builtins __)'에서 dict '. – jfs

5

사전이 채워지면 피연산자가 인 각 작업을 실행하고 결국 dict[op] (None 포함)을 호출하고 아무 작업도하지 않기 때문입니다. 모든 출력을 얻을 이유

# N.B.: in case this is not clear enough, 
#  what follows is the *BAD* code from the OP 
#  with inline explainations why this code is wrong 

dict = { 
    # executes the function add, outputs the result and assign None to the key '+' 
    '+': add(part1, part3), 
    # executes the function sub, outputs the result and assign None to the key '-' 
    '-': sub(part1, part3), 
    # executes the function mult, outputs the result and assign None to the key '*' 
    '*': mult(part1, part3), 
    # executes the function div, outputs the result and assign None to the key '/' 
    '/': div(part1, part3) 
    } 

try: 
    # gets the value at the key "op" and do nothing with it 
    dict[op] 
except KeyError: 
    default() 

, 그리고 아무것도 당신의 try 블록에 변화가 없습니다 : 어떻게됩니까

이다. 당신은 할 수 있습니다

실제로해야 할 일 :

dict = { 
    '+': add, 
    '-': sub, 
    '*': mult, 
    '/': div 
    } 

try: 
    dict[op](part1, part3) 
except KeyError: 
    default() 

하지만 같은 @christian 현명하게 당신이 변수 이름으로 파이썬 예약 된 이름을 사용해서는 안 제안, 그 문제로 당신을 이끌 수 있습니다. 결과를 반환합니다

d = { 
    '+': lambda x,y: x+y, 
    '-': lambda x,y: x-y, 
    '*': lambda x,y: x*y, 
    '/': lambda x,y: x/y 
    } 

try: 
    print(d[op](part1, part3)) 
except KeyError: 
    default() 

하고 그것을

+0

N.B : 무엇이 잘못되었는지를 나타 내기 위해 downvoting 할 때 게시물에 대해 의견을 말하고 제안을하는 것이 좋습니다. – zmo

+0

답은 정확하지 않으므로 downvoter가 아니지만 솔루션이 내 것과 거의 동일하므로 '-1'이라고 생각합니다. 방금 람다 파트를 추가했습니다. – Christian

+0

글쎄, 우리는 실제로 같은 시간에 첫 번째 부분을 게시 했으므로 should'nt 이유는 :-) – zmo

관련 문제