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