1

最終プロジェクト用に Python で簡単な電卓をコーディングしていますが、ユーザーが入力した値が float データ型であることを検証するのに問題があります。値が文字列型の場合、「値は整数または小数でなければなりません-有効な数値を入力してください」と出力し、ループバックしてユーザーが入力するまでユーザー入力を求めるようにしたい有効なエントリ。試しましたが、行き詰まります。これまでの私のコードは次のとおりです。

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 に答える 3

-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) 
于 2013-04-30T01:03:06.057 に答える