2014-12-07 71 views
-1

我的代码的elif语句中出现无效的sytnax错误。我究竟做错了什么?Python 3程序中的Elif语法错误

# define the functions for each math operation 
# 
def add (a, b) : 

    return a + b 

def subtract (a, b) : 

    return a - b 

def multiply (a, b) : 

    return a * b 

def divide (a, b) : 

    return a/b 

def remainder (a, b) : 

    return a % b 

def welcome_message (first_name) : 
    print ("Hi ", first_name, " " ". Welcome to Project 3!") 

welcome_message("Prof. Shah") 

loop = 1 

while loop ==1: 
    print ("Select operation.") 
    print ("1. Add") 
    print ("2. Subtract") 
    print ("3. Multiply") 
    print ("4. Divide") 
    print ("5. Remainder") 
    choice = input("Enter choice :") 
    num1 = int(input |"Please enter your first number: ") 
    num2 = int(input |"Please enter your second number: ") 

    if choice == '1' : 
       print(num1, "+", num2, "=", add (num1,num2) 
     elif choice == '2' : 
       print(num1, "-", num2, "=", subtract (num1,num2) 
     elif choice == '3' : 
       print(num1, "*", num2, "=", multiply (num1,num2) 
     elif choice == '4' : 
       print(num1, "/", num2, "=", divide (num1,num2) 
     elif choice == '5' : 
       print(num1, "%", num2, "=", remainder (num1,num2) 
+2

你知道你可以['从运营商导入添加,子,div,mul,mod'](https://docs.python.org/3/library/operator.html),对吧? – jonrsharpe 2014-12-07 20:34:44

+0

我对Python相当陌生,所以我仍然是一个正在进行的工作! LOL – CherylR 2014-12-07 20:59:21

回答

2
if choice == '1' : 
    print(num1, "+", num2, "=", add(num1,num2)) 
elif choice == '2' : 
    print(num1, "-", num2, "=", subtract(num1,num2)) 
... 

您的缩进,似乎被关闭了,你人失踪在每个print语句结束一个右括号。

+0

Got it!谢谢Haleemur。现在,当我尝试运行该程序时,出现以下错误:Traceback(最近调用最后一次): 文件“/ Users/cherylragin/Desktop/Intro to Interactive Design/Week 4 Assignments/Project3_copy_3_yes.py”,第38行, num1 = int(输入|“请输入您的第一个数字:”) TypeError:不受支持的操作数类型为|:'builtin_function_or_method'和'str' – CherylR 2014-12-07 20:55:02

+0

问题在于以下两行:'num1 = int(输入|“请输入您的第一个数字:”)'和'num2 = int(输入|“请输入您的第二个数字:”)'。试着自己解决它,不应该太难,如果你不能,请在你的尝试后在SO上发帖。祝你好运! – 2014-12-07 21:04:09

+0

是的......我明白了:我进入了|错误中的符号。当我做出更正时,程序运行了,但是我无法计算它。 – CherylR 2014-12-07 21:10:49

0
if choice == '1' : 
       print(num1, "+", num2, "=", add (num1,num2) 
     elif choice == '2' : 
       print(num1, "-", num2, "=", subtract (num1,num2) 
     elif choice == '3' : 
       print(num1, "*", num2, "=", multiply (num1,num2) 
     elif choice == '4' : 
       print(num1, "/", num2, "=", divide (num1,num2) 
     elif choice == '5' : 
       print(num1, "%", num2, "=", remainder (num1,num2) 

问题在这里。如果“if”块将要处理,那么你必须先从if开始,然后elif。像:

if choice == '1' : 
       print(num1, "+", num2, "=", add (num1,num2) 
elif choice == '2' : 
       print(num1, "-", num2, "=", subtract (num1,num2) 
elif choice == '3' : 
       print(num1, "*", num2, "=", multiply (num1,num2) 
elif choice == '4' : 
       print(num1, "/", num2, "=", divide (num1,num2) 
elif choice == '5' : 
       print(num1, "%", num2, "=", remainder (num1,num2)