如何解决计算器跳到结束循环?
我的计算器作业有问题,以下是说明:
-
使用列表创建菜单 2) 创建一个将返回的函数 字典中四个操作的结果 allInOne(n1,n2) 示例输出
-
将两个数字相加 2) 将两个数字相乘 3) 除以 4) Scalc 5) 合二为一 .. 6) ...
res=allInOne(5,2)
结果将以这种格式返回;
res 是字典 {"add":7,"sub":3,"mult":10,"div":2.5) 来自 res, 你要打印
5 + 2 = 7,5 - 2 = 3,5 * 2 = 10,5 / 2 = 2.5
应该发生的是,一旦您输入要计算的数字(例如 5 和 10),它会询问您想用这些数字做什么(加、减、乘、除或全部) 并根据您输入的内容,它会执行其中一项或全部操作,并返回包含您在开头输入的数字的值。
发生的事情是我将数字放入 (5 和 10) 并选择我想对数字做什么(添加它们),而不是返回值,它再次跳到我的 def 结束() 循环并询问我是否要进行另一次计算并完全跳过计算我的数字。
我们被告知要导入包含我们定义的函数的“Mylib.py”,下面是我的计算器和 Mylib 的代码...
编辑:如果您对低范围和高范围感到困惑,这是我们的讲师希望我们从一开始就包含的内容。
课程
def again():
loop_Calc = input("\nWould you like to make another calculation? Enter Y or N. ")
if loop_Calc == 'y' or loop_Calc == 'Y':
calc()
elif loop_Calc == 'n' or loop_Calc == 'N':
print("Thank you for using our calculator!")
else:
quit()
def calc():
try:
import Mylib
low_Range = float(input("Enter your lower range: "))
high_Range = float(input("Enter your higher range: "))
number_1 = float(input("Enter first number: "))
number_2 = float(input("Enter second number: "))
if number_1 < low_Range or number_1 > high_Range:
print("The input values are outside the input ranges.")
print("Check the numbers and try again.")
again()
elif number_2 < low_Range or number_2 > high_Range:
print("The input values are outside the input ranges.")
print("Check the numbers and try again.")
again()
else:
print("\nPlease select a function below with the corresponding number.")
menuList = {"1) Add": 1,"2) Subtract": 2,"3) Multiply": 3,"4) Divide": 4,"5) All In One": 5,"6) Scalc": 6,}
for x in menuList:
print(x)
Choices = float(input("\nChoose a function: "))
res = {}
if Choices == '1' :
res["add"] = Mylib.add(number_1,number_2)
elif Choices == '2':
res["subtract"] = Mylib.subtract(number_1,number_2)
elif Choices == '3':
res["multiply"] = Mylib.multiply(number_1,number_2)
elif Choices == '4':
res["divide"] = Mylib.divide(number_1,number_2)
elif Choices == '5':
res = Mylib.allInOne(number_1,number_2)
elif Choices == '6':
p1 = input("Enter two numbers and the operator. N1,N2,Operator: ")
Mylib.scalc(p1)
for i in res:
if(i=='add'):
print(number_1,'+',number_2,'=',res[i])
if(i=='subtract'):
print(number_1,'-',res[i])
if(i=='multiply'):
print(number_1,'*',res[i])
if(i=='divide'):
print(number_1,'/',res[i])
except ValueError:
print("You must enter a number.")
again()
except ZeroDivisionError:
print("You cannot divide by zero.")
else:
again()
calc()
Mylib
# Input range calculation
def isInRange(low_Range,high_Range,number_1,number_2):
if number_1 < low_Range or number_2 < low_Range or number_1 > high_Range or number_2 > high_Range:
print("The input values are outside the input ranges.")
print("Check the numbers and try again.")
else:
print("The input values are outside the input ranges.")
print("Check the numbers and try again.")
# Functions to add,subtract,multiply,and divide numbers
def add(number_1,number_2):
return number_1 + number_2
def subtract(number_1,number_2):
return number_1 - number_2
def multiply(number_1,number_2):
return number_1 * number_2
def divide(number_1,number_2):
return number_1 / number_2
# String functions to parse N1,and operator from input string
def scalc(p1):
astring = p1.split(",")
number_1 = float(astring[0])
number_2 = float(astring[1])
if astring[2] == "+":
add(number_1,number_2)
elif astring[2] == "-":
subtract(number_1,number_2)
elif astring[2] == "*":
multiply(number_1,number_2)
elif astring[2] == "/":
divide(number_1,number_2)
return number_1,number_2
# Returns the result of all 4 operations
def allInOne(number_1,number_2):
print("The result of","+","=",add(number_1,number_2))
print("The result of","-",subtract(number_1,"*",multiply(number_1,number_2))
try:
print("The result of","/",divide(number_1,number_2))
except ZeroDivisionError:
print("You cannot divide by zero.")
如果您能提供帮助,将不胜感激,希望我的代码不会太乱!
解决方法
首先:您的程序没有运行,因为您将 Choices
设为浮点数,然后检查它是否等于其中一个字符串。你应该只写 Choices = input("\nChoose a function: ")
但是你的代码仍然有更多的错误并且太乱了:
第二:
...
elif Choices == '5':
res = Mylib.allInOne(number_1,number_2)
它假设 allInOne
返回字典,但它不返回任何东西(这被解释为它返回 None
)
第三:scalc
函数存在问题,因为它无论如何都没有响应用户。
第四:如果您重新输入值的次数过多,您的程序最终会失败,因为当调用 again()
时,calc()
会继续工作。这是递归(并且python最大递归深度非常小)。如果用户想继续,您应该重写 again()
以返回 True
,否则返回 False:
def again():
loop_Calc = input("\nWould you like to make another calculation? Enter Y or N. ")
if loop_Calc == 'y' or loop_Calc == 'Y':
return True
elif loop_Calc == 'n' or loop_Calc == 'N':
print("Thank you for using our calculator!")
return False
else:
return False
然后创建函数 cycle
def cycle():
while True:
calc()
if not again():
break
为了使其工作,您必须将 again()
主体中的所有 calc()
语句替换为 return
语句(以退出函数)。
它是这样工作的:
- 调用
calc()
- 等待它完成(通过 return 语句或到达函数结束后)
- 调用
again()
- 如果返回
False
,则结束循环
之后调用 cycle()
作为主函数
5th: 行 import Mylib
应该是文件中的第一行(只是约定)
6th: Choices
不应该大写(choices
),因为它是一个普通的变量,大写的通常是,例如类
第七:有一种东西叫做链式比较。例如,a > lower and a < higher
可以改写为 lower < a < higher
。在代码中使用它以使其更具可读性。
8th: isInRange()
应该完成以给出正确的结果,如果数字在范围内并在您的代码中使用,因为您只需重复两次相同的大代码样本。
9th:使用字典做出多项选择,多if-elif
...嗯...漂亮
if(i=='add'):
print(number_1,'+',number_2,'=',res[i])
...
# should become this
for i in res:
sign = {
'add':'+','subtract':'-','multiply':'*','divide':'/'
}[i]
print(number_1,sign,res[i])
我认为你可以在这个脚本的其他地方使用它
10th:(是的,周年纪念)。 if loop_Calc == 'y' or loop_Calc == 'Y':
可以if loop_Calc.lower() == 'y'
11th:我认为您应该减少 try:
内的数字行,以避免捕获不需要的异常。例如:
try:
low_Range = float(input("Enter your lower range: "))
high_Range = float(input("Enter your higher range: "))
number_1 = float(input("Enter first number: "))
number_2 = float(input("Enter second number: "))
except ValueError:
...
Also as `cycle()` is created,I believe you should use `try:` in it.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。