Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

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? ")
  2. name = input ("What is your name? ")
  3. 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)
  2. print("grand" "mother")
  3. 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. /
  2. \
  3. |
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.

Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.