Start with a small goal
A first program should do one thing you can understand from beginning to end. This reading list helper asks you for a book title, keeps that answer in a variable, and prints a message. You can type the example in a Python 3 interpreter or save it in a file and run it with Python. The built-in input() function reads a line of text. The built-in print() function displays output.
Write and run the program
title = input("Book to read next: ")
print("Added to your reading list: " + title)Run it and enter a title, such as Growing Together. You should see a sentence containing the title you typed. The word title is a variable: it refers to the text returned by input(). The plus sign joins the fixed message and your answer into one string. If you change the prompt, the program still works because the variable name stays the same.
Make the output more useful
Add a second question and use an f-string to place both answers in a sentence:
title = input("Book to read next: ")
reason = input("Why this book? ")
print(f"Next up: {title}. Reason: {reason}")Here the letters inside braces are variable names. The f before the opening quote tells Python to replace those braces with the current values. Try changing the order in the printed sentence. This is a safe way to experiment with a program you already understand.
Handle an empty answer
What if someone presses Enter without typing a title? Add a simple condition:
title = input("Book to read next: ").strip()
if title:
print(f"Next up: {title}")
else:
print("No title entered yet.")The strip() method removes spaces from the beginning and end of the answer. An empty string makes the else branch run. Indentation matters in Python: the indented line under each branch belongs to that branch. Test a normal title, an empty answer, and a few spaces to see the difference.
Know what this version does not do
The list disappears when the program ends because this example does not save anything to a file. That is okay: a small finished program teaches more than a large unfinished one. As a next step, ask for three titles in a loop, or learn how to write lines to a local text file. Keep a copy of each working version before adding a new feature so you can return to it if an experiment breaks.
Where to continue
Read the official Python tutorial when you want to learn about lists, loops, and files. Compare each new example with this project: what information does it receive, what does it store, and what does it produce? Those three questions make unfamiliar code easier to follow. The Python documentation for input() and print() is a useful reference when you want exact behavior.
Explore the related ebook for more ideas.
View How to Code