2017-04-17 1 views
0

다중도 계산기를 만들었는데 거의 문제가 있습니다. 사용자가 문자열 입력을하면 숫자를 물어볼 때 코드가 끊어 지거나 오류가 발생합니다. if 문에 else:이 있습니다. 당신이 먼저 유효 확인하기 위해 확인하지 않고, 사용자의 입력에 int 유형을 주장하고 있기 때문에if/else 문에 코드가 깨졌습니다.

def Start(): 
    numberOneList = [] 
    numberTwoList = [] 
    multiples = 100000 
    iterations = 0 
    multiplicity = int(input("How many common multiplicities you would like to find between two numbers: ")) 

    if multiplicity > 0 and multiplicity < 100001: 
     numberOne = int(input("Input the first number: ")) 
     if numberOne > 0 and numberOne < 100001: 
      numberTwo = int(input("Input the second number: ")) 
      if numberTwo > 0 and numberTwo < 100001: 
       for i in range(multiples): 
        mNumberOne = numberOne * i 
        numberOneList.append(mNumberOne) 
        mNumberTwo = numberTwo * i 
        numberTwoList.append(mNumberTwo) 
       print("") 
       print("Common multiplicities:") 
       print("") 
       print("Calculating...") 
       print("") 
       for i in numberOneList: 
        for a in numberTwoList: 
         if a == i: 
          if a != 0: 
           print(numberOne, "x", i/numberOne, "=", i) 
           print(numberTwo, "x", a/numberTwo, "=", a) 
           print("") 
           iterations += 1 
           if iterations == multiplicity: 
            Again() 
           else: 
            continue 
          else: 
           continue 
         else: 
          continue 
      else: 
       print("Invalid answer, restarting") 
       Start() 
     else: 
      print("Invalid answer, restarting") 
      Start() 
    else: 
     print("Invalid answer, restarting") 
     Start() 

def Again(): 
    calculateAgain = input("Calculate again? [y/n]: ") 
    if calculateAgain == "y": 
     Start() 
    if calculateAgain == "n": 
     quit() 
    else: 
     Again() 

Start() 
+1

을 시도합니다. 'try/except'를 사용해야합니다. – kindall

+4

당신의 함수를 다시 실행하기 위해 재귀를 사용하지 말 것을 강력하게 권장합니다 ... while 루프를 사용하십시오. –

답변

0

당신은 오류가 있어요. @kindall은 comment에 표시되어 있으므로 try/except을 사용하면 실패한 유형의 어설 션을 찾아 정상적으로 처리 할 수 ​​있습니다. 당신의 int 포장하는 것은 같은 뭔가 캐스트 트릭해야 다음 : 현재에 대한

try: 
    multiplicity = int(input("How many common multiplicities you would like to find between two numbers: ")) 
except ValueError as e: 
    print('Please input a valid number') 
    return str(e) 

가 (대신 오류 텍스트를 반환하는 방금 대신 프롬프트를 반복 할 수 있습니다.)

+0

도움을 주셔서 감사합니다, 그것은 매력처럼 작동했습니다! –

+0

또한 일반 예외를 제외하면 안됩니다. 이 경우 ValueError를 사용하십시오. – DSLima90

0

한 빠른 수정을 코드를 입력 또는 유효하지 않은 값을 얻을 수있는 함수를 작성하는 경우는 int가 아닌

def input_positive_integer(message): 
    while(True): 
     try: 
      value = int(input(message)) 
      if (value<=0 or value > 100000): 
       raise ValueError("Not in range") 
      break 
     except ValueError as e: 
      print("Value error!! Try again!") 

그런 다음이 기능을 사용하기 위해서는 정수를받는 모든 사용자의 입력을 변경할 수 있습니다.

값이 유효 할 때까지 계속 루프됩니다.

난 정말 당신이 그 코드에 재귀를 방지하기 위해 제안 ... 루프 동안 간단한을 사용하여`else` 문을 잡기 오류와는 아무 상관이 없기 때문이다