简单计算器适用于 Python 2 但不适用于 3

Simple calculator works in Python 2 but not 3

此计算器适用于 Python 2:

print ("First calculator!")

print ("")

firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
        print ("You mistyped")
        exit(0)
print ("")
secondnum=input ("Insert the second number: ")

if operation == 1:
    print ("The result is:", firstnum+secondnum)
if operation == 2:
    print ("The result is:", firstnum-secondnum)
if operation == 3:
    print ("The result is:", firstnum*secondnum)
if operation == 4:
    print ("The result is:", firstnum/secondnum)

但在 Python 3 中,脚本在接受输入后什么也不做。

--更新--

感谢@moses-koledoye 的帮助修复后,我将 post 最终源代码,它可能对其他一些新手有帮助。

print ("First calculator!")
print ("")

firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
        print ("You mistyped")
        exit(0)
print ("")
secondnum=input ("Insert the second number: ")

firstnum=int(firstnum)
secondnum=int(secondnum)

print ("")
if operation == "1":
    print ("The result is:", firstnum+secondnum)
elif operation == "2":
    print ("The result is:", firstnum-secondnum)
elif operation == "3":
    print ("The result is:", firstnum*secondnum)
elif operation == "4":
    print ("The result is:", firstnum/secondnum)

您正在将字符串与整数进行比较:

if operation == 1 # '1' == 1

将始终是 False,因此 if 块中的 none 将被执行。

改为进行 字符串-字符串 比较:

if operation == '1' 

if 块条件修复后,其他错误将出现:

firstnum + secondnum

这将连接您的字符串,而不是按照您的意图执行数字运算,而运算 -*/ 将引发 TypeError。您应该 cast 您的操作数 firstnumsecondnum 到适当的类型:floatint.


此外,您还可以将所有 if 子句链接成一个 if-elif 子句