2015-10-05 129 views
-2

我在一個初學者編程類中,我應該讓這段代碼工作,我已經按照書的內容一遍又一遍地輸入它, m得到一個無效的語法錯誤,並在Python空閒是高清def總和(num1,num2) 我已經看遍了,在書中,在線,還沒有找到答案,爲什麼它給了我一個錯誤。def sum(num1,num2)上的Python語法錯誤

#this program uses the return value of a function 

def main(): 
    #Get the user's age 
    first_age = int(input('Enter your age: ')) 

    #Get the user's best friend's age. 
    second_age = int(input("Enter your best friend's age: ")) 

    #Get the sum of both ages 
    total = sum(first_age, second_age) 

    #Display the total age 
    print('Together you are', total, 'years old.') 

#the sum function accepts two numeric arguments and 
# return the sum of those arguments. 
def sum(num1, num2): 
    result = num1 + num2 
    return result 

#Call the main function 

main() 

SyntaxError: invalid syntax 
+1

我只是複製粘貼到我的編輯器,它運行成功。 – idjaw

+0

我也給我的課程發了電子郵件,我收到的一封回覆說他們複製並粘貼了代碼,並且完全適合他們。我很沮喪,不明白爲什麼我得到一個錯誤 – user3539642

+3

你可以用確切的錯誤信息更新你的文章嗎?整個消息將有所幫助。 – idjaw

回答

0

您的代碼正在運行。你有像下面那樣的縮進嗎?我必須修復它才能使它工作。

def main(): 
    #Get the user's age 
    first_age = int(input('Enter your age: ')) 

    #Get the user's best friend's age. 
    second_age = int(input("Enter your best friend's age: ")) 

    #Get the sum of both ages 
    total = sum(first_age, second_age) 

    #Display the total age 
    print('Together you are', total, 'years old.') 

#the sum function accepts two numeric arguments and 
# return the sum of those arguments. 
def sum(num1, num2): 
    result = num1 + num2 
    return result 

#Call the main function 

main() 
+0

那一個適合我... 上週我有這種類型的任務,沒有問題,本週,無論我什麼都沒有工作。 謝謝! – user3539642

+0

@ user3539642你一個歡迎。如果你喜歡它,請注意Python中的縮進。也許你會更喜歡另一個IDE,比如pycharm社區版。它免費且非常擅長檢查錯誤。 – LetzerWille