Python简单计算器程序

2024-09-27 07:18:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在练习python3.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")

根据我的实践教程,一切看起来都很好,但当我运行代码时,输出如下所示:

^{pr2}$

当我输入选项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:

我无法前进,无论我输入什么选项,它都会给我相同的输出。有人能帮我一下吗?我在密码里遗漏了什么?在


Tags: thetopyloopinputyourthiscalculator
2条回答

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

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

^{pr2}$

注意,必须将add1和{}等值转换为整数,因为"1" + "2" == "12",而{}。在

input返回一个字符串,并且将其与整数进行比较,因此if都不能工作。在

只需将choice设为整数:

choice = int(input(...))

相关问题 更多 >

    热门问题