2015-01-28 6 views
0

저는 파이썬을 사용하여 계산기 용 코드를 작성하고 있습니다. 여기에 나열된 또한 섹션 아래 IF가 WHILE 루프 내에서 작동하지 않는 이유는 무엇입니까? (Python 3.4)

loop = 1 
while loop == 1: #loop calculator while loop is TRUE 
    print ("""Options: 
     Addition  1) 
     Subtraction 2) 
     Multiplication 3) 
     Division  4) 
     Quit   5) 
     Reset Sum  6) """)  #display calculator's options 
    (' ') #spacer 
    choice = input("option: ") #get user input for calculator options 
#----------------------------------------------------------------------------Addition 
    if choice == 1:  #check if user wants to add 
     print (' ') #spacer 
     print ('Addition Loaded!') #tell the user they are adding 
     print (' ') #spacer 
     add1 = int(input('Base Number')) #get value for add1 
     sum = int(input('Number ta add')) #get value for sum 
     sum = add1 + sum #make sum equal the sum of add1 and sum 
     print (str(sum)) #print sum 
     addloop = 1  #set addloop to TRUE 
     while addloop == 1:  #continue addition while addloop = TRUE 
      add1 = int(input('Additional number to add')) #get value for add1 
      if add1 == 0: #check if add1 equals zero 
       print (' ') #spacer 
      sum = add1 + sum #make sum equal the sum of add1 and sum 
      if add1 != 0: #check if add1 is not equal to 0 
       print (str(sum)) #print sum 
      if add1 == 0: #check if add1 is equal to 0 
       print ('Total: ',) #print prefix 
       print (str(sum)) #print sum 
       addloop = 0 #set addloop to FALSE 

대신 IF의 ELIF를 사용하는 등 뺄셈, 곱셈, 다른 부분이 (그들이해야대로?). 문제는 사용자가 계산기에 대한 옵션 (더하기, 빼기 ...)을 선택하면 IF 또는 ELIF 문을 거치지 않고 while 루프로 다시 루프하는 것입니다. WHILE 루프 내에서 IF 문이 작동하지 않습니까?

choice = input("option: ") 

파이썬 3에서,이 choice문자열을두고 :

+2

소스의 모든 라인을 언급 할 필요가 없습니다 code, 특히 주석이 단지 코드를 반복하는 경우에 특히 – Jasper

+0

이 문제는 이해하기 어려울 수 있습니다 ...'print (choice)'는 정수를 나타내는 것처럼 보이지만 ...'print (repr (choice))'는 실제로 문자열 (결코 정수와 동일하지 않음). – tdelaney

+0

@ Jasper 나는 모든 의견을 남기는 습관을 갖기 위해 모든 라인에 댓글을 달았다. 나는 미래에 불필요한 행을 언급 할 의도는 없으며 조기에 그렇게하는 법을 배울 수 있습니다. – stapler8

답변

4

는 여기에 귀하의 문제입니다. 이 정수가 아닌 ValueError 경우 사용자 유형 뭔가를 올릴 것이다

choice = int(input("option: ")) 

: 당신은 정수가 필요합니다. 당신은 try/except ValueError 블록과 그 잡을 수, 또는 당신은 질문에 표시되는 choice 라인을 떠나 같이하는 모든 비교를 변경할 수 있습니다

if choice == "1": # compare to a string instead of an integer 
+1

쉬운 방법은 다음과 같습니다 : 인터프리터 ('python3')를 실행하고'1 == "1"'을 입력하십시오. 출력은'거짓 '입니다. –

관련 문제