首页 > 解决方案 > 在 Python 中制作计算器以检查有效性的问题

问题描述

我想创建一个简单的计算器,您可以在其中输入 2 个数字并选择您的操作并显示结果。

我完成了上述任务,但我想设计一个系统,在要求输入数字之前首先检查操作是否有效,如果选择的选项(操作)无效,则应要求用户再次选择。

print("Welcome to the Great Calculator")

print("                                     ")

print("Please choose Your Operation")

print("1 Addition")

print("2 Subtraction")

print("3 Multiplication")

print("4 Division")

print("5 Exponent")

choice=int(input("What is your choice?[1,2,3,4,5]: "))

print("                                     ")

while (choice ==1,2,3,4,5):
    n1=int(input("Please enter the First Number- "))

    print("                                     ")

    n2=int(input("Please enter the Second Number- "))

    if (choice==1):
        result=n1 + n2
        print("The Sum is",result)

    elif (choice==2):
        result=n1 - n2
        print("The Difference is",result)

    elif (choice==3):
       result=n1 * n2
       print("The Product is",result)

    elif (choice==4):
       result=n1 / n2
       print("The Quotient is",result)

    elif (choice==5):
       result=n1 ** n2
       print("The Answer is",result)

    else:
       print("Invalid Input")

else:
    print("Invalid Input")

我无法实现我的目标。请帮我。非常感谢。

标签: python

解决方案


在您的情况下,有效的选择是数字 1、2、3、4、5。首先我们将 设置choice为 0 以使choice无效并进入while循环,然后我们要求input. while只要所做的选择无效(choice not in [1, 2, 3, 4, 5]),程序就会陷入循环。

choice = 0
while choice not in [1, 2, 3, 4, 5]:
    choice=int(input("What is your choice?[1,2,3,4,5]: "))

print('\n')
n1 = int(input("Please enter the First Number- "))
print('\n')
n2 = int(input("Please enter the Second Number- "))

if choice == 1:
    result = n1 + n2
    print("The Sum is %s" % result)

elif choice == 2:
    result = n1 - n2
    print("The Difference is %s" % result)

elif choice == 3:
    result = n1 * n2
    print("The Product is %s " % result)

elif choice == 4:
    result = n1 / n2
    print("The Quotient is %s" % result)

elif choice == 5:
    result = n1 ** n2
    print("The Answer is %s" % result)

对脚本的一项可能改进是在将输入转换为整数之前检查输入是否为整数。例如,如果输入是字母而不是数字,您的脚本就会崩溃。


推荐阅读