0%

Chapter 3 · practice

Talking with Your Program

Your Program Can Ask Questions

Until now, your programs have worked with values written directly in the code. They produce the same result each time unless you edit them.

Python’s input() lets a running program ask the person at the keyboard for a .

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

This program does not finish immediately. It pauses at input() and waits for an answer.

Run your first interactive program

Press Run in the playground. The program’s will show:

What is your name?

Click in the terminal if necessary, type your name, and press Enter. Python stores what you typed in the name, then continues to the next instruction.

The terminal echoes your answer as you type. That is normal. It lets you see what you entered.

If the program appears to be doing nothing, look for the cursor in the terminal. It may simply be waiting for your answer. You can stop a program that is waiting, then run it again.

Taking input() apart

Look closely at the first instruction:

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

Python handles it in this order:

  1. Call input().

  2. Display the prompt between the parentheses.

  3. Wait until the person an answer and presses Enter.

  4. Produce that answer as a value.

  5. the value to name.

The space before the closing quotation mark in the prompt is intentional. It leaves a little room between the question and the typed answer.

Turn the answer into a greeting

The starter program currently prints the name by itself. Replace the second instruction with an so it prints a friendly greeting.

If the person enters Ada, the final line should be:

Hello, Ada!

Use the variable name. Do not write a particular person’s name into the greeting.

Run the program and try your own name. When it works, press Submit.

What happens during Submit

Your own answer is useful while you experiment. During Submit, Python Land runs the program again with a private test answer. This makes the exercise fair and repeatable without requiring everyone to type the same name.

Your code should therefore work with whatever answer input() returns. That is the real goal of an interactive program.

If your plan includes Guided, you can ask Monty:

Trace my program from the question to the greeting. Explain where the typed answer is stored without rewriting my code.

Task

Replace the final print instruction with an that greets the name returned by input().

If the answer is Ada, the final line should be:

Hello, Ada!

Run the program, type an answer in the , and press Enter. Then submit your code.