Home » Python Programming » Python Programming – Comments and Concatenation

Python Programming – Comments and Concatenation

Comments

We covered the use of the hashtag in regards to commenting out individual lines of code in our Python programs.

 

comment-example1

The recent example of last week, we see our initial comments to identify the program, name of the programmer and date the program was written.

# While Loop Demonstration
# 3 year old why with count
# Matt Cole
# 9.22.16

I am seeing some inquire if there is a cleaner way to comment out sections of the code. This largely depends on the editor we are using. Up to last week, we have been using the provided GUI, via Python shell. Last week, we downloaded PyCharm Community Edition.

My comment is keep it simple. Do not comment out sections of code, and keep to the working hashtag.

 

 

Concatenation

Let’s look at a quick program regarding Print with Strings and Numbers.

combininginprint1

We see our comments in red. I want you to write the above code in your Python Idle, or PyCharm. Notice how the two out fine. We use the plus sign. Recall this is concatenating the two strings together, while also adding 3 and 6.

Concatenation is defined as “the action of linking things together in a series.”

In the above example, we are concatenating “The test is due ” with “in nine days”.  This is done with the plus sign.

combininginprint2png

We now see the same code, with the print statement “The test is due” + “in ” + 9 + “days”.  We would think this would work, but there is a problem. Python will only properly concatenate with the plus sign if it’s using all String.

Run this code again to see the results. Did you get the error, “TypeError: Can’t convert ‘int’ object to str implicitly”?

Python is confused for you using both String and numeric values. If we are combining both String and a number in our Print command, we will need to replace the plus sign with the comma.

combininginprint3

Notice the change in our program above. We replaced the plus with the comma. I want you to run it again and see if it now works. Interesting isn’t it.

 

 

 


Leave a comment

Your email address will not be published. Required fields are marked *