2013-04-30 2 views
0

최종 프로젝트를 위해 Python으로 간단한 계산기를 코딩하고 있는데 사용자가 입력 한 값이 float 데이터 유형인지 확인하는 데 문제가 있습니다. 값이 문자열 유형이라면 "값은 정수 또는 소수 일 필요합니다 - 유효한 숫자를 입력하십시오."라는 메시지를 출력 한 다음 사용자가 입력 할 때까지 사용자 입력을 요구하도록 루프를 다시 작성합니다. 유효한 항목. 나는 노력했다. 그러나 나는 갇혀있다. 그래서 여기 내 코드는 지금까지 있습니다 :float 데이터 유형 유효성 검사 Python

keepProgramRunning = True 

print ("Welcome to the Calculator Application!") 
good = True 
while keepProgramRunning: 

    print ("1: Addition") 

    print ("2: Subtraction") 

    print ("3: Multiplication") 

    print ("4: Division") 

    print ("5: Quit Application") 


    choice = input("Please choose what you would like to do: ") 

    if choice == "1": 
     n1 = float(input ("Enter your first number: ")) 
     n2 = float(input ("Enter your second number: ")) 
     print ("Your result is: ", n1 + n2) 
    elif choice == "2": 
     n1 = float(input ("Enter your first number: ")) 
     n2 = float(input ("Enter your second number: ")) 
     print ("Your result is: ", n1 - n2) 
    elif choice == "3": 
     n1 = float(input ("Enter your first number: ")) 
     n2 = float(input ("Enter your second number: ")) 
     print ("Your result is: ", n1 * n2) 
    elif choice == "4": 
     n1 = float(input ("Enter your first number: ")) 
     n2 = float(input ("Enter your second number: ")) 
     try: 
      print ("Your result is: ", n1/n2) 
     except: 
      if n2 == 0: 
       print ("Zero Division Error - Enter Valid Number") 
       while good: 
        n2 = float(input ("Enter your second number: ")) 
        if n2!=0: 
         good =False 
         print ("Your result is: ", n1/n2) 
    elif choice == "5": 
     print ("Thank you for using the calculator. Goodbye!") 
     keepProgramRunning = False 
    else: 
     print ("Please choose a valid option.") 

답변

4

는이 라인의 각, 당신은 여기 파이썬 3.x를를 사용하는 가정 :

n1 = float(input ("Enter your first number: ")) 

... ValueError 경우 주어진 무언가를 올릴 것 없습니다 float로 변환 할 수 있습니다.

따라서 유효성을 확인한 다음 변환하는 대신 변환을 시도하고 변환기를 자체 유효성 검사기로 지정하십시오. 대신이의 예를 들어

:

n1 = float(input ("Enter your first number: ")) 
n2 = float(input ("Enter your second number: ")) 
print ("Your result is: ", n1 + n2) 

... 당신은이 작업을 수행 할 수 있습니다

while True: 
    try: 
     n1 = float(input ("Enter your first number: ")) 
     n2 = float(input ("Enter your second number: ")) 
    except ValueError: 
     print("When I ask for a number, give me a number. Come on!") 
    else: 
     print ("Your result is: ", n1 + n2) 
     break 

별도로 각 값을 확인하고 싶은 경우에, 다만 try를 통해 두 개의 작은 루프를 할 하나의 큰 것 대신에.


이 코드를 6 번 복사하여 붙여 넣는 대신 함수로 리팩토링하는 것이 좋습니다. 이런 식으로 뭔가 :

def get_two_floats(): 
    while True: 
     try: 
      n1 = float(input ("Enter your first number: ")) 
      n2 = float(input ("Enter your second number: ")) 
     except ValueError: 
      print("When I ask for a number, give me a number. Come on!") 
     else: 
      return n1, n2 

또는 별도로 각각의 유효성을 검사 할 경우 :

def get_float(): 
    while True: 
     try: 
      return float(input ("Enter your second number: ")) 
     except ValueError: 
      print("When I ask for a number, give me a number. Come on!") 

def get_two_floats(); 
    return get_float(), get_float() 

그런 다음이 작업을 수행 할 수 있습니다 보조 노트로

if choice == "1": 
    n1, n2 = get_two_floats() 
    print ("Your result is: ", n1 + n2) 
elif choice == "2": 
    n1, n2 = get_two_floats() 
    print ("Your result is: ", n1 - n2) 
# etc. 

를 : 0으로 나눗셈을 잡으려면 모든 예외를 처리 한 다음 입력을 기반으로 오류의 원인을 알아내는 대신를 처리하십시오.. 일반적으로 except:sys.exc_info(), 012--ing 또는 이와 비슷한 것을 사용하지 않는 한 나쁜 아이디어입니다. except SpecificException:을 사용하면 거의 항상 더 좋으며, 더 자주는 except SpecificException as e:이므로 뭔가 할 수 있습니다. 오류 메시지에서 print 그것을 같은 e로.)

-1
# get original input 
n1 = raw_input("enter your number: ") 

while not (n1.isdigit()): 
# check of n1 is a digit, if not get valid entry 
    n1 = raw_input ("enter a valid number: ") 

num1 = float(n1) # convert string to float 



n2 = raw_input("enter number: ") 
while not (n2.isdigit()): 
    n2 = raw_input("enter a valid number: ") 

num2 = float(n2) 
+1

이 (가) 나쁜 생각은, (b)는 정확하지 (''3.2 ''완벽하게 유효한'float'이다, 그러나 아니다 'isdigit()'), (c) 잘못된 버전의 파이썬에 대해서 (OP는'print'를 함수로 사용하고,'input'을 문자열 등), 그리고 (d) 표준 파이썬 스타일이 아닙니다 (예 :'while' 조건에 여분의 괄호 추가). – abarnert