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

2024-09-19 23:29:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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!") 

Tags: oftheinputbyisasprintenter
2条回答

假设您使用的是现代Python,input实际上是要使用的正确函数(3.x中没有原始的\u输入,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。你知道吗

假设您使用的是Python2.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])

相关问题 更多 >