Chapter 3: Your First Python Program

In this foundational chapter, you'll write your very first Python programs and learn the fundamental concepts that will serve as building blocks for everything you create in Python. We'll start with the classic "Hello, World!" program and progress to understanding variables, basic data types, error handling, and the tools you'll need to debug your code. Get ready to join the ranks of Python programmers – this is where your journey begins.

In this chapter you will learn:

3.1 Write a Python Script

The first step in your Python programming journey is creating and running a simple script. Unlike clicking buttons in a word processor or media player, programming requires you to write instructions that the computer can understand and execute. Your first program will be the traditional "Hello, World!" greeting.

Interactive vs Script Mode

Python offers two primary ways to execute code: the interactive interpreter and script files. Each has its purpose and benefits.

The Interactive Interpreter (REPL)

The interactive interpreter (also called the Python shell or REPL - Read, Evaluate, Print, Loop) is perfect for testing small pieces of code and learning the language. When you start IDLE, you automatically get an interactive window that shows a prompt like this:

>>>

This is Python's way of saying "I'm ready for your commands." Type a statement at the prompt and press Enter. Python will evaluate it immediately and display the result:

>>> print("Hello, World!") Hello, World! >>> 2 + 2 4 >>> "Hello" + " " + "World" 'Hello World'

The REPL is great for experimenting with language features and testing short pieces of code. However, its major limitation is that your work disappears when you close the interpreter session. For more permanent programs, you need to use scripts.

Creating and Running Script Files

Script files contain code that you can save, modify, and run repeatedly. To create a script in IDLE:

  1. Open a new script window by selecting File → New File
  2. Type your code in the script window
  3. Save the file with a .py extension (e.g., hello.py)
  4. Run the script by selecting Run → Run Module (or press F5)

Let's create your first program. In the script window, type:

print("Hello, world!")

Save this as hello_world.py and run it. You should see:

Hello, world!

The print() function is one of Python's built-in functions. It takes one or more arguments and displays them on the screen. The parentheses are required when calling functions in Python.

Let's make a more interesting example. Create a new script with this code:

print("Welcome to Python programming!") print("Today is a great day to start coding.") print("Let's build something amazing together!")

Save it as welcome.py and run it. Each print statement displays on a separate line.

Understanding the Print Function

The print() function has several optional parameters that control its behavior:

>>> print("Hello", "world")      # Multiple arguments Hello world >>> print("Hello", "world", sep="-")    # Custom separator Hello-world >>> print("First", end=" ")           # Custom ending (no newline) >>> print("Second")              # Continues on same line First Second

3.2 Mess Things Up (Handling Errors)

Programming is fundamentally about problem-solving. One crucial problem-solving skill is addressing errors when they occur. Python provides clear, specific error messages to help you identify and fix problems. To learn effectively, we need to actively explore what happens when things go wrong.

Syntax Errors

Syntax errors occur when you write code that doesn't follow Python's grammatical rules. These are caught before the program runs and are also called "parsing errors" or "compile-time errors." Common causes include:

Try running this (deliberately) broken script:

