python - 在 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")
我无法实现我的目标。请帮我。非常感谢。
解决方案
在您的情况下,有效的选择是数字 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)
对脚本的一项可能改进是在将输入转换为整数之前检查输入是否为整数。例如,如果输入是字母而不是数字,您的脚本就会崩溃。
推荐阅读
- android-studio - Strings.xml 文件和 values.xml 文件错误
- java - 复选框状态硒
- react-native - React Native 可能出现未处理的 Promise Rejection (id)
- java - 并发多线程请求的 Java OKHTTP SocketTimeoutException
- python - 如何使用 Python 将时间序列转换为显示时间序列每个元素的计数的两列数据框
- gcc - 如何确定给定编译标志的 GCC 的最小/最大版本?
- javascript - Sitecore Headless Next.js 404 错误页面不起作用
- node.js - 从前端调用 API 端点不返回数据,但直接调用 API 有效
- core-nfc - 完成 NFCTagReaderSession 的标准是什么?
- laravel - Laravel:模块未存储到数据库中