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

时间:2016-07-16 14:24:31

标签: python-3.x calculator

此计算器适用于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中,脚本在接受输入后什么都不做。

- UPDATE -

在感谢@ moses-koledoye的帮助后,我会发布最终的源代码,这可能对其他新手有所帮助。

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)

1 个答案:

答案 0 :(得分:1)

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

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

始终为False,因此没有if块被执行。

执行字符串字符串比较:

if operation == '1' 

if阻止条件得到修复时,其他错误将显示出来:

firstnum + secondnum

这将使您的字符串连接起来,而不是按照您的意图执行数字操作,而操作-*/将引发TypeError。您应该您的操作数 firstnum secondnum 投射到相应的类型:floatint

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