2013-07-29 104 views
1

我想創建一個程序使用python,它可以幫助我們告訴時間,日期和年份,但是我面臨一些問題。Python(3.3)無效的語法錯誤

from datetime import datetime 
now = datetime.now() 
current_day = now.day 
print current_day 
current_month = now.month 
print current_month 
current_year = now.year 
print current_year 
input(press enter to exit) 

我每次運行它,它說無效的語法,顯然它的東西與第三line.I'm不知道該怎麼辦呢!誰能幫我?

+0

如果這是你實際的代碼,那麼你需要周圍的輸入和打印引號是一個函數...你可以在'='符號周圍加空格嗎? – Ben

+0

我拿走了輸入,因爲它說它導致了一個錯誤,並且一旦它打開就會一直關閉。你能說明腳本應該是什麼樣子嗎?謝謝! – Fin

回答

5

的Python 3不使用相同的print語法的Python 2 print在Python 3是一個函數,所以你需要print(current_day)

+0

我還需要做第2行嗎? – Fin

+0

第2行,你的意思是'現在= datetime.now()'?你爲什麼不需要那個? –

2

在Python 3.x中,你所要做的print(current_day)print不再是2.x中的關鍵字,而是內置的關鍵字。

這是你的腳本應該如何在Python 3.X:

from datetime import datetime 
now=datetime.now() 
current_day=now.day 
print(current_day) 
current_month=now.month 
print(current_month) 
current_year=now.year 
print(current_year) 
# You have to make "press enter to exit" a string. 
# Otherwise, the script will blow up because "press" isn't defined. 
input("press enter to exit") 
2

Python 3裏沒有印刷者!它具有打印功能:您需要打印(smthn)。 也input("press enter to exit")

+0

什麼是輸入錯誤(「按Enter鍵退出」)? – Fin

+0

錯過了你的問題中的引號 – eri

1

正如其他人已經提到你需要使用打印功能,而不是Python3中的打印語句。您還可以進一步簡化代碼:

from datetime import datetime 

now = datetime.now() 
print("{0.day}-{0.month}-{0.year}".format(now)) 
input('Press any key to exit') 

你可以找到更多關於print function和文檔中的format syntax

0

起初是python 2.7的代碼。 這是在python3代碼的完整修復

from datetime import datetime 
now = datetime.now() 
current_day = now.day 
print(current_day) 
current_month = now.month 
print(current_month) 
current_year = now.year 
print(current_year) 

input("Press Enter to exit") 

而對於Python 2.7版,這是一個速戰速決..

from datetime import datetime 
now = datetime.now() 
current_day = now.day 
print current_day 
current_month = now.month 
print current_month 
current_year = now.year 
print current_year 
try: 
    input("press enter to exit") 
except SyntaxError: 
    pass