PDA

View Full Version : Basic Python Programming Question



Cunnilingus
January 30th, 2010, 04:44 PM
Why does the program

length = 5
width = 2

area = length * width
print('Area is', area)
print('Perimeter is', 2 * (length + width))

give an output of

('Area is', 10)
('Perimeter is', 14)

Zugzwang
January 30th, 2010, 04:52 PM
Because you are printing tuples. The print command can be used without parentheses.

CptPicard
January 30th, 2010, 05:31 PM
That is, print is a statement, not a function. This will change in Python 3 though.

Cunnilingus
January 30th, 2010, 06:13 PM
Got it. Thanks!

nvteighen
January 30th, 2010, 07:56 PM
You can use it with parentheses, but instead of commas, you have to use + and be sure everything is a string... or convert it to string using str()



print("A" + str(4) + "b")


Anyway, it's nicer to use printf-like control strings or the new format() method (only since Python 2.6):


print "A%d %s" % (4, "b")
# or Python 2.6+
print "A{0} {1}".format(4, "b")