计算器跳到结束循环?

如何解决计算器跳到结束循环?

我的计算器作业有问题,以下是说明:

  1. 使用列表创建菜单 2) 创建一个将返回的函数 字典中四个操作的结果 allInOne(n1,n2) 示例输出

  2. 将两个数字相加 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 语句(以退出函数)。

它是这样工作的:

  1. 调用calc()
  2. 等待它完成(通过 return 语句或到达函数结束后)
  3. 调用again()
  4. 如果返回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 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res