0

I downloaded python 3.3. I am just learning python and wanted to try some of it out with the actual IDE. I want to print the date and time. It says syntax error when I type in print _ . Please check if there is something wrong with the code or syntax :

>>> from datetime import datetime
>>> now = datetime.now()
>>> print now
SyntaxError: invalid syntax


>>> from datetime import datetime

>>> current_year = now.year

>>> current_month = now.month

>>> current_day = now.day

>>> print now.month

SyntaxError: invalid syntax

>>> print now.day

SyntaxError: invalid syntax

>>> print now.year

SyntaxError: invalid syntax

2 Answers 2

4

print is a function in Python 3.

 >>> print(now.year)
Sign up to request clarification or add additional context in comments.

Comments

2

in python 2.x you used print like this

print "hi"

in python 3.x the print statement was upgraded to a function to allow it to do more things and behave more predictably, like this

print("hi")

Or more specifically, in your case: print(now.year)

With the new print function you can do all sorts of things like specifying the terminating character, or printing straight to a file

print("hi" end = ",")
print("add this to that file", file=my_file)

You can also do things that you couldn't have done with the old statment, such as

[print(x) for x in range(10)]

3 Comments

Instead of [print(x) for x in range(10)], I prefer print(*range(10), sep='\n'), which also can't be done with the old print statement. Iterables, generators, and sequences are all unpacked similarly (which is problematic when the iterator or generator doesn't terminate, but that's a different issue), so this isn't much different from the list comprehension, but I've always disliked using list comprehensions for the side effects rather than for the list, and it also only calls print() once and reduces the number of times output is produced, which can increase efficiency in some cases.
@JAB I agree that doing that with a list comprehension is actually LESS efficient, but its just to show that it can go places the old one can't, if you have a better example let me know. I tried yours and it doesn't run :(
What version of Python? It works just fine in Python 3.2, but I don't have 3.3 available to test with at the moment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.