Python简单计算器程序

时间:2017-02-26 18:42:00

标签: python

我一直在练习python 3.6,我有这个程序在python中构建一个简单的计算器。

#Calculator Program

#This variable tells the loop whether it should loop or not.
#1 means loop. Everything else means don't loop.

loop=1

#This variable holds the user's choice in the menu:

choice=0

while loop==1:
    print("Welcome to calclator.py")

    print("Your options are")
    print("")
    print("1.Addition")
    print("2.Subtraction")
    print("3.Multiplication")
    print("4.Divison")
    print("5.Quit calculator.py")
    print("")

    choice=input("Choose your option:")
    if choice==1:
        add1=input("Add this:")
        add2=input("to this:")
        print(add1,"+",add2,"=",add1+add2)
    elif choice==2:
        sub2=input("Subtract this:")
        sub1=input("from this:")
        print(sub1,"-",sub2,"=",sub1-sub2)
    elif choice==3:
        mul1=input("Multiply this:")
        mul2=input("with this:")
        print(mul1,"*",mul2,"=",mul1*mul2)
    elif choice==4:
        div1=input("Divide this:")
        div2=input("by this:")
        print(div1,"/",div2,"=",div1/div2)
    elif choice==5:
        loop=0

print("Thank you for using calculator.py")

根据我的练习教程,一切看起来都很好但是当我运行代码时输出是这样的:

Welcome to calclator.py
Your options are

1.Addition
2.Subtraction
3.Multiplication
4.Divison
5.Quit calculator.py

Choose your option:

当我输入选项1时,它会给我输出:

Choose your option:1
Welcome to calclator.py
Your options are

1.Addition
2.Subtraction
3.Multiplication
4.Divison
5.Quit calculator.py

Choose your option:

我无法继续前进,无论我输入什么选项,它都会给我相同的输出。有人可以帮助我,我的代码中缺少什么?

2 个答案:

答案 0 :(得分:0)

input返回一个字符串;您正在将值与一系列整数进行比较。首先将结果转换为整数。

choice=input("Choose your option:")
try:
    choice = int(choice)
except ValueError:
    continue   # Go back to the top of the loop and ask for the input again

if choice==1:
    add1=int(input("Add this:"))
    add2=int(input("to this:"))
    print(add1,"+",add2,"=",add1+add2)

# etc

或者,只需将结果与字符串进行比较:

if choice == "1":

请注意,必须add1add2等值转换为整数,因为"1" + "2" == "12",而1 + 2 == 3

答案 1 :(得分:0)

input会返回一个字符串,并且您将其与整数进行比较,因此if都不会有效。

只需将choice设为整数:

choice = int(input(...))