Unable to understand this Python code

I read about python functions and saw this code:

def happyBirthday(person):
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear " + person + ".")
    print("Happy Birthday to you!")

happyBirthday('Emily')
happyBirthday('Andre')

I could not understand why these brackets are used for print commands, and so I deleted them.

def happyBirthday(person):
    print "Happy Birthday to you!"
    print "Happy Birthday to you!"
    print "Happy Birthday, dear " + person + "."
    print "Happy Birthday to you!")

happyBirthday('Emily')
happyBirthday('Andre')

Even after removing these brackets, I get exactly the same results, so I'm not sure which one is correct or should I use these brackets at all. Is it really necessary to use these brackets?

One more thing. when I use brackets then +person+it gives a result like happy birthday, dear Andre. but when I use ,person,, then it gives a result like "Happy Birthday, dear", "Andre", "." >

I cannot understand these differences in results. Could you shed some light on this?

+3
source share
4 answers

?

Python 2.x, print - , .

Python 3.x, print() , .

Python 2.x, Python 3.x.

. ?

, Python 2.x:

In [1]: print(1,2,3)
(1, 2, 3)

print, , . .

In [2]: print 1,2,3
1 2 3

print, . , .

Python 3: -, Python 3.

:

print("Happy Birthday, dear " + person + ".")

Python 2.x, Python 3.x.

+13

Python2 . Python3

, , , Python3

.

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi",
hi
>>> print("hi",)
('hi',)

vs

Python 3.2.2 (default, Sep  5 2011, 21:17:14) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hi",
  File "<stdin>", line 1
    print "hi",
             ^
SyntaxError: invalid syntax
>>> print("hi",)
hi
+3

, print - Python 2 , ('xxx'),

('xxx')

. , , .

'string' + name + 'string', ther (), . parens, .

, ('x', 'y', 'z'),

('x', 'y', 'z')

is a tuple that is printed as "Happy Birthday, dear," "Andre", "." >

+1
source

try str(person)in print staement

0
source

All Articles