python - 当用户假设按数字而不是字母时如何使我的程序运行
问题描述
我正在制作计算器,例如,当用户不小心输入字母而不是数字时,程序就会崩溃。如何通过说“按下错误的键”来使其运行,并且只要有人键入字母,它就会继续打印该消息。直到用户输入一个数字,它才会继续。例如,在我的代码中,我想让 num1 和 num2 打印出“错误的按键错误”,而不是人们输入字母而不是数字。
编辑:我还希望结局在按下“y”和“n”以外的任何键时打印出错误消息
这是我的代码
def calculator():
print("") # leaves a line space
num1 = float((input("Enter first number ")))
operator = input("Enter an operator ")
num2 = float(input("Enter second number "))
if num1 == str:
print("Error: wrong key pressed")
if num2 == str:
print("Error: wrong key pressed")
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
if num2 == 0:
print("Error: You cannot divide a number by 0")
else:
print(num1 / num2)
else:
print("Error wrong key pressed")
restart = input("Press \"y\" to continue. If you wish to leave press \"n\" ")
if restart.lower() == "y":
calculator()
elif restart.lower() == "n":
print("Bye!")
exit()
calculator()
解决方案
只需像这样在您的输入语句周围添加一个 try catch。
def calculator():
print("") # leaves a line space
num1 = 0
num2 = 0
try:
num1 = float((input("Enter first number ")))
operator = input("Enter an operator ")
num2 = float(input("Enter second number "))
except Exception as e:
print("Error: wrong key pressed")
calculator()
if num1 == str:
print("Error: wrong key pressed")
if num2 == str:
print("Error: wrong key pressed")
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
if num2 == 0:
print("Error: You cannot divide a number by 0")
else:
print(num1 / num2)
else:
print("Error wrong key pressed")
restart = input("Press \"y\" to continue. If you wish to leave press \"n\" ")
if restart.lower() == "y":
calculator()
elif restart.lower() == "n":
print("Bye!")
exit()
calculator()
在里面try
我们编写语句,如果发生异常,它将在catch
语句中捕获。在您的情况下,我们将再次调用计算器程序。
推荐阅读
- c++ - 安装哪个组件来获取 Windows Docker 容器中的 VC 文件夹?
- java - 如何在 Java 文件中运行 Kotlin 库(通过 JitPack 分发)?
- arrays - 连接不同大小的二维数组(谷歌表格)
- r - 您可以增加 R 格式表中列名/标题的大小吗
- json - 如何使用从 axios 发送的数据更新订单?
- amazon-web-services - 如何在 EC2 上创建警报,如果实例保持打开超过 6 小时就会触发?
- azure - Azure 数据工厂 - 将数据从 ADLS 复制到 Cosmos DB - 在创建 ADLS 作为源的连接时出错
- php - 在 Laravel 7x 中找不到 App\XyzModel 错误
- python - QuickSort Python 中值三分区
- java - 使用 Java spring 和休眠的 Oracle 插入需要太多时间