Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Engineering LibreTexts

2.7: Formatting Code

( \newcommand{\kernel}{\mathrm{null}\,}\)

Learning Objectives

By the end of this section you should be able to

  • Identify good spacing for expressions and statements.
  • Write multi-line statements using implicit line joining.

Recommended spacing

Most spaces in Python code are ignored when running programs; however, spaces at the start of a line are very important. The following two programs are equivalent:

  • Good spacing: name = input("Enter someone's name: ") place = input("Enter a famous place: ") print(name, "should visit", place + "!")
  • Poor spacing: name=input ("Enter someone's name: " ) place =input("Enter a famous place: ") print( name,"should visit" , place+ "!")

One might argue that missing or extra spaces do not matter. After all, the two programs above run exactly the same way. However, the "poor spacing" version is more difficult to read. Code like name=input and place+ might lead to confusion.

Good programmers write code that is as easy to read as possible. That way, other programmers are more likely to understand the code. To encourage consistency, the Python community has a set of guidelines about where to put spaces and blank lines, what to name variables, how to break up long lines, and other important topics.

Python style guide

PEP 8 is the official style guide for Python. PEP stands for Python Enhancement Proposal. Members of the Python community write PEPs to document best practices and propose new features. The table below is based on guidelines from PEP 8 under the heading Whitespace in Expressions and Statements.

Guideline Example Common Mistakes
Parentheses: no space before or after.

print("Go team!")

print ("Go team!")
print( "Go team!" )

Commas: no space before, one space after.

print("Hello", name)

print("Hello" , name)
print("Hello",name)

Assignment: one space before and after the =.

name = input("Your name? ")

name=input("Your name? ")
name= input("Your name? ")
name =input("Your name? ")

Concatenation: one space before and after the +.

print("Hi", name + "!")

print("Hi", name+"!")
print("Hi", name+ "!")
print("Hi", name +"!")

Arithmetic: use space to show lower precedence.

x**2 + 5*x - 8

x ** 2 + 5 * x - 8
x ** 2+5 * x-8
x**2+5*x-8

Table 2.7 Guidelines for spaces.
Concepts in Practice: Recommended spacing
1.
Which statement is formatted properly?
  1. name = input("What is your name? ")
  • name = input ("What is your name? ")
  • name = input( "What is your name? " )
  • 2.
    Which statement is formatted properly?
    1. name=name+"!"
    2. name = name+"!"
    3. name = name + "!"
    3.
    Which statement is formatted properly?
    1. print("Hello",name)
    2. print("Hello", name)
    3. print("Hello " , name)
    4.
    Which expression is formatted properly?
    1. b**2 - 4*a*c
    2. b ** 2 - 4 * a * c
    3. b**2 - 4*a * c

    Automatic concatenation

    Long strings make Python programs difficult to read. Ex: This program prints the first sentence of the US Declaration of Independence:

    print("The unanimous Declaration of the thirteen united States of America, When in the Course of human events, it becomes necessary for one people to dissolve the political bands which have connected them with another, and to assume among the powers of the earth, the separate and equal station to which the Laws of Nature and of Nature's God entitle them, a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation.")

    PEP 8 recommends that each line of code be less than 80 characters long. That way, programmers won't need to scroll horizontally to read the code. The above program can be rewritten by breaking up the original string:

         print("The unanimous Declaration of the thirteen united States of "
               "America, When in the Course of human events, it becomes "
               "necessary for one people to dissolve the political bands "
               "which have connected them with another, and to assume among "
               "the powers of the earth, the separate and equal station to "
               "which the Laws of Nature and of Nature's God entitle them, a "
               "decent respect to the opinions of mankind requires that they "
               "should declare the causes which impel them to the separation.")

    For convenience, Python automatically concatenates multiple strings. The + operator is not required in this situation.

    Checkpoint: String concatenation
    Concepts in Practice: String literal concatenation
    5.
    Which line prints the word "grandmother"?
    1. print(grandmother)
  • print("grand" "mother")
  • print("grand", "mother")
  • 6.
    What string is equivalent to "Today is" "a holiday"?
    1. 'Today isa holiday'
    2. 'Today is a holiday'
    3. 'Today is" "a holiday'
    7.
    If name is "Ada", what does print("Hello," name) output?
    1. Hello,Ada
    2. Hello, Ada
    3. SyntaxError

    Multi-line statements

    Most statements in a Python program need only one line of code. But occasionally longer statements need to span multiple lines. Python provides two ways to write multi-line statements:

    • Explicit line joining, using \ characters: decl = "The unanimous Declaration of the thirteen united States of " \ "America, When in the Course of human events, it becomes " \ "necessary for one people to dissolve the political bands..."
    • Implicit line joining, using parentheses: decl = ("The unanimous Declaration of the thirteen united States of " "America, When in the Course of human events, it becomes " "necessary for one people to dissolve the political bands...")

    Implicit line joining is more common, since many statements and expressions use parentheses anyway. PEP 8 recommends avoiding the use of explicit line joining whenever possible.

    Concepts in Practice: Multi-line statements
    8.
    Which character is used for explicit line joining?
    1. /
  • \
  • |
  • 9.
    What is the best way to print a very long string?
    1. Break up the string into multiple smaller strings.
      print("..." # first part of string
      "..." # next part of string
      "...")
    2. Print the string using multiple print statements.
      print("...") # first part of string
      print("...") # next part of string
      print("...")
    3. Assign the string to a variable and print the variable.
      text = "..." # the entire string
      print(text)
      
    10.
    Which example consists of two statements?
    1. print("Happy "
      "New Year")
    2. saying = ("Happy "
      "New Year")
    3. saying= "Happy "
      "New Year"
    Try It: Spaced out

    The following code works correctly but is formatted poorly. In particular, the code does not include spaces recommended by PEP 8. Furthermore, two of the lines are about 90 characters long. Reformat the code to follow the guidelines in this section. Be careful not to change the behavior of the code itself.

    Try It: Five quotes

    Write a program that prints the following five quotes (source: BrainyQuote) from Guido van Rossum, the creator of Python. Your program should have exactly five print statements, one for each quote:

        1. "If you're talking about Java in particular, Python is about the best fit you can get amongst all the other languages. Yet the funny thing is, from a language point of view, JavaScript has a lot in common with Python, but it is sort of a restricted subset."
        2. "The second stream of material that is going to come out of this project is a programming environment and a set of programming tools where we really want to focus again on the needs of the newbie. This environment is going to have to be extremely user-friendly."
        3. "I have this hope that there is a better way. Higher-level tools that actually let you see the structure of the software more clearly will be of tremendous value."
        4. "Now, it's my belief that Python is a lot easier than to teach to students programming and teach them C or C++ or Java at the same time because all the details of the languages are so much harder. Other scripting languages really don't work very well there either."
        5. "I would guess that the decision to create a small special purpose language or use an existing general purpose language is one of the toughest decisions that anyone facing the need for a new language must make."

    Notice that all of these lines are longer than 80 characters, and some contain single quote marks. Format the code using multi-line statements and escape sequences as necessary.


    This page titled 2.7: Formatting Code is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.

    Support Center

    How can we help?