Making Decisions

Talking with a Program


Learning Objectives

  • You can display output using print(...).
  • You can read user input using input(...) and store the result.
  • You understand a string as text represented as a value in Python.
  • You can build readable output using f-strings.
  • You can apply simple string operations such as .strip() and .lower() when appropriate.

Programs become much more interesting when they can communicate with a user. In this chapter, you will write programs that show information, ask questions, remember the answers, and build new text from those answers.

Printing Output

You used print(...) in the previous chapter while learning how to run and revise a program. Now the focus moves from the workflow to the values a program displays. The print(...) function displays a value as output.

print("Hello!")

You can call print several times:

print("Welcome to the course.")
print("We are writing Python now.")

Each call produces a line of output.

You can also print an empty line:

print("Before")
print()
print("After")

This is useful when you want output to be easier to read.

Welcome card

0 / 10 points

Write a program that outputs exactly the following text:

********
Welcome!
********

Strings Hold Text

Text values in Python are called strings. A string is written between quotation marks:

"hello"
"Ada Lovelace"
"42"
""

The last example is an empty string: text containing zero characters.

The value "42" is also a string. It contains digit characters, but it is still text. Later, you will see why the distinction between the string "42" and the number 42 matters.

Both single and double quotation marks can be used:

'hello'
"hello"

In this course, double quotation marks are used most often for consistency.

Strings Now and Later

Strings are important enough that you will return to them several times during the course. In this part, the goal is deliberately small: strings are text values that your program can receive, store, compare, clean up, and print.

You do not need to know yet how to access individual characters, take slices of text, loop through a string, or explain why strings cannot be changed in place.


Asking for Input

The input(...) function shows a prompt and waits for the user to type something.

No files opened Select a file to edit

If you run the program, type Ada, and press Enter, Python receives the text Ada. Nothing is stored yet, so the program cannot use the answer later. The program simply ends after the user presses Enter.

The output window shows the prompt and the text you typed. The text you typed is shown in blue, but it is not program output. It is the user’s input. The program does not print your answer; it only receives it.

Usually, you want to remember the answer. A variable is a name that lets the program refer to a value later. Read the following as “store the result of input(...) in a variable named name”:

name = input("What is your name? ")

Now the program can use name later:

No files opened Select a file to edit

If the user types Ada, the interactive terminal transcript normally looks like this:

What is your name? Ada
Ada

The first line contains the prompt from input(...) followed by the text the user typed. The second line is program output produced by print(name).

The variable is what lets information move from one line of the program to another.

This is enough about variables for the interactive programs in this chapter. Chapter 4 examines assignment, reassignment, and program state more carefully.

The same conversation can be described in plain language first. Arrange the steps so the generated program reads a name, thanks the user, and then prints the stored name.

Reading and printing with natural-language programming

0 / 5 points

Drag and drop the natural-language programming steps to the area marked with “Program”. Arrange the steps so the program reads a name from the user, prints “Thank you!”, and then prints the stored name.

Building Text with f-strings

A common task is combining fixed text with a variable value. Python’s f-strings make this straightforward.

name = "Ada"
print(f"Hello, {name}!")

The f before the opening quotation mark tells Python that expressions inside {...} should be evaluated and inserted into the string.

If name contains Ada, the output is:

Hello, Ada!

The same works directly with user input:

No files opened Select a file to edit

You will use f-strings throughout the course. They are usually the clearest way to construct messages containing values.

Personalized output

0 / 10 points

Complete the program so it asks for a name and a hometown, then prints one sentence containing both entered values.

Use an f-string for the final output line.

If the user enters Ada and London, the final output line must be:

Ada is from London.

A Few Useful String Operations

Strings have operations associated with them. These are called methods. You do not need to understand methods formally yet; that arrives much later when you learn about objects. For now, you only need a few methods that make user input easier to work with.

Removing Extra Whitespace

Users sometimes type spaces before or after an answer. The method .strip() removes whitespace from both ends:

name = input("Name: ").strip()

If the user types spaces around Ada, the stored value becomes simply Ada.

Changing Letter Case

The method .lower() produces a lowercase version of a string:

answer = input("Continue? ").strip().lower()

If the user types YES, the value after .lower() is yes.

These operations will become useful when you compare user input in the decisions chapter.

Objects Hiding in Plain Sight

Strings are actually objects in Python. An object is a value that has operations associated with it. The operations are called methods. You will learn about objects and methods in detail later in the course.

For now, it is enough to read name.strip() as “produce a cleaned-up version of the string stored in name” and answer.lower() as “produce a lowercase version of the string stored in answer.”


Normalize an answer

0 / 10 points

Complete the program so it stores a cleaned, lowercase version of the user’s answer and prints it.

Use both .strip() and .lower(). The inputs yes, YES, and Yes must all produce output ending with:

yes

A Complete Interactive Program

Here is a small program using everything from the chapter:

No files opened Select a file to edit

Before running it, work through the program from top to bottom with these imaginary inputs:

Ada
London
tea

Ask yourself:

  • What values are stored after the three input lines?
  • What does the first final print produce?
  • What does the second final print produce?

Then run it and compare.

Change a profile program with intent

0 / 15 points

Make three deliberate changes to the profile program:

  1. Change the City: question to Hometown:.
  2. After the favorite-food question, add an input stored in language with the prompt Favorite programming language: .
  3. Include the favorite programming language in the final output.

Before running the changed program, predict what one example run will display. Then run it and compare the result with your prediction. The prediction is a working step and is not submitted separately.

Common Pitfalls

A few mistakes are common at this stage:

  • forgetting quotation marks around literal text;
  • using a variable name before assigning it;
  • misspelling a variable name in one place;
  • forgetting the f before a string containing {name};
  • adding extra quotation marks around a variable inside an f-string, causing the variable name itself to be printed as text.

Compare:

print("Hello, {name}")

with:

print(f"Hello, {name}")

The first prints the braces and word name literally. The second inserts the variable’s value.

Find the greeting problems

0 / 10 points

The program should ask for a name and print a personalized greeting, but its output line contains two mistakes.

Correct the program so it uses the assigned variable and an f-string. If the user enters Ada, the output must end with:

Hello, Ada!

Check Your Understanding

  1. What kind of value does input(...) return?
  2. What does the f do in an f-string?
  3. What is the purpose of .strip()?
  4. Why might .lower() be useful before comparing user input?
  5. What is the difference between a literal string such as "name" and a variable named name?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0