python - 在基本脚本中使用 break 语句
问题描述
下面是一个简单的计算器程序,我在其中使用break
语句来控制逻辑,我想知道这对break
语句来说是否过分或者是否可以。
while True:
try:
print("Choose operation(+ | - | * | / | Enter 'e' to exit)")
op=input()
if op!="+" and op!="-" and op!="*" and op!="/" and op!="e":
print("Invalid input, you must choose an option from the menu.")
break
elif op=="e":
break
else:
print(">")
val1=float(input(val1))
print(">")
val2=input()
val2=float(input(val2))
if op=="+":
print("= ", val1+val2)
elif op=="-":
print("= ", val1-val2)
elif op=="*":
print("= ", val1*val2)
else:
print("= ", val1/val2)
except ValueError:
print("Input must be numerical.")
break
except ZeroDivisionError:
print("Dividing by zero is undefined.")
break
exit()
解决方案
更新:
基本上我所做的是修复缩进,删除两次val2
,删除exit()
调用,将所有内容放在一个函数中,然后从另一个while True
循环调用它。如果输入错误,程序将再次调用该函数并尝试要求用户输入正确。如果用户输入是e
,则函数返回“EXIT”,然后程序将终止。
顺便说一句,您可以在没有函数的情况下使用 2 个嵌套的 for 循环来执行此操作,尽管我认为它看起来不会像现在这样好。
def calculator():
while True:
try:
print("Choose operation(+ | - | * | / | Enter 'e' to exit)")
op=input()
if op not in ("+", "-", "*", "/", "e"): # Changed that too, more simple now
print("Invalid input, you must choose an option from the menu.")
break
elif op == "e":
return "EXIT"
else:
print(">")
val1=float(input())
print(">")
val2=float(input())
if op == "+":
print("= ", val1+val2)
elif op == "-":
print("= ", val1-val2)
elif op == "*":
print("= ", val1*val2)
else:
print("= ", val1/val2)
except ValueError:
print("Input must be numerical.")
break
except ZeroDivisionError:
print("Dividing by zero is undefined.")
break
return "OK"
while True:
if calculator() == "EXIT":
break
这就是具有多种功能的解决方案:
def is_valid(user_input):
if user_input not in ("+", "-", "*", "/", "e"):
print("Invalid input, you must choose an option from the menu.")
return False
return True
def result(val1, val2, op):
if op == "+":
print("= ", val1 + val2)
elif op == "-":
print("= ", val1 - val2)
elif op == "*":
print("= ", val1 * val2)
else:
if val2 != 0:
print("= ", val1 / val2)
else:
print("Dividing by zero is undefined.")
def caculater():
while True:
op=input("Choose operation(+ | - | * | / | Enter 'e' to exit)\n")
if not is_valid(op):
break
if op == "e":
return "e"
else:
try:
val1=float(input("> "))
val2=float(input("> "))
result(val1, val2, op)
except ValueError:
print("Input must be numerical.")
return "OK"
while True:
if caculater() == "e":
break
推荐阅读
- python - 为什么在除块之外的python中包含错误类型会减少运行时间?
- python - 自定义损失函数:NotImplementedError:无法将符号张量(truediv_2:0)转换为 numpy 数组
- sql - 用于返回分隔字符串不匹配的行的 SQL 表达式
- python-3.x - 我如何从 transfermarkt 上的玩家那里抓取多个国家/地区的图像并且仍然避免双重国籍?
- javascript - 我将如何使用 Discord.js 制作一个“主持活动”的机器人?
- python - 我试图了解神经网络训练中的“时代”。接下来的实验是否相同?
- c++ - 如何在 C++ 中使用 std::unique_ptr?
- go - 如何使用 godoc 做文档
- android - 回收站视图不显示列表
- c - c程序中的SHA256和RIPEMD160HASH