print("This line is fine") print("This line has noclosing parenthesis" print("This line won't run if there's an error above")

Python will display:

SyntaxError: unterminated string literal (detected at line 2)

Common Syntax Error Messages

Error Message Common Cause
SyntaxError: invalid syntax Missing colon, mismatched brackets, or incorrect keyword usage
SyntaxError: unterminated string literal Missing quotation mark at end of string
IndentationError: expected an indented block Missing indentation after colon
IndentationError: unexpected indent Incorrect indentation that doesn't match surrounding code

Fix syntax errors by checking your code line by line. Look for mismatched punctuation and ensure proper indentation. Python's error messages usually point exactly to the problem location.

Runtime Errors

Runtime errors (also called exceptions) occur while the program is running. Syntax errors prevent the program from starting, but runtime errors crash programs that are already executing. Common types include:

Try this code to see runtime errors in action:

# This will cause a NameError print(undefined_variable) # This will cause a TypeError print("hello" + 5) # This will cause a ZeroDivisionError result = 10 / 0

The program will stop execution at the first error. Here's what you'll see:

Traceback (most recent call last): NameError: name 'undefined_variable' is not defined

Error messages include a "traceback" that shows exactly where the error occurred. The traceback shows the sequence of function calls that led to the error, with the most recent call at the bottom.

Fixing Errors Systematically

When you encounter an error:

  1. Read the error message - It tells you exactly what went wrong
  2. Check the line number - The error location in the traceback
  3. Look for typos - Variable names, function names, operators
  4. Check indentation - Python depends on consistent indentation
  5. Test minimal code - Run simplified versions to isolate problems
  6. Use print() for debugging - Add temporary print statements to see variable values

3.3 Create a Variable

Variables are the foundation of programming. They allow you to store, reference, and manipulate data throughout your program. In Python, variables are created when you first assign a value to them.

The Assignment Operator

The equals sign (=) is Python's assignment operator. It stores the value on the right into the variable name on the left:

>>> message = "Hello, world!" >>> count = 42 >>> price = 29.99 >>> is_active = True

Unlike many languages, Python doesn't require you to declare variable types. The interpreter automatically determines the appropriate type based on the value assigned.

Variable Naming Rules

Python variable names must follow these rules:

  1. Start with a letter or underscore - Never begins with a number
  2. Contain only alphanumeric characters and underscores - No special characters
  3. Are case-sensitive - name, Name, and NAME are different
  4. No reserved words - Cannot use keywords like if, for, print

Python follows the convention of using lowercase variable names with underscores for readability: user_name rather than username or userName.

Good Variable Names

# Good examples user_name = "Alice" total_price = 99.95 is_logged_in = True customer_list = ["Alice", "Bob", "Charlie"] # Not so good x = "Alice"                            # Too vague TotalPrice = 99.95                      # Mixed case (against PEP 8) variable1 = True                        # Not descriptive

Basic Data Types in Python

Every value in Python belongs to a specific data type. Let's introduce the most fundamental ones:

Integers (int)

Whole numbers, positive or negative:

>>> age = 25 >>> temperature = -5 >>> year = 2024 >>> type(age)

Floating‑Point Numbers (float)

Decimal numbers:

>>> pi = 3.14159 >>> price = 19.99 >>> percentage = 0.75 >>> type(pi)

Strings (str)

Text data:

>>> name = "Alice" >>> message = "Hello, World!" >>> type(name)

Booleans (bool)

True or false values:

>>> is_raining = True >>> has_license = False >>> type(is_raining)

Inspecting Variables

Python's interactive interpreter is excellent for examining variables:

>>> name = "Alice" >>> name                               # Just typing the name shows its value 'Alice' >>> age = 30 >>> type(age)                            # Check the data type >>> repr(age)                            # Official string representation '30'

Just typing a variable's name in the interactive interpreter displays its value. This is often more informative than using print(), especially for complex data types.

3.4 Leave Yourself Helpful Notes (Comments)

Comments are essential for making your code understandable to others and your future self. In Python, comments begin with the hash symbol (#).

Writing Comments

Anything after # on the same line is ignored by Python:

# This is a comment print("This will run")  # This comment is on the same line

Types of Comments

# Calculate the area of a circle radius = 5.0                            # Radius in centimeters # Formula: area = π × r² import math area = math.pi * (radius ** 2) print(f"The area is {area:.2f} cm²")

Comment Best Practices

Effective commenting involves balance:

Avoid obvious comments that merely restate what the code does. Focus on explaining the "why" and "how" rather than the "what".

# Bad comment - just restates the obvious count = count + 1  # Add one to count # Good comment - explains the business logic discount = base_price * 0.15  # Apply 15% senior citizen discount

Keep comments current with code changes. Outdated comments are worse than no comments at all.

3.5 Getting User Input

User input allows your programs to be interactive. Python's input() function reads text entered by the user.

The input() Function

input() displays a prompt and waits for the user to type something:

>>> name = input("What is your name? ") What is your name? Alice >>> name 'Alice'

The function always returns a string, even if the user types a number:

>>> age = input("How old are you? ") How old are you? 25 >>> age '25' >>> type(age)

Type Conversion

Convert strings to other types when needed:

# Convert to integer age = int(input("Enter your age: ")) # Convert to float price = float(input("Enter the price: ")) # Convert to boolean (strings are truthy if non-empty) is_active = bool(input("Enter 'y' to continue: "))

Always handle potential conversion errors. If the user enters non-numeric text for int(), Python raises a ValueError.

3.6 Challenge: Personal Greeting Program

Create a program called greeter.py that:

  1. Prompts the user for their first name
  2. Prompts the user for their age
  3. Displays a personalized greeting including their name and age
  4. Calculates and displays how old they will be in 5 years
  5. Uses proper error handling for age input
What is your name? Alice How old are you? 30 Hello, Alice! You are 30 years old. In 5 years, you will be 35 years old.

Error Handling Version

try:   name = input("What is your name? ")   age = int(input("How old are you? "))   print(f"Hello, {name}! You are {age} years old.")   print(f"In 5 years, you will be {age + 5} years old.") except ValueError:   print("Please enter a valid age (next time around).")

Review Exercises

  1. Write a program that prompts for a person's name and favorite color, then displays a message combining them.
  2. Create a program that asks for the length and width of a rectangle and prints its area and perimeter.
  3. Modify the greeter program to ask three questions and provide an appropriate response to each.
  4. Test your understanding by intentionally creating different types of errors and noting the error messages.
  5. Add helpful comments to explain the purpose of each section in your greeter program.

3.7 Using IDLE Effectively

IDLE provides several features that can help you write and debug Python programs more efficiently. Learning these features early will make your programming life much easier.

Keyboard Shortcuts

IDLE supports various keyboard shortcuts to speed up common operations:

# In the interactive window: Alt+P      # Previous command (up arrow also works) Alt+N      # Next command (down arrow also works) Ctrl+C    # Interrupt running code # In the script window: Ctrl+N      # New window Ctrl+O      # Open file Ctrl+S      # Save file F5         # Run module

Code Coloring and Syntax Highlighting

IDLE uses colors to make your code more readable:

Print Function Tips in IDLE

The print() function automatically adds newlines, but has additional parameters for control:

>>> print("Hello", "World", sep="-", end="!") Hello-World! >>> print("This", end=" ") >>> print("is on the same line.") This is on the same line.

Debugging with Print

Temporary print statements are the easiest way to debug your programs:

def calculate_tax(price, rate):     tax = price * rate     print(f"Debug: price={price}, rate={rate}, tax={tax}")  # Temporary debug     return tax

3.8 Summary and Additional Resources

This foundational chapter introduced you to the basics of Python programming. You learned how to write and run your first programs, handle common errors, work with variables and data types, add comments for documentation, and create interactive programs with user input.

With these fundamentals, you're ready to explore more advanced programming concepts. Practice by creating small programs that demonstrate these concepts.

Interactive Quiz: This chapter comes with a free online quiz to test your understanding of Python programming fundamentals.

End of Chapter 3 — Your First Python Program

100%