Kahibaro
Discord Login Register

Writing interactive programs

What Makes a Program “Interactive”?

A program is interactive when it reacts to the user:

In this chapter, you’ll combine input and output with simple logic to create small, conversational programs.

You already know how to:

Now you’ll learn how to structure these pieces into a smooth interaction.

Basic Structure of an Interactive Program

Most simple interactive programs follow this pattern:

  1. Greet the user.
  2. Ask for some information.
  3. Process that information.
  4. Show a result.
  5. Optionally repeat or ask something else.

In pseudocode, that looks like:

  1. Say hello
  2. Ask a question
  3. Wait for the answer
  4. Do something with the answer
  5. Show a message

In Python:

print("Welcome to the program!")
name = input("What is your name? ")
age_text = input("How old are you? ")
age = int(age_text)  # process/convert
print("Nice to meet you,", name)
print("You are", age, "years old.")

The important idea: input → processing → output.

Asking Multiple Questions

Interactive programs rarely ask just one question. You can ask one after another and reuse previous answers.

print("Welcome to the trip planner!")
name = input("What is your name? ")
destination = input("Where would you like to travel? ")
days_text = input("How many days will you stay there? ")
days = int(days_text)
print()
print("Trip summary:")
print("Traveler:", name)
print("Destination:", destination)
print("Duration:", days, "days")

Notes:

Making Decisions Based on Input

Interactivity becomes more interesting when the program reacts differently to different answers. Here’s a simple example of using if with input:

color = input("What is your favorite color? ")
if color == "blue":
    print("Blue is calming!")
elif color == "red":
    print("Red is energetic!")
else:
    print("Nice choice! I like", color, "too.")

Here, the user’s answer changes the program’s response. You’ll learn if, elif and else in more detail in the conditions chapter; here the key idea is:

Building a Simple Question–Answer Flow

You can chain several questions and decisions to create a mini “conversation”.

print("Welcome to the coffee machine!")
name = input("What is your name? ")
print("Hello,", name)
drink = input("Do you want coffee or tea? ")
if drink == "coffee":
    size = input("Small, medium, or large? ")
    print("Preparing a", size, "coffee for you...")
elif drink == "tea":
    kind = input("Green or black tea? ")
    print("Brewing some", kind, "tea for you...")
else:
    print("Sorry, I only have coffee or tea.")

This example shows:

Handling Simple Input Errors

Real users don’t always type what you expect. For interactive programs, it’s good practice to:

Here is a basic approach without loops (you’ll do this better once you learn loops):

age_text = input("Enter your age: ")
if age_text.isdigit():
    age = int(age_text)
    print("In 10 years, you will be", age + 10)
else:
    print("That doesn't look like a number.")

str.isdigit() returns True if the string contains only digits like "123".

This is a very simple form of “defensive” interaction: check the input before using it.

Simple Menus

Many interactive programs present a menu of options. For now, you can implement a menu with input and conditions.

print("Calculator")
print("1) Add two numbers")
print("2) Multiply two numbers")
choice = input("Choose an option (1 or 2): ")
if choice == "1":
    a = float(input("First number: "))
    b = float(input("Second number: "))
    print("Result:", a + b)
elif choice == "2":
    a = float(input("First number: "))
    b = float(input("Second number: "))
    print("Result:", a * b)
else:
    print("Invalid choice.")

Key ideas:

Keeping the Conversation Clear

Good interactive programs are easy to understand. Some practical tips:

1. Use Clear Prompts

Bad:

x = input("?> ")

Better:

age_text = input("How old are you? ")

Prompts should tell the user exactly what to type.

2. Show Examples in the Prompt

This helps the user know the expected format:

color = input("Choose a color (red/green/blue): ")

3. Echo Important Information Back

Confirm what the user entered:

name = input("What is your name? ")
print("You entered:", name)

Useful when inputs are long or important.

4. Use Blank Lines to Group Messages

It’s easier to read:

print("Welcome to the registration form!")
print()
name = input("Name: ")
email = input("Email: ")
print()
print("Thank you for registering,", name)

Combining Input, Processing, and Output: Mini Examples

Here are a few complete interactive snippets you can type and run.

Age in Months Calculator

print("Age in months calculator")
age_years_text = input("How old are you (in years)? ")
if age_years_text.isdigit():
    age_years = int(age_years_text)
    age_months = age_years * 12
    print("You are about", age_months, "months old.")
else:
    print("Please enter your age as a number, like 20.")

Simple Greeting Customizer

print("Custom greeting")
name = input("What is your name? ")
mood = input("How are you today? ")
print()
print("Hello", name + "!")
print("I'm glad to hear you are", mood + ".")

Temperature Converter (Celsius to Fahrenheit)

Using the formula
$$
F = C \times \frac{9}{5} + 32
$$

print("Celsius to Fahrenheit converter")
celsius_text = input("Enter temperature in Celsius: ")
celsius = float(celsius_text)
fahrenheit = celsius * 9 / 5 + 32
print("That is", fahrenheit, "degrees Fahrenheit.")

Simple Pattern for Interactive Programs

You can use this general pattern when you start a new interactive script:

  1. Intro message: what the program does.
  2. Ask inputs: one or more input() calls.
  3. Convert/process: turn text into numbers or make decisions.
  4. Output result: print() answers, summaries, or next steps.

Template:

print("Short description of what the program does")
# 1. Ask for input
user_input1 = input("Question 1: ")
user_input2 = input("Question 2: ")
# 2. Convert/process
# (convert to numbers, do calculations, make decisions, etc.)
# 3. Output results
print("Some result using", user_input1, "and", user_input2)

As you learn conditions and loops in later chapters, you’ll be able to:

For now, practice by writing small programs that:

Views: 19

Comments

Please login to add a comment.

Don't have an account? Register now!