1

Unable to understand this Python code

 2 years ago
source link: https://www.codesd.com/item/unable-to-understand-this-python-code.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Unable to understand this Python code

advertisements

I was reading 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 couldn't understand why these brackets were being used for the print commands and so I removed 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 those brackets I am getting the exact same results, so I am not sure which one is correct or whether I should use those brackets at all. Is it really necessary to use those brackets?

One more thing. when I use the brackets then the +person+ gives the result as Happy Birthday, dear Andre. but when I use ,person, then it gives the result as <'Happy Birthday,dear ',' 'Andre','.'>

I am unable to understand these differences in the results. Could you shed some light on this?


Is it really necessary to use those brackets?

In Python 2.x, print is a statement, and the brackets are optional.

In Python 3.x, print() is a function, and the brackets are mandatory.

It is considered good practice to use brackets even in Python 2.x, to ease eventual transition to Python 3.x.

I am unable to understand these differences in the results. Could you shed some light on this?

Here is what happens when you print several comma-separated things in Python 2.x:

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

The above is interpreted as the print statement followed by a single argument, which is a tuple. The tuple is rendered with parentheses and commas.

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

The above is interpreted as the print statement followed by three arguments. Each argument is printed out separately, with spaces between them.

Neither version is great as far as compatibility with Python 3 is concerned: the first version is rendered differently, and the second is simply not valid Python 3 code.

With this in mind, I recommend that you stick with:

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

This produces exactly the same results in both Python 2.x and Python 3.x.

Tags python

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK