简体   繁体   中英

Python: Should I use multiple print statements or “+” for consecutive sentences?

    print("\nINSTRUCTIONS~\nEnter:\n'c' to use a full fledged calculator,")
    print("'a' to add and subtract numbers " +
          "(faster than calculator if you just want to add and subtract),")
    print("'s' to find a number's square root,")
    print("'p' to see powers,")
    print("'n' to arrange numbers in ascending and descending order,")
    print("'f' to calculate factorials,\n'x' to exit the program,")

I currently put a "+" for sentences on the same line, but otherwise make another print statement, I would like to know which would be a better programming practice.

To answer your question, they are essentially the same. It is really a matter of readability, and thus personal preference.

However, there is a more convenient way to do it, which is to use multi line strings . They are delimited by """ , and are essentially strings that are capable of spanning multiple lines.

For example,

print("Hello,
world!")

would throw an error saying EOL while scanning string literal , whereas

print("""Hello,
world!""")

is fine and prints this:

Hello,
World!

as it is supposed to.


Clarification: It is not the same as using the line continuation character( \\ ). That only goes to the next line without breaking the string, to help the programmer read their code. It does not include the newline.

This:

print("Hello,\
world!")

Is not the same as this:

print("""Hello,
world!""")

While it is true they are both valid, they have different results. The former would print:

Hello,world!

While the latter would print

Hello,
world!

EDIT: When using this for a docstring, there is the concern that indentation meant for human readability will interfere with it by adding in extra tabs. Example:

# Less easily readable
def test():
    """Docstring
Docstring"""
    pass

# More easily readable
def otherTest():
    """Docstring
    Docstring"""
    pass

The thing is that these two docstrings produce the exact same result. Python ignores the leading whitespace.


Source: Proper indentation for Python multiline strings

In terms of speed they are equivalent.

text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'

size = 5


def test_multiple_prints():
    for _ in range(size):
        print(text)


def test_single_print():
    big_text = '\n'.join([text for _ in range(size)])
    print(big_text)


%timeit test_multiple_prints()
#1000 loops, best of 3: 702 µs per loop


%timeit test_single_print()
#1000 loops, best of 3: 703 µs per loop

做任何使程序最容易阅读和最容易维护的事情。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM