5.4. Writing interactive programs
Table of Contents
What Makes a Program “Interactive”?
A program is interactive when it reacts to the user:
- It asks questions.
- It waits for input.
- It decides what to do based on that input.
- It gives feedback and often asks again.
In this chapter, you’ll combine input and output with simple logic to create small, conversational programs.
You already know how to:
- Get input with
input() - Convert input to numbers
- Print results with
print()
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:
- Greet the user.
- Ask for some information.
- Process that information.
- Show a result.
- Optionally repeat or ask something else.
In pseudocode, that looks like:
- Say hello
- Ask a question
- Wait for the answer
- Do something with the answer
- 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:
- Use blank
print()to add a blank line for readability. - Store each answer in a variable with a clear name.
- Convert to numbers only when needed.
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:
- Ask a question
- Check the answer
- Respond differently depending on what they typed
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:
- Step-by-step interaction: each question depends on earlier answers.
- Branching: different paths depending on
drink.
Handling Simple Input Errors
Real users don’t always type what you expect. For interactive programs, it’s good practice to:
- Warn the user when something is unexpected.
- Ask again, or choose a default behavior.
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:
- Show clear numbered options.
- Ask for the choice.
- Use
if/elif/elseto run the correct section of code. - Use the same pattern for simple “text menus” in many programs.
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:
- Intro message: what the program does.
- Ask inputs: one or more
input()calls. - Convert/process: turn text into numbers or make decisions.
- 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:
- Repeat questions until the user is done.
- Validate input more carefully.
- Build more complex interactive menus and games.
For now, practice by writing small programs that:
- Ask at least two questions.
- Use the answers in some calculation or decision.
- Print a meaningful, friendly result.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!