此计算器适用于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)
答案 0 :(得分:1)
您正在将字符串与整数进行比较:
if operation == 1 # '1' == 1
始终为False
,因此没有if
块被执行。
执行字符串字符串比较:
if operation == '1'
当if
阻止条件得到修复时,其他错误将显示出来:
firstnum + secondnum
这将使您的字符串连接起来,而不是按照您的意图执行数字操作,而操作-
,*
和/
将引发TypeError
。您应该将您的操作数 firstnum 和 secondnum 投射到相应的类型:float
或int
。
此外,您还可以将所有if
子句链接到一个if-elif
子句