简体   繁体   English

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

[英]Parts of my code won't show in shell. (if/elif statement)

I'm new to Python. 我是Python的新手。 When I run this code, the last part where the results should be calculated is not shown on shell. 当我运行此代码时,应计算结果的最后一部分未显示在shell上。 Can someone tell me how should I fix this? 有人可以告诉我该如何解决? The last part seems a little bit awkward, but I have no idea how to convert str into operations. 最后一部分似乎有点尴尬,但我不知道如何将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!") 

Assuming you're using Python 2.x, the main issue that's getting you hung up is that you're using input instead of raw_input . 假设您使用的是Python 2.x,让您挂断电话的主要问题是您使用的是input而不是raw_input input will evaluate your equation and use the evaluation in your program, whereas raw_input will get exactly what the user types as a string. input将评估您的方程式并在您的程序中使用该评估,而raw_input将完全获得用户以字符串形式输入的内容。 For example: 例如:

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"

No matter what version of Python you're using, you'll have to fix the following: 无论您使用什么版本的Python,都必须修复以下问题:

Indentation 缩进

You'll need to indent the code for your case where theParts has three integers so it executes only then. 您需要为您的情况缩进代码,其中theParts具有三个整数,因此仅在那时执行。 Otherwise it will execute no matter what and give you an array out of bounds error or the you'll get an indentation formatting error. 否则它将执行任何操作,并给您一个数组超出范围的错误,否则您将获得缩进格式错误。

Testing string equality 测试字符串相等

Rather than use is str("[string]") simply use == . 不是使用is str("[string]")而是使用== Don't try to over-complicate things. 不要试图使事情复杂化。

Strings vs. Numbers 字符串与数字

In order to do math, you'll have to convert your strings to numbers. 为了进行数学运算,您必须将字符串转换为数字。 You can do that using something like int("5") which is equal to 5 (integer). 您可以使用等于5 (整数)的int("5")方法来实现。

Example Code 范例程式码

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

Assuming you are using a modern Python, input is actually the correct function to use (there is no raw_input in 3.x, and input is always a string). 假设您使用的是现代Python,则输入实际上是要使用的正确函数(3.x中没有raw_input,输入始终是字符串)。 But, as mentioned, there are other problems. 但是,如上所述,还有其他问题。

Here's a version with some corrections. 这是经过更正的版本。

# 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!")

If you wanted division to have a more school book response, with a quotient and remainder, then instead of p1 / p2, you should use divmod(p1, p2) and parse out the two parts in your printed response. 如果希望除法运算得到除以商和余数的更多教科书,则应使用divmod(p1,p2)代替p1 / p2,并在打印的响应中解析出这两个部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM