Python计算器代码

时间:2017-01-02 15:22:46

标签: python calculator

我对python很新,并试图开发一个计算器。我创建了它,所以它一直问你问题,直到你按9并退出。这样做时我犯了一个错误,它一直要求我输入第一个数字并继续循环

loop = 1
oper = 0

while loop == 1:    
    num1 = input("Enter the first number: ")
    print num1

    oper = input("+, -, *, /,9: ")
    print oper

    num2 = input("Enter the second number: ")
    print num2

    if oper == "+":
        result = int(num1) + int(num2)
    elif oper == "-":
        result = int(num1) - int(num2)
    elif oper == "*":
        result = int(num1) * int(num2)
    elif oper == "/":
        result = int(num1) / int(num2)
    elif oper == "9":
        loop = 0


    print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)

    input("\nPress 9 to exit.")

3 个答案:

答案 0 :(得分:1)

这是因为你从来没有做过任何事情要打破。尝试将oper更改为包含9

oper = raw_input("+, -, /, *, or 9 (to exit)": )

然后添加elif语句并将loop更改为0以退出while循环:

elif oper == "9":
    loop = 0

另外,处理你的缩进:

loop = 1

while loop == 1:    

    num1 = input("Enter the first number: ")
    print num1

    oper = input("+, -, *, /,9: ")
    print oper

    num2 = input("Enter the second number: ")
    print num2

    if oper == "+":
        result = int(num1) + int(num2)
    elif oper == "-":
        result = int(num1) - int(num2)
    elif oper == "*":
        result = int(num1) * int(num2)
    elif oper == "/":
        result = int(num1) / int(num2)
    elif oper == "9":
        loop = 0


print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)

答案 1 :(得分:1)

问题似乎是你没有缩进。 Python关心你缩进多少,因此只有缩进行将被视为while循环的一部分。这里只有第一行(num1 = input...)被认为是while循环的一部分。解决这个问题的最简单方法是在每个应该在循环中的行之前添加四个空格(以及if语句中每行之前的另外四个空格)。

有关更多帮助,请参阅http://www.diveintopython.net/getting_to_know_python/indenting_code.html

答案 2 :(得分:0)

你有缩进问题,这是一个更好的方法退出while循环使用break:

loop = 1
oper = 0

while loop == 1:

    x = input("Press 9 to exit otherwise anything to continue:")#much better way
    if x == "9":
        break
    num1 = input("Enter the first number: ")
    print (num1)

    oper = input("+, -, *, /: ")
    print (oper)

    num2 = input("Enter the second number: ")
    print (num2)

    if oper == "+":
        result = int(num1) + int(num2)
    elif oper == "-":
        result = int(num1) - int(num2)
    elif oper == "*":
        result = int(num1) * int(num2)
    elif oper == "/":
        result = int(num1) / int(num2):
    else:
       print("Invalid operator!") #if user inputs something else other than those


    print ("The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result))