CODING / BEGINNER

Your First Python Program: From Input to Output

A first program should be small enough to understand and useful enough to change. A personalised greeting is a good place to begin.

Start with one clear task

The task is simple: ask for a name, store the reply, and display a greeting. Read this code before running it:

name = input("What is your name? ")
print("Hello,", name)
print("Welcome to Python!")

input() displays a prompt and returns the text entered by the user. The variable name stores that text. print() displays output. The quotation marks identify text written directly in the program.

Predict, run, explain

First, predict the output if the user enters Asha. Then run the program and compare the result with your prediction. Finally, explain each line aloud or to a partner. This makes it easier to notice whether you understand the code or have only copied it.

Try a fictional name, then a name with a space. What changes? The program stores the whole line of text that the user enters.

Make three changes

  1. Change the welcome message.
  2. Ask for a favourite subject and display it in a second sentence.
  3. Add a question asking for a favourite number.

At this stage, a number entered through input() is still text. If you want to calculate with it, convert it first using int() for an integer or float() for a decimal. Entering unsuitable text during conversion produces an error.

A useful check before moving on

Can you identify the input, the variable, and the output? Can you explain why name has no quotation marks when it is used as a variable? If something fails, check spelling, matching quotation marks, and parentheses one at a time.

Next, try the rectangle exercise on the Resources page. It adds arithmetic to the same input–process–output pattern.