Python Small Things – I

Just title written in three words to be short and to get attention, but I think most proper title can be "Python Small Things But Important". We will discuss about:

  • Comments
  • Quotation

Comments

Any line that begins with a hash (i.e. # ) is a comment. 

Example, first line from below is a comment:


# Follow import packages section 

import sys

import random

import pandas


Python interpreter ignores comment lines. The role of the comment is to document the code.

There is no sign to comment multiple lines in Python, thus when many lines need to be commented we need to comment each one. 

Sometime we use comments to make unusable a code line, we think that the line will not be needed as for example we replaced it with something else, but we still need to keep it for a while, thus we comment it, and interpreter will skip it.

Example of multi-line comment and lines commented to become inactive: 


#file1 = open("file1.txt", "r")

#print(file1.readlines())

with open("file1.txt") as file1:

    file_1_data = file1.readlines()

print(file_1_data)


Quotation

All, single quotes → ' , double quotes → "" and triple quotes → """ or ''' are used for assigning values to string variables.


Example: 

var1 = 'sky'

var2 = 'The sky is blue'


but we can use also:

var1 = "sky"

var2 = "The sky is blue"


The idea is that at the beginning and the end of string to use the same quote type.


Triple quotes are used when strings occupy many lines.

Example:

var3a = """Today is a sunny day, no clouds at all 

and the sky is blue"""


#or 


var3b = '''Today is a sunny day, no clouds at all 

and the sky is blue'''


A particular use case for single ' and double "" is when we need to print or have a variable that contain a  word that is quoted. For example we need to have a variable that have like value  Today is a 'sunny' day


If use: 

var4 = "Today is a "sunny" day"

print(var4)

this will give error: 

File "C:\Users\Stefan\app-start\test.py", line 1

var4 = "Today is a "sunny" day"

^^^^^

SyntaxError: invalid syntax


Solution is to use:

var4 = 'Today is a "sunny" day'

print(var4)


that will print indeed:

Today is a "sunny" day


Or something a little bit similar:

var4 = "Today is a 'sunny' day"

print(var4)

which will print:

Today is a 'sunny' day


The rule to quote string inside other string is to do it with different quotes. Means for example if the big string is between single ‘ we can quote inside it using double quote.