我对Python还不熟悉。当我运行这段代码时,应该计算结果的最后一部分不会显示在shell上。有人能告诉我该怎么修吗?最后一部分似乎有点尴尬,但我不知道如何将str
转换为操作。你知道吗
# Set variables
opList = ["plus", "minus", "times", "divided-by", "equals"]
# Instrution
print("Intructions: Please enter + as plus, - as minus, * as times and / as divided-by.")
# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")
# Echo to the screen what the user has entered
print('The equation you entered is "%s".' %equation)
# Parse the equation into a list
theParts = equation.split() # default is whitespace
# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes
if len(theParts) == 0 :
print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
elif len(theParts) == 1 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 2 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 3 :
print("\nThe equation entered by the user is %s %s %s." %(theParts[0], theParts[1], theParts[2]))
if theParts[1] is str("plus"):
theAnswer == theParts[0] + theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("minus"):
theAnswer == theParts[0] - theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("times"):
theAnswer == theParts[0] * theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts [1] is str("divided-by"):
theAnswer == theParts[0] / theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
print("\nBye!")
假设您使用的是现代Python,input实际上是要使用的正确函数(3.x中没有原始的\u输入,input总是一个字符串)。但是,如前所述,还有其他问题。你知道吗
这是一个有一些修正的版本。你知道吗
如果您希望除法有更多的教科书响应,使用商和余数,那么应该使用divmod(p1,p2)来解析打印响应中的两个部分,而不是p1/p2。你知道吗
假设您使用的是Python2.x,主要的问题是您使用的是
input
而不是raw_input
。input
将计算公式并在程序中使用计算结果,而raw_input
将获得用户作为字符串键入的内容。例如:input
raw_input
无论使用哪种版本的Python,都必须修复以下问题:
压痕
在
theParts
有三个整数的情况下,您需要缩进代码,这样它才会执行。否则,不管发生什么,它都将执行,并给您一个数组越界错误,否则您将得到一个缩进格式错误。你知道吗测试字符串相等性
与其使用
is str("[string]")
,不如使用==
。不要试图把事情复杂化。你知道吗字符串与数字
为了做数学,你必须把字符串转换成数字。您可以使用
int("5")
这样的函数来实现,它等于5
(整数)。你知道吗示例代码
相关问题 更多 >
编程相关推荐