困在文本计算器上

时间:2014-08-20 04:27:10

标签: python-3.x

当我运行此代码时,它输出"输入第一个数字。"并允许输入,然后重复。我不知道问题是什么。我在这里也听说过使用eval会更容易。我还没看好它,但我打算。 P.S。:我确信你可以看到,我提出了无关的代码来试图弄清楚发生了什么。

condition0=False
condition1=0
x=1

while 1==1:

while condition0==True:
    restart=input("to restart calculations enter \'true\'")

    if restart != "true":
        numone=answer
        condition1=1
    else:
        condition1=0

while condition1==0:
    numone=input("Enter the first number: ")
try:
    numone=int(numone)
    condition1=1
except ValueError:
    print("you must enter an integer!")
    condition1=0

condition2=0
while condition2==0:
    operator = input("Enter the operator(+,-,*,/):")
if operator=="+"|operator=="-"|operator=="*"|operator=="/":
    condition2=1
else:
    print("you must enter an operator!")
    condition2=0

condition3=0
while condition3==0:
    numtwo=input("Enter another number: ")
try:
    numtwo=int(numtwo)
    condition3=1
except ValueError:
    print('you must enter an integer!')
    condition3=0

if operator== '+':
    answer=int(numone)+int(numtwo)
    print(answer)
    print("test")

elif operator == "-":
    answer=int(numone)-int(numtwo)
    print(answer)

elif operator == "*":
    answer=int(numone)*int(numtwo)
    print(answer)

elif operator == "/":
    answer=int(numone)/int(numtwo)
    print(answer)

else:
    print("something went wrong")

print(x + "time(s) through the while loop")
condition0=True

2 个答案:

答案 0 :(得分:1)

这是您代码的实际缩进吗?如果是这样,try和except块需要在其上方的while循环下缩进,以便condition1值更改。否则它只是一遍又一遍地经过while循环。这适用于你的几个循环。

while condition1==0:
    numone=input("Enter the first number: ")
    try:
        numone=int(numone)
        condition1=1
    except ValueError:
        print("you must enter an integer!")
        condition1=0

condition2=0
while condition2==0:
    operator = input("Enter the operator(+,-,*,/):")
    if operator=="+"|operator=="-"|operator=="*"|operator=="/":
        condition2=1
    else:
        print("you must enter an operator!")
        condition2=0

condition3=0
while condition3==0:
    numtwo=input("Enter another number: ")
    try:
        numtwo=int(numtwo)
        condition3=1
    except ValueError:
        print('you must enter an integer!')
        condition3=0

答案 1 :(得分:0)

while condition1==0:
    numone=input("Enter the first number: ")
try:
    numone=int(numone)
    condition1=1
except ValueError:
    print("you must enter an integer!")
    condition1=0
...(the rest of the code)

现在try,其余代码不在while范围内。因此,程序将要求numone,直到condition1等于零。并且它总是等于零,因为condition1在循环内永远不会改变。 我想,它应该是这样的:

while condition1==0:
    numone=input("Enter the first number: ")
    try:
        numone=int(numone)
        condition1=1
    except ValueError:
        print("you must enter an integer!")
        condition1=0