I just started learning Python yesterday and one of the programs I'm trying to write is a calculator. This segment of code is where I'm having problems. The while loop is supposed to stop when the user inputs any of the math operators but it still asks for input even when the user enters one the correct characters.

What do I need to do to fix this.

    op = None                                 
    while (op != "-" or op != "+" or op != "*" or op != "/"):
        op = input("Enter operator (-, +, *, /):  ")
    print(op)

推荐答案

  op = None                                 
while op not in ["-","+","*","/"]:
    op = input("Enter operator (-, +, *, /):  ")
print(op)

or

op = None                                 
while (op != "-" and op != "+" and op != "*" and op != "/"):
    op = input("Enter operator (-, +, *, /):  ")
print(op)

your code isnt working because while "op" might be equal to one of your options, its not equal to all the others, and therefore continues the loop

Python相关问答推荐

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

如何创建一个缓冲区周围的一行与manim?

导入...从...混乱

字符串合并语法在哪里记录

无法连接到Keycloat服务器

为什么Django管理页面和我的页面的其他CSS文件和图片都找不到?'

Flash只从html表单中获取一个值

重置PD帧中的值

在Python中从嵌套的for循环中获取插值

计算空值

Odoo16:模板中使用的docs变量在哪里定义?

有没有办法在不先将文件写入内存的情况下做到这一点?

按条件添加小计列

以极轴表示的行数表达式?

大型稀疏CSR二进制矩阵乘法结果中的错误

如何通过函数的强式路径动态导入函数?

生产者/消费者-Queue.get by list

Django-修改后的管理表单返回对象而不是文本

根据两个lambda条件筛选组并根据条件创建新列的最佳方式是什么?

如何省略所有Pandas 数据帧