首页 > 解决方案 > Python Synthax 错误:使用 Elifs 的语法无效

问题描述

我正在为学校期末项目设计一个计算器。我对 Python 很陌生,不知道为什么我的 Elifs 有 SyntaxError: invalid syntax。我也很感激打印带有 2 个小数点的浮点数的帮助,因为我非常不确定如何使用它。谢谢!

# This is a calculator that calculates Addition, Subtraction, Division, Multiplication and Powers. 
# It must round all answers to atleast 2 decimal points.

print ("Welcome! Choose what Type of operation you would like, 1: Addition, 2: Subtraction, 3: Multiplication, 4: Division, 5: Powers.")
Choice = int(input("Your Choice ( 1 - 5 ): "))

if Choice <= 0 or Choice > 5:
    print ("Invalid Entry")

elif Choice == 1 or Choice == 2 or Choice == 3 or Choice == 4 or Choice == 5:
    num1 = float(input("Your First Number: "))
    num2 = float(input("Your Second Number: "))


if Choice == 1:
    Addition = num1 + num2
    print ("Your Final Number Is: " + str(round(Addition, 2))

elif Choice == 2:
    Subtraction = num1 - num2
    print ("Your Final Number Is: " + str(round(Subtraction, 2))

elif Choice == 3:
    Multiplication = num1 * num2
    print ("Your Final Number Is: " + str(round(Multiplication, 2))

elif Choice == 4:
    Division = num1 / num2
    print ("Your Final Number Is: " + str(round(Division, 2))

elif Choice == 5:
    Powers =num1 / num2
    print ("Your Final Number Is: " + str(round(Powers, 2))

else:
    print ("Invalid Entry")

标签: python-3.x

解决方案


问题是您的打印报表。在这些中,您打开 print ,(然后打开 str ,(然后打开 round ,(然后关闭 round)并关闭 str ,)但不要关闭 print 语句)。所以你有 3(但只有 2)所以你需要在)打印行的末尾添加以关闭语句。

但是,如果您发现自己像打印报表一样重复您的代码,那么可能有更好的方法来做到这一点。下面只是一个示例,说明如何以更简洁的方式编写它

# This is a calculator that calculates Addition, Subtraction, Division, Multiplication and Powers.
# It must round all answers to atleast 2 decimal points.

print("Welcome! Choose what Type of operation you would like, 1: Addition, 2: Subtraction, 3: Multiplication, 4: Division, 5: Powers.")
Choice = int(input("Your Choice ( 1 - 5 ): "))

if 1 <= Choice <= 5:
    num1 = float(input("Your First Number: "))
    num2 = float(input("Your Second Number: "))
    result = 0
    if Choice == 1:
        result = num1 + num2
    elif Choice == 2:
        result = num1 - num2
    elif Choice == 3:
        result = num1 * num2
    elif Choice == 4:
        result = num1 / num2
    elif Choice == 5:
        result = num1 ** num2
    print("Your Final Number Is: " + str(round(result, 2)))
else:
    print("Invalid Entry")

推荐阅读