尝试在接受int和str值的同时中断计算器程序的while循环

如何解决尝试在接受int和str值的同时中断计算器程序的while循环

我在学习python时正在编写计算器程序,我在高中学习Java时还不知道任何高级python函数,因此请尽量不要使用任何太高级的方法,但请解决我的问题。抱歉,如果这个问题组织得不好,我从来没有在这里发表过。整个程序将在底部。

我遇到的麻烦是让用户输入要使用的运算符,然后要求输入数字1和2。如果用户随时输入“退出”或“停止”,则程序退出,对于操作员部分,它可以正常退出并显示退出消息。但是当为num1或num2输入exit时,我没有得到想要的响应,我在使用它时遇到很多错误,但主要是num是int不能具有字符串值,num是str不能具有int,或者它接受'exit'/ “停止”,然后进入num2,然后在num2中输入任何内容后引发错误

operator = (input("Would you like to add(+),subtract(-),multiply(*),divide(/) or use exponents(**)? "))

if operator.lower() == 'exit' or operator.lower() == 'stop':
    break                       #this part works fine and as intended

num1 = eval(input("Enter number 1: "))
if num1 == str() and (num1.lower() == 'exit' or num1.lower() == 'stop'):
    break                       #this part however doesnt work because i have int and str in the same variable

num2 = eval(input("Enter number 2: "))
if num2 == str() and (num2.lower() == 'exit' or num2.lower() == 'stop'):
    break

我尝试过使用float,str或int来表示num,弄乱了if语句的位置,我希望能够接受'exit'或'stop'作为num的值,然后退出while循环,该程序已结束,但我尝试了一个小时左右,无法弄清楚。所以我的问题又是我需要num1和num2值,使其能够接受str和int并在它们等于“停止”或“退出”时结束程序。

operator = ''
num1 = ''
num2 = ''
while True:
    operator = (input("Would you like to add(+),divide(/) or use exponents(**)? "))

    if operator.lower() == 'exit' or operator.lower() == 'stop':
        break

    num1 = eval(input("Enter number 1: "))
    if num1 == str() and (num1.lower() == 'exit' or num1.lower() == 'stop'):
        break

    num2 = eval(input("Enter number 2: "))
    if num2 == str() and (num2.lower() == 'exit' or num2.lower() == 'stop'):
        break

    oldNum2 = num2

    if operator == 'add' or operator == '+':
        answer = num1 + num2
        print(num1,'+',num2,'=',answer)

    elif operator == 'subtract' or operator == '-':
        answer = num1 - num2
        print(num1,'-',answer)

    elif operator == 'multiply' or operator == '*':
        answer = num1 * num2
        print(num1,'*',answer)

    elif operator == 'divide' or operator == '/':
        answer = num1 / num2
        print(num1,'/',answer)

    elif operator == 'exponents' or operator == '**':
        answer = num1 ** num2
        print(num1,'**',answer)

    else:
        print('Please type a valid operator...')
print('Program has exited due to user input.')

解决方法

基本上只是将num1num2视为字符串,直到您知道它们不是stopexit为止,然后解析其中的数字:

def isExitCommand(userInput):
  return userInput.lower() == 'exit' or userInput.lower() == 'stop'

while True:
  operator = str(input("Would you like to add(+),subtract(-),multiply(*),divide(/) or use exponents(**)? "))

  if isExitCommand(operator):
      break                       #this part works fine and as intended

  num1 = input("Enter number 1: ")
  if isExitCommand(num1):
      break
  else:
    num1 = float(num1)             

  num2 = input("Enter number 2: ")
  if isExitCommand(num2):
      break
  else:
    num2 = float(num2)

  print("You entered {} {} {}".format(num1,operator,num2))

也无需检查输入是否为字符串,但是如果您确实想输入num1 == str()是不正确的。 str()仅给出一个空白字符串。您想用isinstance(s,str)代替Python 3.x

,

您的问题可能有很多答案,但是我会做的是摆脱eval()并只对待input(),因为它始终是字符串格式。

num1 = input("Enter number 1: ")
if num1.lower() == 'exit' or num1.lower() == 'stop':
    break
    
num2 = input("Enter number 2: ")
if num2.lower() == 'exit' or num2.lower() == 'stop':
    break

但是由于num1num2都在if语句之后都是字符串格式,因此请确保将它们强制转换为整数(或浮点数)

num1 = int(num1)
num2 = int(num2)
,

您的功能问题是这些验证检查的开始:

if num1 == str() and ...

您刚刚在支票上未通过检查。我认为,您正在尝试检查eval之后的输入类型(顺便说一下,这是要使用的baaaaaad函数)。

str()是将空参数转换为字符串的调用。这将返回一个空字符串。由于这将不等于任何非空输入,因此您将失败。

为此,请使用提供的功能:

if isinstance(num1,str)

更好的是,请先尝试检查值,然后再尝试进行转换:

user_input = input("What would you like to do?")
if user_input in ("stop","exit"):
    break

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 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 -> 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("/hires") 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<String
使用vite构建项目报错 C:\Users\ychen\work>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)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); 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> 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 # 添加如下 <configuration> <property> <name>yarn.nodemanager.res