使用Python的简单计算器

0 投票
1 回答
2894 浏览
提问于 2025-04-18 12:49

你好,我是新手,刚开始学习 python。我正在做一个简单的计算器,但它没有正常工作。代码如下:

#calculator program
#this variable tells the loop whether it should loop or not.
# 1 means loop. anything else means don't loop.

loop = 1

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

choice = 0

while loop == 1:
#print what options you have
print ("Welcome to calculator.py")

print ("your options are:")
print (" ")
print ("1) Addition")
print ("2) Subtraction")

print ("3) Multiplication")

print ("4) Division")
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 ("Thankyou for using calculator.py!")

我按 F5 来运行时,出现了

Welcome to calculator.py
your options are:

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

Choose your option:

选择 1 后,它应该提示我输入数字,但却又回到了之前的状态,显示了

Welcome to calculator.py
your options are:

我觉得它在我输入 1、2、3、4 或 5 时,无法正确识别我的选择,然后又回去了。到底哪里出了问题呢?

1 个回答

1
choice = input("Choose your option: ")
choice = int(input("Choose your option: "))

当你输入选择为 1 时,它会把 1 作为字符串处理,但你却在用整数来比较。简单来说,就是把你的输入转换成 int 类型。

撰写回答