2. Your First Python Programs
In Chapter 1, you learned how to install Python, use the interactive shell (REPL), and run simple script files. You also got your first look at errors and tracebacks. Now it's time to write your first real Python programs—programs that display information, accept input from users, and produce meaningful results.
This chapter introduces the fundamental building blocks you'll use in nearly every Python program you write: the print() function for displaying output, comments for documenting your code, variables for storing data, and the input() function for getting information from users. By the end of this chapter, you'll be able to create simple but complete interactive programs that follow the classic input-process-output pattern.
2.1) Printing Text with the print() Function
The print() function is one of Python's most essential tools. It displays text (and other information) to the screen, allowing your programs to communicate with users. You've already seen print() briefly in Chapter 1, but now we'll explore it in depth.
2.1.1) Basic Printing
At its simplest, print() displays text enclosed in quotes. Let's create a script file to see how this works:
# hello.py
print("Hello, World!")When you run this script, Python displays:
Hello, World!The text inside the quotes—"Hello, World!"—is called a string. A string is a sequence of characters (letters, numbers, symbols, spaces) that Python treats as text. We'll explore strings in much more detail in Chapter 5, but for now, think of them as the way you represent text in Python.
You can print any text you want by placing it inside quotes:
# greetings.py
print("Welcome to Python programming!")
print("This is your first real program.")
print("Python makes programming fun and accessible.")Output:
Welcome to Python programming!
This is your first real program.
Python makes programming fun and accessible.Notice that each print() statement produces output on a separate line. Python automatically adds a line break (newline) after each print() call, moving the cursor to the next line.
2.1.2) Printing Multiple Items
The print() function can display multiple items in a single call by separating them with commas:
# multiple_items.py
print("Python", "is", "awesome!")
print("I", "am", "learning", "to", "code")Output:
Python is awesome!
I am learning to codeWhen you separate items with commas, print() automatically inserts a space between them. This is convenient for combining multiple pieces of text without having to manually add spaces.
You can also mix different types of data. For example, you can print both text and numbers:
# mixed_output.py
print("The answer is", 42)
print("Python version", 3.12, "is powerful")Output:
The answer is 42
Python version 3.12 is powerfulPython automatically converts numbers to text when printing them, so you don't need to worry about the technical details yet. We'll learn more about different data types in Chapter 3.
2.1.3) Single vs Double Quotes
Python accepts both single quotes (') and double quotes (") for strings. These are completely interchangeable for simple text:
# quotes.py
print("This uses double quotes")
print('This uses single quotes')
print("Both work exactly the same way")Output:
This uses double quotes
This uses single quotes
Both work exactly the same wayHowever, quotes become important when your text contains apostrophes or quotation marks. If your text contains an apostrophe (which is the same character as a single quote), use double quotes to enclose it:
# apostrophes.py
print("It's a beautiful day!")
print("Python's syntax is clean")Output:
It's a beautiful day!
Python's syntax is cleanIf you tried to use single quotes here, Python would get confused:
# This causes an error:
print('It's a beautiful day!') # Error! Python sees three separate quotesThe error occurs because Python sees the apostrophe in "It's" as the end of the string, leaving "s a beautiful day!" as invalid code.
Similarly, if your text contains double quotes, use single quotes to enclose it:
# quotations.py
print('She said, "Hello!"')
print('The book is called "Python Basics"')Output:
She said, "Hello!"
The book is called "Python Basics"Practical guideline: Choose one style (single or double quotes) and use it consistently throughout your code. Most Python programmers prefer double quotes for regular strings, but either choice is fine. Switch to the other style only when your text contains the quote character you normally use.
2.1.4) Printing Empty Lines
Sometimes you want to add blank lines to your output to make it more readable. You can do this by calling print() with no arguments:
# spacing.py
print("First section of output")
print("More information here")
print() # Empty line
print("Second section of output")
print("This is separated from the first section")Output:
First section of output
More information here
Second section of output
This is separated from the first sectionThe empty print() call creates a blank line, making the output easier to read by visually separating different sections.
2.1.5) Special Characters in Strings
Sometimes you need to include special characters in your output that you can't type directly or that have special meaning in Python. For example, how do you create a line break in the middle of a string? Or include a tab for alignment? Python provides escape sequences—special two-character combinations that start with a backslash (\)—to represent these characters.
These escape sequences are particularly useful when you need to format output in specific ways—creating multi-line messages, aligning columns of data, or working with file paths on Windows. You'll use \n frequently as you write more programs.
The most common escape sequence is \n, which represents a newline (line break):
# newlines.py
print("First line\nSecond line\nThird line")Output:
First line
Second line
Third lineThe \n tells Python to move to a new line at that point in the string. This is useful when you want to create multiple lines of output with a single print() statement.
Another useful escape sequence is \t, which represents a tab (horizontal spacing):
# tabs.py
print("Name:\tJohn")
print("Age:\t25")
print("City:\tNew York")Output:
Name: John
Age: 25
City: New YorkThe \t creates consistent spacing, aligning the values in a column-like format.
If you need to include an actual backslash in your output, use \\:
# backslash.py
print("The file path is C:\\Users\\Documents")Output:
The file path is C:\Users\DocumentsWe'll explore escape sequences and string handling in much more depth in Chapter 5. For now, just know that \n creates new lines and \t creates tabs.
2.2) Using Comments to Explain Code
As your programs grow more complex, it becomes important to explain what your code does—both for others who might read it and for your future self. Python provides comments for this purpose: notes in your code that Python completely ignores when running the program.
2.2.1) Single-Line Comments
In Python, any text following a # symbol on a line is a comment. Python ignores everything from the # to the end of that line:
# comment_example.py
# This is a comment. Python ignores this line completely.
print("This line runs") # This comment explains the print statement
# print("This line does NOT run because it's commented out")
print("This line also runs")Output:
This line runs
This line also runsNotice that the second print() statement didn't execute because the entire line was commented out. This is useful when you want to temporarily disable code without deleting it.
Comments can appear on their own line or at the end of a line of code. Both styles are common:
# display_info.py
# Display a welcome message to the user
print("Welcome to the program!")
print("Processing data...") # Inform the user of progress2.2.2) When and How to Write Good Comments
Comments should explain why you're doing something, not just what the code does. Here's an example of a poor comment:
# Bad comment - just repeats what the code obviously does
print("Hello") # Print "Hello"This comment doesn't add any value because anyone reading the code can already see that it prints "Hello".
Here's a better approach:
# Good comment - explains the purpose or context
# Greet the user before requesting their information
print("Hello")This comment explains why we're printing "Hello"—it's part of a larger interaction with the user.
Guidelines for writing helpful comments:
- Explain the purpose: Why does this code exist? What problem does it solve?
- Clarify complex logic: If something isn't immediately obvious, explain it
- Note important decisions: Explain why you chose one approach over another
- Warn about gotchas: Point out anything that might be confusing or unexpected
- Keep them current: Update comments when you change the code
Here's an example showing effective commenting:
# temperature_converter.py
# This program converts temperatures from Fahrenheit to Celsius
# Formula: C = (F - 32) × 5/9
# Display program title
print("Temperature Converter")
print("Fahrenheit to Celsius")
print()
# We'll learn how to get user input in section 2.4
# For now, we'll use a fixed temperature value
fahrenheit = 75 # Temperature in Fahrenheit to convert
# Perform the conversion using the standard formula
# Subtract 32 first (order matters due to the formula)
celsius = (fahrenheit - 32) * 5 / 9
# Display the result
print("Temperature:", fahrenheit, "°F =", celsius, "°C")Output:
Temperature Converter
Fahrenheit to Celsius
Temperature: 75 °F = 23.88888888888889 °CNotice how the comments explain the program's purpose, the formula being used, and the logic behind the calculation. They make the code much easier to understand, especially for someone encountering it for the first time.
2.2.3) Multi-Line Comments and Docstrings
For longer explanations, you could use multiple single-line comments:
# multi_line_comments.py
# This program demonstrates a longer explanation
# that spans multiple lines. Each line starts
# with a # symbol.
print("Program starts here")Python doesn't have a special multi-line comment syntax like some other languages. However, there's an alternative approach using triple-quoted strings. We'll learn more about this in Chapter 19 when we discuss docstrings (documentation strings for functions), but here's a preview:
# docstring_preview.py
"""
This is a multi-line string that can serve as a comment.
It's not technically a comment—it's a string that Python
creates but doesn't use. However, it's often used for
longer explanations at the beginning of files.
"""
print("Program starts here")For now, stick with # for comments. We'll explore triple-quoted strings and their proper uses in later chapters.
2.2.4) Commenting Out Code for Testing
Comments are also useful for temporarily disabling code while testing:
# testing.py
print("This always runs")
# print("This is disabled for testing")
print("This also always runs")This technique is called "commenting out" code. It's helpful when you want to test how your program behaves without certain lines, but you don't want to delete those lines permanently.
2.3) Introducing Variables and Assignment (Preview)
Programs become much more useful when they can store and manipulate data. Variables are named containers that hold values. Think of a variable as a labeled box where you can store information and retrieve it later.
Important note: This section provides a preview of variables to help you understand the examples in this chapter. We'll explore variables in complete depth in Chapter 3, including naming rules, data types, and how Python handles variables internally. For now, we'll focus on the basic concept and usage.
2.3.1) Creating Variables with Assignment
You create a variable using the assignment operator (=). The basic pattern is:
variable_name = valueThe variable name goes on the left, the value goes on the right, and the = connects them:
# variables_basic.py
message = "Hello, Python!"
print(message)Output:
Hello, Python!Here's what happens:
- Python creates a variable named
message - Python stores the string
"Hello, Python!"in that variable - When we use
messagein theprint()function, Python retrieves the stored value and displays it
Variables can store different types of data. Here are some examples:
# variable_types.py
greeting = "Welcome!" # A string (text)
age = 25 # A number (integer)
price = 19.99 # A number with a decimal point (float)
is_student = True # A boolean (True or False)
print(greeting)
print(age)
print(price)
print(is_student)Output:
Welcome!
25
19.99
TrueWe'll learn about these different data types (strings, integers, floats, booleans) in Chapter 3. For now, just understand that variables can hold various kinds of information.
2.3.2) Why Variables Are Useful
Variables make your code more flexible and easier to maintain. Compare these two approaches:
Without variables:
# no_variables.py
print("Welcome, John!")
print("John, your account balance is $1000")
print("Thank you for banking with us, John!")With variables:
# with_variables.py
name = "John"
balance = 1000
print("Welcome,", name + "!")
print(name, "your account balance is $", balance)
print("Thank you for banking with us,", name + "!")Both programs produce similar output, but the version with variables has significant advantages:
- Easy updates: To change the name, you only need to modify one line (
name = "John") instead of three - Fewer errors: You can't accidentally misspell the name in one place
- More flexible: You can later change how
namegets its value (for example, by asking the user)
2.3.3) Reassigning Variables
Variables can change their values during program execution. This is called reassignment:
# reassignment.py
score = 0
print("Initial score:", score)
score = 10
print("After first update:", score)
score = 25
print("After second update:", score)Output:
Initial score: 0
After first update: 10
After second update: 25Each time you assign a new value to a variable, Python replaces the old value with the new one. The previous value is discarded.
You can even use a variable's current value to calculate its new value:
# updating_values.py
count = 5
print("Starting count:", count)
count = count + 1 # Add 1 to count
print("After adding 1:", count)
count = count + 10 # Add 10 to count
print("After adding 10:", count)Output:
Starting count: 5
After adding 1: 6
After adding 10: 16This pattern—count = count + 1—is extremely common in programming. It means "take the current value of count, add 1 to it, and store the result back in count." We'll learn about a shorthand for this (count += 1) in Chapter 4.
2.3.4) Variable Naming Preview
Variable names in Python must follow certain rules:
- They can contain letters, numbers, and underscores (
_) - They must start with a letter or underscore (not a number)
- They cannot contain spaces or special characters like
@,$,%, etc. - They cannot be Python keywords (reserved words like
print,if,for, etc.)
Here are some valid variable names:
# valid_names.py
user_name = "Alice"
age2 = 30
_private_value = 42
totalPrice = 99.99And some invalid names:
# These cause errors:
# 2age = 30 # Cannot start with a number
# user-name = "Alice" # Cannot contain hyphens
# total price = 99.99 # Cannot contain spaces
# print = "Hello" # Cannot use Python keywordsBest practice: Use descriptive names that explain what the variable represents. user_age is better than a, and total_price is better than tp. We'll discuss naming conventions in detail in Chapter 3.
2.3.5) Variables Make Programs Dynamic
The real power of variables becomes apparent when you use them to make programs more dynamic:
# dynamic_greeting.py
name = "Alice"
age = 28
city = "Seattle"
print("Personal Information")
print("====================")
print("Name:", name)
print("Age:", age)
print("City:", city)
print()
print("Summary:", name, "is", age, "years old and lives in", city)Output:
Personal Information
====================
Name: Alice
Age: 28
City: Seattle
Summary: Alice is 28 years old and lives in SeattleBy changing the values of name, age, and city at the top of the program, you can customize the entire output without modifying the print() statements. This separation of data from logic is a fundamental principle of good programming.
Looking ahead: In Chapter 3, we'll explore variables comprehensively, including data types, type conversion, naming rules, and how Python manages variables internally. For now, you have enough understanding to use variables in simple programs.
2.4) Reading Input from the Keyboard with input()
So far, all the data in our programs has been hardcoded—written directly into the code. But real programs often need to interact with users, accepting information they provide. Python's input() function makes this possible.
2.4.1) Basic Input
The input() function displays a message (called a prompt) and waits for the user to type something and press Enter. Here's the basic pattern:
# basic_input.py
name = input("What is your name? ")
print("Hello,", name + "!")When you run this program, here's what happens:
What is your name? Alice
Hello, Alice!Let's break this down:
- Python executes
input("What is your name? ") - Python displays the prompt:
What is your name? - The program pauses and waits for the user to type something
- The user types
Aliceand presses Enter - Python stores the text
"Alice"in the variablename - The program continues, printing the greeting
The text you provide to input() is the prompt—what the user sees before typing. Always include a space at the end of your prompt (notice the space after the question mark) to separate the prompt from the user's input, making it easier to read.
2.4.2) Input Always Returns a String
This is crucial to understand: input() always returns a string, even if the user types numbers:
# input_as_string.py
age = input("How old are you? ")
print("You entered:", age)
print("The type is:", type(age))When you run this and enter 25:
How old are you? 25
You entered: 25
The type is: <class 'str'>Even though the user typed 25, Python stores it as the string "25", not as the number 25. The type() function confirms this—it shows that age is a string (str), not an integer.
This matters when you want to perform calculations. You cannot directly do math with strings:
# This causes an error:
age = input("How old are you? ")
next_year_age = age + 1 # Error! Can't add a number to a stringThis produces an error because Python doesn't know how to add the number 1 to the string "25".
2.4.3) Converting Input to Numbers
To use input as a number, you must explicitly convert it using int() (for whole numbers) or float() (for decimal numbers):
# input_conversion.py
age_string = input("How old are you? ")
age = int(age_string) # Convert string to integer
next_year = age + 1
print("Next year, you will be", next_year, "years old")When you run this and enter 25:
How old are you? 25
Next year, you will be 26 years oldYou can also combine the input and conversion in one line:
# input_conversion_compact.py
age = int(input("How old are you? "))
next_year = age + 1
print("Next year, you will be", next_year, "years old")This is more concise and is the style you'll see most often. It works from the inside out:
input("How old are you? ")gets the user's input as a stringint(...)converts that string to an integer- The integer is stored in the variable
age
Here's an example using float() for decimal numbers:
# float_input.py
price = float(input("Enter the price: $"))
tax_rate = 0.08
tax = price * tax_rate
total = price + tax
print("Price: $", price)
print("Tax: $", tax)
print("Total: $", total)When you run this and enter 19.99:
Enter the price: $19.99
Price: $ 19.99
Tax: $ 1.5992
Total: $ 21.5892Important: If the user enters text that cannot be converted to a number, Python will raise an error. For example, if you use int(input("Enter a number: ")) and the user types "hello", Python cannot convert "hello" to an integer and will display an error message. We'll learn how to handle these situations gracefully in Chapter 27 when we study exception handling.
2.4.4) Multiple Inputs
Programs often need several pieces of information from the user. Simply call input() multiple times:
# multiple_inputs.py
print("Please enter your information:")
print()
first_name = input("First name: ")
last_name = input("Last name: ")
age = int(input("Age: "))
city = input("City: ")
print()
print("Summary")
print("=======")
print("Name:", first_name, last_name)
print("Age:", age)
print("Location:", city)Example interaction:
Please enter your information:
First name: John
Last name: Smith
Age: 30
City: Boston
Summary
=======
Name: John Smith
Age: 30
Location: BostonNotice how the program prompts for each piece of information separately. This makes it clear to the user what they need to provide and in what order.
2.4.5) Creating Informative Prompts
Good prompts make your programs easier to use. Here are some guidelines:
Be specific about what you want:
# Good prompts
name = input("Enter your full name: ")
temperature = float(input("Enter temperature in Fahrenheit: "))
quantity = int(input("How many items do you want to purchase? "))Include the expected format or units:
# format_prompts.py
date = input("Enter date (MM/DD/YYYY): ")
phone = input("Enter phone number (XXX-XXX-XXXX): ")
price = float(input("Enter price in dollars (without $): "))Use clear, friendly language:
# friendly_prompts.py
print("Welcome to the Temperature Converter!")
print()
temp = float(input("Please enter a temperature in Fahrenheit: "))Clear prompts reduce user confusion and make your programs more professional.
2.5) Simple Input-Process-Output Programs
Most programs follow a common pattern called Input-Process-Output (IPO):
- Input: Get data from the user or another source
- Process: Perform calculations or transformations on the data
- Output: Display the results
This pattern is so fundamental that you'll use it in countless programs throughout your programming journey. Let's explore it with several complete examples.
2.5.1) Example: Temperature Converter
Let's create a complete program that converts temperatures from Fahrenheit to Celsius:
# temperature_converter.py
# This program converts a temperature from Fahrenheit to Celsius
# Formula: C = (F - 32) × 5/9
print("Temperature Converter")
print("Fahrenheit to Celsius")
print("=" * 30) # Print a line of equal signs
print()
# INPUT: Get temperature from user
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
# PROCESS: Convert using the formula
celsius = (fahrenheit - 32) * 5 / 9
# OUTPUT: Display the result
print()
print("Result:", fahrenheit, "°F =", celsius, "°C")Example interaction:
Temperature Converter
Fahrenheit to Celsius
==============================
Enter temperature in Fahrenheit: 75
Result: 75.0 °F = 23.88888888888889 °CNotice how the program clearly follows the IPO pattern:
- Input: Get the Fahrenheit temperature
- Process: Apply the conversion formula
- Output: Display the Celsius result
The comments in the code explicitly mark these three sections, making the program's structure clear.
2.5.2) Example: Rectangle Area Calculator
Here's another IPO example that calculates the area of a rectangle:
# rectangle_area.py
# Calculate the area of a rectangle
# Formula: Area = length × width
print("Rectangle Area Calculator")
print("=" * 30)
print()
# INPUT: Get dimensions from user
length = float(input("Enter the length: "))
width = float(input("Enter the width: "))
# PROCESS: Calculate area
area = length * width
# OUTPUT: Display the result
print()
print("A rectangle with length", length, "and width", width)
print("has an area of", area, "square units")Example interaction:
Rectangle Area Calculator
==============================
Enter the length: 5.5
Enter the width: 3.2
A rectangle with length 5.5 and width 3.2
has an area of 17.6 square units2.5.3) Example: Shopping Total Calculator
This example calculates a shopping total with tax:
# shopping_total.py
# Calculate total cost including tax
print("Shopping Total Calculator")
print("=" * 30)
print()
# INPUT: Get price and tax rate
price = float(input("Enter item price: $"))
tax_rate = float(input("Enter tax rate (as decimal, e.g., 0.08 for 8%): "))
# PROCESS: Calculate tax and total
tax_amount = price * tax_rate
total = price + tax_amount
# OUTPUT: Display itemized breakdown
# Note: Comma in print() adds a space after $
print()
print("Purchase Summary")
print("-" * 30)
print("Item price: $", price)
print("Tax rate: ", tax_rate * 100, "%")
print("Tax amount: $", tax_amount)
print("-" * 30)
print("Total: $", total)Example interaction:
Shopping Total Calculator
==============================
Enter item price: $49.99
Enter tax rate (as decimal, e.g., 0.08 for 8%): 0.08
Purchase Summary
------------------------------
Item price: $ 49.99
Tax rate: 8.0 %
Tax amount: $ 3.9992
------------------------------
Total: $ 53.98922.6) Basic Debugging by Reading Simple Error Messages
Even experienced programmers make mistakes. Learning to read and understand error messages is an essential skill that will save you countless hours of frustration. Python's error messages are actually quite helpful—they tell you what went wrong and where the problem occurred.
The terms "error message" and "traceback" are related but slightly different: a traceback is the complete report Python shows when an error occurs, including the error type, description, and the path through your code that led to the error. The error message is the final line of the traceback that describes what went wrong. In casual conversation, programmers often use "error message" to refer to the entire traceback.
2.6.1) Understanding Error Messages
When Python encounters an error, it displays a traceback—a detailed report about what went wrong. Let's look at a simple example:
# error_example.py
print("Starting the program")
print("This line works fine"
print("This line might not be reached")When you try to run this, Python displays:
File "error_example.py", line 2
print("This line works fine"
^
SyntaxError: '(' was never closedLet's break down what this error message tells us:
- File name:
error_example.py- The file where the error occurred - Line number:
line 2- Where Python detected the problem - Code snippet: Shows the problematic line with a
^pointing to where Python noticed the issue - Error type:
SyntaxError- What kind of error occurred - Description:
'(' was never closed- A human-readable explanation
The error occurred because we forgot the closing parenthesis on line 2. Python tried to continue reading the next line as part of the same print() statement and got confused.
2.6.2) Common Error Types for Beginners
Let's explore the most common errors you'll encounter as a beginner and how to fix them.
SyntaxError: Invalid Syntax
This is the most common error for beginners. It means Python couldn't understand your code because it doesn't follow Python's grammar rules.
Missing colon:
# missing_colon.py
name = input("What is your name? ")
if name == "Alice" # Missing colon
print("Hello, Alice!")Error:
File "missing_colon.py", line 2
if name == "Alice"
^
SyntaxError: expected ':'Note: We haven't learned about if statements yet—we'll cover them in Chapter 8. This example just shows what the error looks like.
Mismatched quotes:
# mismatched_quotes.py
message = "Hello, world!'
print(message)Error:
File "mismatched_quotes.py", line 1
message = "Hello, world!'
^
SyntaxError: unterminated string literal (detected at line 1)The error occurs because the string starts with a double quote (") but ends with a single quote ('). Python expects the same type of quote at both ends.
NameError: Name Not Defined
This error occurs when you try to use a variable that doesn't exist:
# name_error.py
print("Starting calculation")
result = total + 10 # 'total' was never created
print(result)Error:
Traceback (most recent call last):
File "name_error.py", line 2, in <module>
result = total + 10
^^^^^
NameError: name 'total' is not definedPython is telling you that it doesn't know what total is because you never created that variable. The fix is to define total before using it:
# name_error_fixed.py
print("Starting calculation")
total = 0 # Define the variable first
result = total + 10
print(result)Common causes of NameError:
- Typos in variable names (
totlainstead oftotal) - Using a variable before assigning it a value
- Forgetting to create a variable entirely
TypeError: Unsupported Operand Type(s)
This error occurs when you try to perform an operation on incompatible types:
# type_error.py
age = input("How old are you? ")
next_year = age + 1 # Can't add a number to a string
print("Next year:", next_year)Error:
Traceback (most recent call last):
File "type_error.py", line 2, in <module>
next_year = age + 1
~~~~^~~
TypeError: can only concatenate str (not "int") to strPython is telling you that age is a string (because input() returns strings), and you can't add a number to a string. The fix is to convert the input to an integer:
# type_error_fixed.py
age = int(input("How old are you? ")) # Convert to integer
next_year = age + 1
print("Next year:", next_year)ValueError: Invalid Literal
This error occurs when you try to convert a string to a number, but the string doesn't represent a valid number:
# value_error.py
age = int(input("How old are you? "))
print("You are", age, "years old")If the user enters text instead of a number:
How old are you? twenty
Traceback (most recent call last):
File "value_error.py", line 1, in <module>
age = int(input("How old are you? "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'twenty'Python is telling you that it can't convert the string "twenty" to an integer. The user needs to enter a number like 20 instead.
Important: Right now, if users enter invalid input, your program will crash with an error. This is normal for beginner programs. In Chapter 27, we'll learn how to handle these situations gracefully using exception handling, allowing your program to recover from errors and ask the user to try again.
2.6.3) Reading Tracebacks Carefully
When an error occurs, Python shows you a traceback that traces the error back through your code. For simple programs, the traceback is short:
# simple_traceback.py
print("Starting program")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello,", name)
print("Next year you'll be", age + 1)If the user enters invalid input for age:
Starting program
Enter your name: Alice
Enter your age: abc
Traceback (most recent call last):
File "simple_traceback.py", line 3, in <module>
age = int(input("Enter your age: "))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'The traceback shows:
- The file name and line number where the error occurred
- The actual line of code that caused the problem
- The type of error and a description
Reading strategy: Start from the bottom of the traceback and work your way up. The last line tells you what went wrong. The lines above show where in your code the error occurred.
2.6.4) Common Debugging Strategies
When you encounter an error, follow these steps:
1. Read the error message carefully
Don't panic! The error message is trying to help you. Read it completely and try to understand what it's saying.
2. Look at the line number
The error message tells you which line Python thinks has the problem. However, sometimes the actual mistake is on a previous line. For example, a missing closing parenthesis on line 2 might not be detected until Python reads line 3.
3. Check for common mistakes
- Missing or mismatched quotes
- Missing closing parentheses or brackets
- Missing colons (for statements we'll learn later like
if,for,while) - Typos in variable names
- Forgetting to convert input to numbers
4. Use print() to inspect values
If you're not sure what's going wrong, add print() statements to see what values your variables contain:
# debugging_with_print.py
price = input("Enter price: ")
print("DEBUG: price =", price, "type =", type(price)) # Debugging line
tax = price * 0.08 # This will cause an error
print("Tax:", tax)The debug line shows you that price is a string, not a number, helping you identify the problem.
5. Comment out code to isolate the problem
If you have multiple lines and aren't sure which one is causing the error, comment out lines until the error goes away:
# isolating_error.py
name = input("Enter name: ")
# age = int(input("Enter age: ")) # Commented out for testing
# city = input("Enter city: ") # Commented out for testing
print("Name:", name)Once the error disappears, you know the problem is in one of the commented lines.
6. Start with a simple version
If your program isn't working, simplify it to the bare minimum:
# simplified_version.py
# Start with just the basic structure
print("Program starting")
# Add one feature at a time and testOnce the simple version works, add features one at a time, testing after each addition.
2.6.5) Preventing Errors
While debugging is important, preventing errors in the first place is even better:
Write code incrementally
Don't write your entire program and then run it for the first time. Write a few lines, run the program, make sure those lines work, then add more. This way, when an error appears, you know it's in the code you just added.
# incremental_development.py
# Step 1: Get input and test
name = input("Enter name: ")
print("DEBUG: Got name:", name)
# Step 2: Add more input and test
# age = int(input("Enter age: "))
# print("DEBUG: Got age:", age)
# Step 3: Add processing and test
# ... and so onUse descriptive variable names
Clear variable names help you avoid mistakes:
# Clear variable names make errors less likely
user_age = int(input("Enter your age: "))
next_year_age = user_age + 1Add comments to explain your logic
Comments help you (and others) understand what the code should do, making it easier to spot when it's doing something different:
# temperature_with_comments.py
# Get temperature in Fahrenheit from user
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
# Convert to Celsius using the standard formula: C = (F - 32) × 5/9
celsius = (fahrenheit - 32) * 5 / 9
# Display the result
print(fahrenheit, "°F =", celsius, "°C")Test with different inputs
Don't just test your program once. Try different inputs, including edge cases:
- Normal values:
25,100 - Zero:
0 - Negative numbers:
-10 - Decimal numbers:
3.14 - Very large numbers:
1000000
This helps you discover problems before users encounter them.
2.6.6) When to Ask for Help
Sometimes you'll encounter errors you can't solve on your own. Before asking for help:
- Read the error message carefully - Make sure you understand what it's saying
- Search for the error - Copy the error message (without your specific variable names) and search online. Many errors have been encountered and solved by others
- Check your code carefully - Look for typos, missing punctuation, and common mistakes
- Create a minimal example - Reduce your code to the smallest version that still produces the error
When you do ask for help, provide:
- The complete error message
- The code that produces the error
- What you expected to happen
- What actually happened
- What you've already tried
Remember: Errors are a normal part of programming. Every programmer, from beginners to experts, encounters errors daily. The difference is that experienced programmers have learned to read error messages efficiently and know common solutions. You'll develop these skills with practice.
You've now learned the fundamental building blocks of Python programming: displaying output with print(), documenting code with comments, storing data in variables, getting user input with input(), following the input-process-output pattern, and debugging simple errors.
These concepts form the foundation for everything else you'll learn in Python. In the next chapter, we'll dive deeper into variables and explore Python's basic data types, giving you a more complete understanding of how Python stores and manipulates different kinds of information.
Key takeaways from this chapter:
- Use
print()to display text and other information to users - Use comments (
#) to explain your code and document your thinking - Store data in variables using assignment (
=) - Get user input with
input()and convert it to numbers when needed - Structure programs using the input-process-output pattern
- Read error messages carefully—they're trying to help you fix problems
- Write code incrementally and test frequently to catch errors early
With these skills, you can now write simple but complete interactive programs. As you continue learning, you'll build on these fundamentals to create increasingly sophisticated applications.