其他语句语法错误(简单计算器)

时间:2017-03-15 17:02:43

标签: python if-statement

我正在尝试编写一个小计算器代码,因为我正在学习python。我的问题是,它始终在else语句中输出语法错误,因为我还是初学者,我不知道为什么。 :( Code of my calculator

2 个答案:

答案 0 :(得分:0)

您错过了colon : with else

应为else: {your logic}

Here's an example

更新:实际上你确实有结肠,但有条件。这应该是elif而不是else

将上次else更改为elif,如果没有默认检查,则您不一定需要其他内容。

答案 1 :(得分:0)

您的代码实际上存在一些问题。

  1. 您不能在字符串和整数等之间进行转换。"4" + "5"不是9,而是"45",因为它正在组合两个字符串。但如果你做int("4") + int("5")那么你会得到9.

  2. 在做else语句时,没有条件。

  3. 所以,基本的 if,elif,else 将是:

    a = "yay"
    if a == "yay":
        print("a likes you")
    elif a == "no":
        print("a doesn't like you")
    else:
        print("a doesn't want to respond")
    

    Python 2.7

    print ("Welcome to your friendly Python calculator.  Use + for addition and - for substraction")
    print ("This code uses period (.) for decmimals")
    
    first = "Please enter your first number "
    second = "Please enter your second number "
    
    operator = raw_input("Please choose an operation (+ or -) ")
    if operator == "+":
        num1 = input(first)
        num2 = input(second)
        print ("Result: " + str(num1 + num2))
    elif operator == "-":
        num1 = input(first)
        num2 = input(second)
        print ("Result: " + str(num1 - num2))
    else:
        print("You didn't enter a valid operator.")
    

    Python 3.6

    print ("Welcome to your friendly Python calculator.  Use + for addition and - for substraction")
    print ("This code uses period (.) for decmimals")
    
    first = "Please enter your first number "
    second = "Please enter your second number "
    
    operator = input("Please choose an operation (+ or -) ")
    if operator == "+":
        num1 = int(input(first))
        num2 = int(input(second))
        print ("Result: " + str(num1 + num2))
    elif operator == "-":
        num1 = int(input(first))
        num2 = int(input(second))
        print ("Result: " + str(num1 - num2))
    else:
        print("You didn't enter a valid operator.")