在计算器项目中使用 while 循环的问题

problem in using while loop in a calculator project

我正在创建一个计算器,其中我使用了一个 while 循环,以便用户可以一次又一次地进行计算。但是while循环有点问题。

这是代码:

print("CALCULATOR")

def addint(n1,n2):

    sum = n1 + n2

    return sum

def minusint(n1,n2):

    minus = n1 - n2

    return minus

def mult(n1,n2):

    multsum = n1 * n2

    return multsum

def div(n1,n2):

    divsum = n1 / n2

    return divsum

n1 = int(input("Enter First Number:\n"))

n2 = int(input("Enter Second Number:\n"))

n3 = str(input("Which Operator?\n"))

while n1 <= 0:

    if n3 == '+':

        print(f"The answer is {addint(n1,n2)}")

    elif n3 == '-':

        print(f"The answer is {minusint(n1,n2)}")

    elif n3 == '*':

        print(f"The answer is {mult(n1,n2)}")

    elif n3 == '/':

        print(f"The answer is {div(n1,n2)}")

    else:

        print("INVALID OPERATOR")

    break

这是输出 window:

CALCULATOR

Enter First Number:

20

Enter Second Number:

10

Which Operator?

-

出现的问题是,当我在输出 window 之后使用 while 循环时,计算没有像预期的那样发生。输入数字和运算符后,输出 window 就关闭了。第二个问题是用户不能反复计算。

为什么 while 条件是“while n1 <= 0”? 开箱即用,您输入的 n1 = 20 不 <=0。所以,根本不进入while循环

你可以这样做

while True:
    n1 = int(input("Enter First Number:\n"))
    n2 = int(input("Enter Second Number:\n"))
    n3 = str(input("Which Operator?\n"))

    if n3 == '+':
        print(f"The answer is {addint(n1,n2)}")

    elif n3 == '-':
        print(f"The answer is {minusint(n1,n2)}")

    elif n3 == '*':
        print(f"The answer is {mult(n1,n2)}")

    elif n3 == '/':
        print(f"The answer is {div(n1,n2)}")

    else:
        print("INVALID OPERATOR")
  1. while循环运行s里面的代码只要条件为真。在这种情况下,条件是 n1 <= 0。因此,如果 n1 = 20,循环将不会 运行 一次。如果你想要一个无限循环,使用 while True.
  2. 最后有一个break关键字,所以循环只会运行一次。
  3. 您的程序将永远打印相同的结果,因为输入指令在循环之外。

工作示例:

def addint(n1, n2):
    sum = n1 + n2
    return sum

def minusint(n1, n2):
    minus = n1 - n2
    return minus

def mult(n1, n2):
    multsum = n1 * n2
    return multsum

def div(n1, n2):
    divsum = n1 / n2
    return divsum

while True:
    n1 = int(input("Enter First Number:\n"))
    n2 = int(input("Enter Second Number:\n"))
    n3 = input("Which Operator?\n")

    if n3 == '+':
        print(f"The answer is {addint(n1,n2)}")
    elif n3 == '-':
        print(f"The answer is {minusint(n1,n2)}")
    elif n3 == '*':
        print(f"The answer is {mult(n1,n2)}")
    elif n3 == '/':
        print(f"The answer is {div(n1,n2)}")
    else:
        print("INVALID OPERATOR")

注意将 input("Which Operator?\n") 转换为 str 是不必要的,因为输入函数 returns string.