Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: correct usage of triple quotes

Tags:

python

My code doesn't run if I use triple quotes before an else statement:

def do_something(test_option=False):
    """
    function to do something
    :param test_option: bool
    :return: None
    """
    
    '''
    Testing
    '''
    
    if test_option==True:
        print("testing")
    
    '''
    Visualization
    '''
    
    else:
        # do thing

I get a red squiggly under my else. Why is this?

I understand that ''' can also be used for function annotation. Is it not supposed to be used anywhere else?

Suggestions for alternative ways to highlight organization of code? (My IDE literally highlights ''' in yellow which I have been using organize different sections of my code.)

like image 329
Christina Zhou Avatar asked Feb 19 '26 18:02

Christina Zhou


2 Answers

Triple quotes represent a string literal, not a comment, so by placing the Visualization outside the if block with the same level of indentation you are effectively ending the if statement, so the following else clause becomes invalid. Indent Visualization inside the if block to avoid such an error.

like image 66
blhsing Avatar answered Feb 22 '26 07:02

blhsing


Only use triple-quotes for docstrings (or else other multiline strings, which are rare).

Don't try to use them for comments. Use # your comment goes here...

def do_something(test_option=False):
    """
    function to do something
    :param test_option: bool
    :return: None
    """

    # Testing
    if test_option==True:
        print("testing")

    # Visualization
    else:
        # do thing

(Note by the way that comments are more compact)

like image 37
smci Avatar answered Feb 22 '26 06:02

smci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!