我的部分代码不会在shell中显示。 (if / elif声明)

时间:2016-01-29 00:51:13

标签: python

我是Python的新手。当我运行此代码时,应该计算结果的最后部分不会显示在shell上。有人能告诉我该如何解决这个问题?最后一部分看起来有点尴尬,但我不知道如何将Range("B2:G2").Cells(i + 1).Clear转换为操作。

str

2 个答案:

答案 0 :(得分:1)

假设您正在使用Python 2.x,那么让您陷入困境的主要问题是您使用的是input而不是raw_inputinput将评估您的等式并在您的程序中使用评估,而raw_input将获得用户键入的字符串。例如:

input

# what the user types
3 + 7
# what the program gets as an integer
10

raw_input

# what the user types
3 + 7
# what the program gets as a string
"3 + 7"

无论您使用的是哪种版本的Python,都必须修复以下内容:

压痕

对于theParts有三个整数的情况,您需要缩进代码,以便它只执行。否则它将执行无论什么,并给你一个数组越界错误或你将得到缩进格式错误。

测试字符串相等性

而不是使用is str("[string]"),只需使用==即可。不要试图使事情过于复杂。

字符串与数字

为了进行数学运算,您必须将字符串转换为数字。你可以使用类似int("5")(整数)的5之类的东西来做到这一点。

示例代码

# case 3
elif len(theParts) == 3:
    # do stuff
    if "plus" == theParts[1]:
        theAnswer = int(theParts[0]) + int(theParts[2])

答案 1 :(得分:0)

假设您使用的是现代Python,输入实际上是正确使用的函数(3.x中没有raw_input,输入始终是字符串)。但是,如上所述,还有其他问题。

这是一个带有一些更正的版本。

# Instruction 
# I changed the instructions to make them more precise and get rid of the unneccesarily awkward operators
print("Instructions: Please enter a simple equation of the form 'integer [operator] integer', where [operator] is '+', '-', '*' or '/'.")
print("Instructions: Make sure to put spaces between each element.")

# 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! :)")
# Since the two conditions warranted the same response, I just condensed them.
elif len(theParts) == 1 or 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]))
    # I set the answer before the conditions to a float, so division can result in more meaningful answers
    theAnswer = 0.0
    # I cast the input strings to integers
    p1 = int(theParts[0])
    p2 = int(theParts[2])
    if theParts[1] is str("+"):
        theAnswer = p1 + p2
    elif theParts[1] is str("-"):
        theAnswer = p1 - p2
    elif theParts[1] is str("*"):
        theAnswer = p1 * p2
    elif theParts [1] is str("/"):
        theAnswer = p1 / p2
    print('The anwser of the input equation is "{}".'.format(theAnswer))



print("\nBye!")

如果你希望师有更多的学校书回应,有商和余数,那么你应该使用divmod(p1,p2)而不是p1 / p2来解析打印响应中的两个部分。