Python & AI Tutorials Logo
Python Programming

1. First Steps with Python

Welcome to your journey into Python programming! This chapter will guide you through the essential first steps: understanding what Python is, installing it on your computer, and running your first Python code. By the end of this chapter, you'll be comfortable using Python's interactive shell, creating and running script files, and understanding the basic error messages Python gives you.

1.1) What Is a Program and What Does Python Do?

Before diving into Python specifically, let's understand what a program is and what role Python plays in creating programs.

1.1.1) Understanding Programs

A program is a set of instructions that tells a computer what to do. Just as a recipe tells you step-by-step how to bake a cake, a program tells a computer step-by-step how to perform a task. These tasks can range from simple calculations to complex operations like displaying web pages, processing images, or controlling robots.

Computers don't understand human languages like English or Spanish directly. They only understand machine code—sequences of binary numbers (0s and 1s) that represent very basic operations. Writing programs directly in machine code would be extremely difficult and error-prone for humans.

This is where programming languages come in. A programming language is a human-readable way to write instructions that can be translated into machine code. Python is one such programming language, designed to be particularly easy for humans to read and write.

1.1.2) What Makes Python Special

Python is a high-level programming language, meaning it abstracts away many of the complex details that you'd need to handle in lower-level languages. Here's what makes Python particularly appealing for beginners and professionals alike:

Readable Syntax: Python code reads almost like English. For example, to print "Hello, World!" in Python, you write:

python
# hello_simple.py
print("Hello, World!")

Output:

Hello, World!

Compare this to languages like C or Java, which require more boilerplate code for the same task.

Interpreted Language: Python is an interpreted language. This means you don't need to compile your code into machine code before running it. Instead, a program called the Python interpreter reads your code and executes it line by line. This makes development faster because you can immediately see the results of your code changes.

Versatile and Powerful: Despite being beginner-friendly, Python is used in professional settings for:

  • Web development (websites and web applications)
  • Data analysis and visualization
  • Machine learning and artificial intelligence
  • Scientific computing
  • Automation and scripting
  • Game development
  • And much more

Large Community and Libraries: Python has a massive community of users and thousands of pre-written code libraries that extend its capabilities. This means solutions to common problems are often just a library import away.

1.1.3) How Python Executes Your Code

When you write Python code and run it, here's what happens behind the scenes:

Your Python Code

Python Interpreter

Bytecode

Python Virtual Machine

Execution/Output

  1. You write code: You create a file containing Python instructions or type them directly into the Python interactive shell.

  2. The interpreter reads your code: The Python interpreter checks your code for syntax errors (mistakes in how you've written the code).

  3. Translation to bytecode: If there are no syntax errors, Python translates your code into an intermediate form called bytecode. Bytecode is an intermediate form of your code—a translation into a language that's halfway between Python and machine code. It's simpler than Python for the computer to execute, but more abstract than pure machine code.

  4. Execution: The Python Virtual Machine (PVM) executes the bytecode, performing the operations you specified.

  5. Output: You see the results of your program—whether that's text printed to the screen, a file created, or any other action.

The beauty of this process is that you don't need to worry about most of these steps. You write code, run it, and see results. The interpreter handles the rest.

1.2) Installing Python and Running the Interpreter

To start programming in Python, you first need to install Python on your computer. This section will guide you through the installation process and verify that everything is working correctly.

1.2.1) Checking if Python Is Already Installed

Some operating systems come with Python pre-installed. Before downloading anything, let's check if Python is already on your system.

On Windows:

  1. Open the Command Prompt:

    • Press Windows + R to open the Run dialog
    • Type cmd and press Enter
  2. Type the following command and press Enter:

bash
python --version

If Python is installed, you'll see output like:

Python 3.11.5

If you see an error message like 'python' is not recognized as an internal or external command, Python is not installed or not in your system PATH.

On macOS:

  1. Open the Terminal application:

    • Press Command + Space to open Spotlight
    • Type Terminal and press Enter
  2. Type the following command and press Enter:

bash
python3 --version

Note: On macOS, you typically use python3 instead of python because python might refer to Python 2, which is outdated.

If Python 3 is installed, you'll see output like:

Python 3.11.5

On Linux:

  1. Open your terminal application (varies by distribution)

  2. Type the following command and press Enter:

bash
python3 --version

Most modern Linux distributions come with Python 3 pre-installed.

1.2.2) Downloading and Installing Python

If Python isn't installed or you have an older version, follow these steps to install the latest version.

Windows Installation:

  1. Visit the official Python website: https://www.python.org/downloads/

  2. Click the "Download Python" button (it will show the latest version, like "Download Python 3.11.5")

  3. Run the downloaded installer (.exe file)

  4. Important: On the first screen of the installer, check the box that says "Add Python to PATH". This is crucial—it allows you to run Python from any command prompt.

    What happens if you forget: If you don't check "Add Python to PATH", you won't be able to run Python from the command line, and you'll see an error like 'python' is not recognized as an internal or external command. If this happens, you'll need to either reinstall Python (checking the box this time) or manually add Python to your PATH, which is more complex for beginners.

  5. Click "Install Now" and wait for the installation to complete

  6. Verify the installation by opening a new Command Prompt and typing:

bash
python --version

You should see the version number you just installed.

macOS Installation:

  1. Visit https://www.python.org/downloads/

  2. Click the "Download Python" button for the latest version

  3. Open the downloaded .pkg file and follow the installation wizard

  4. Verify the installation by opening Terminal and typing:

bash
python3 --version

Linux Installation:

Most Linux distributions come with Python 3, but if you need to install or update it:

For Ubuntu/Debian-based systems:

bash
sudo apt update
sudo apt install python3

For Fedora/Red Hat-based systems:

bash
sudo dnf install python3

Verify with:

bash
python3 --version

1.2.3) Running the Python Interpreter

Once Python is installed, you can run the Python interpreter directly from your command line or terminal. The interpreter is the program that executes Python code. Running the interpreter directly opens the interactive shell (REPL), which we'll explore in detail in the next section. This is different from running a script file, which we'll cover in Section 1.4.

On Windows:

Open Command Prompt and type:

bash
python

On macOS and Linux:

Open Terminal and type:

bash
python3

You should see something like this:

Python 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> prompt indicates that Python is ready to accept your commands. This is called the Python interactive shell or REPL (Read-Eval-Print Loop), which we'll explore in detail in the next section.

To exit the interpreter, you can:

  • Type exit() and press Enter
  • Type quit() and press Enter
  • Press Ctrl + D (on macOS/Linux) or Ctrl + Z then Enter (on Windows)

Congratulations! You've successfully installed Python and verified that the interpreter works. You're now ready to start writing Python code.

1.3) Using the Python Interactive Shell (REPL)

The Python interactive shell, commonly called the REPL (Read-Eval-Print Loop), is one of Python's most useful features for learning and experimentation. It allows you to type Python code and see the results immediately, making it perfect for trying out new concepts, testing small pieces of code, and exploring Python's capabilities.

1.3.1) What Is the REPL?

The Python interactive shell, commonly called the REPL (Read-Eval-Print Loop), is one of Python's most useful features for learning and experimentation. The REPL is also called the Python interactive shell or simply the interactive interpreter—these terms all refer to the same thing: the >>> prompt where you can type Python code and see immediate results.

REPL stands for:

  • Read: Python reads the code you type
  • Eval: Python evaluates (executes) that code
  • Print: Python prints the result
  • Loop: Python loops back to read more code

This cycle continues until you exit the REPL. It's like having a conversation with Python—you give it an instruction, it responds, and you can immediately give it another instruction based on that response.

1.3.2) Starting and Using the REPL

To start the REPL, open your command line or terminal and type python (Windows) or python3 (macOS/Linux), as we did in the previous section.

Once you see the >>> prompt, you can start typing Python code. Let's try some basic examples:

Simple Arithmetic:

python
>>> 5 + 3
8
>>> 10 * 2
20
>>> 15 / 3
5.0

Notice that you don't need to use print() in the REPL—Python automatically displays the result of each expression. This is one of the REPL's conveniences.

Working with Text:

python
>>> "Hello, World!"
'Hello, World!'
>>> "Python" + " is " + "great"
'Python is great'

When you type just a string (text in quotes), Python shows it with quotes—this is Python's way of representing the string. If you want to display text without quotes, use the print() function:

python
>>> print("Hello, World!")
Hello, World!

Notice the difference: typing just the string shows it with quotes (Python's representation), but print() displays it without quotes (the actual text).

Storing Values in Variables:

While typing values directly is useful for quick tests, you'll often want to store values in variables—named containers that hold data you can reuse throughout your program.

python
>>> name = "Alice"
>>> name
'Alice'
>>> age = 25
>>> age
25

When you assign a value to a variable (like name = "Alice"), Python doesn't print anything. But when you type just the variable name, Python shows you its value.

Using Python as a Calculator:

python
>>> 2 + 2
4
>>> (10 + 5) * 2
30
>>> 100 / 4
25.0
>>> 7 % 3
1

The REPL is excellent for quick calculations and testing mathematical expressions.

1.3.3) Multi-Line Input in the REPL

Sometimes you need to write code that spans multiple lines, such as function definitions. The REPL handles this gracefully by changing its prompt. When you start a multi-line statement, the prompt changes from >>> to ... to indicate that Python is waiting for you to complete the statement.

Here's a simple example using a function (Note: We'll learn about functions in detail in Chapter 19. This example just shows how the REPL handles multi-line input with the ... continuation prompt):

python
>>> def greet():
...     print("Hello!")
...
>>> greet()
Hello!

After typing the first line and pressing Enter, the prompt becomes .... You type the indented line, press Enter, then press Enter again on an empty line to execute the code.

1.3.4) Accessing Previous Commands

The REPL keeps a history of the commands you've typed. You can use the up and down arrow keys to navigate through your command history:

  • Up arrow: Shows the previous command
  • Down arrow: Shows the next command (if you've gone back)

This is incredibly useful when you want to modify and re-run a command, or when you want to recall what you typed earlier.

1.3.5) Getting Help in the REPL

Python's REPL has built-in help features. You can get information about Python objects, functions, and modules directly.

These help features are most useful when you're exploring Python and want to learn what's available. For example, if you're working with strings and wonder what methods are available, dir(str) shows you all the options. As you progress through this book, you'll find these tools increasingly valuable for independent exploration.

python
>>> help()

This enters the help system. You can then type the name of something you want help with, or type quit to exit the help system.

You can also get help on specific things directly:

python
>>> help(print)

This shows documentation for the print() function. Press q to exit the help display.

Another useful function is dir(), which lists the attributes and methods available on an object. (Note: Attributes and methods are features and actions available on an object—we'll learn more about these in Chapter 43. We'll also learn about importing modules in Chapter 22. This example shows how the REPL helps explore Python's capabilities.)

python
>>> dir(str)

This shows all the methods available for string objects.

1.3.6) When the REPL Is Most Useful

The REPL excels at:

  1. Learning and Exploration: When you're learning a new concept, the REPL lets you experiment immediately without creating files.

  2. Testing Small Code Snippets: Before adding code to your program, you can test it in the REPL to ensure it works as expected.

  3. Quick Calculations: The REPL is a powerful calculator that's always available.

  4. Debugging: When your program isn't working, you can use the REPL to test individual parts of your code in isolation.

  5. Exploring Libraries: When learning a new library, you can import it in the REPL and try out its functions interactively.

However, the REPL has limitations. Code you write in the REPL disappears when you close it—there's no way to save your REPL session as a program. For any code you want to keep and run repeatedly, you'll need to create script files, which we'll cover in the next section.

1.3.7) Exiting the REPL

When you're done with the REPL, you can exit it in several ways:

python
>>> exit()

Or:

python
>>> quit()

Or use keyboard shortcuts:

  • Windows: Press Ctrl + Z, then Enter
  • macOS/Linux: Press Ctrl + D

After exiting, you'll return to your regular command prompt or terminal.

1.4) Creating and Running Python Script Files

The REPL is excellent for experimentation and quick tests, but what if you want to save your code and run it again later? What if you want to write a longer program with dozens or hundreds of lines? For these situations, you need script files—permanent files containing Python code that you can edit, save, and run repeatedly.

While the REPL is excellent for experimentation, most Python programming involves writing script files—text files containing Python code that can be saved, edited, and run repeatedly. In this section, you'll learn how to create your first Python script and run it from the command line.

1.4.1) What Is a Python Script?

A Python script is simply a text file containing Python code, saved with a .py extension. Unlike code typed into the REPL, script files:

  • Are permanent—you can save them and run them later
  • Can be edited and modified easily
  • Can contain as much code as you need
  • Can be shared with others
  • Can be run automatically or on a schedule

Think of a script file as a recipe you write down, while the REPL is like cooking while making up the recipe as you go. Both have their place, but for anything substantial, you'll want a script file.

1.4.2) Choosing a Text Editor

To create Python scripts, you need a text editor. Do not use word processors like Microsoft Word or Google Docs—these add formatting that Python cannot understand.

Good Options for Beginners:

  1. IDLE: Comes bundled with Python. Simple and designed for learning.

    • On Windows: Search for "IDLE" in the Start menu
    • On macOS/Linux: Type idle3 in the terminal
  2. Visual Studio Code (VS Code): Free, powerful, and widely used by professionals. Excellent Python support with extensions.

  3. PyCharm Community Edition: A full-featured IDE (Integrated Development Environment) specifically for Python.

  4. Notepad++ (Windows only): Lightweight and simple.

  5. Sublime Text: Fast and elegant, with good Python support.

For this book, we'll use simple examples that work with any text editor. Choose whichever editor feels most comfortable to you.

1.4.3) Creating Your First Python Script

Let's create a simple Python script that prints greeting messages.

Step 1: Create a New File

Open your chosen text editor and create a new file. Save it as hello.py in a location you'll remember (like your Desktop or a dedicated folder for Python projects).

Important: The .py extension is crucial. It tells your operating system and text editor that this is a Python file.

Step 2: Write Your Code

Type the following code into your file:

python
# hello.py
# My first Python script
 
print("Hello, World!")
print("Welcome to Python programming!")

Lines starting with # are comments—notes for humans reading the code. Python completely ignores them. Comments help you remember what your code does and help others understand your work. We'll explore comments in more detail in Chapter 2.

Step 3: Save the File

Save the file. Make sure it's saved as hello.py, not hello.py.txt or any other extension.

Let's understand what this code does:

  • print("Hello, World!") tells Python to display the text "Hello, World!" on the screen.
  • print("Welcome to Python programming!") displays another message.

Let's add one more example to bridge the gap before we move to more complex scripts:

python
# greetings.py
# A script with multiple print statements
 
print("Python is fun!")
print("Let's learn together.")
print("This is exciting!")

Save this as greetings.py. This example uses three print statements but no variables yet, helping you get comfortable with the basic structure before moving to more complex concepts.

1.4.4) Running Your Script from the Command Line

Now that you've created your script, let's run it.

Step 1: Open Your Command Line/Terminal

  • Windows: Open Command Prompt
  • macOS/Linux: Open Terminal

Step 2: Navigate to Your Script's Location

Use the cd (change directory) command to navigate to where you saved hello.py. For example, if you saved it on your Desktop:

Windows:

bash
cd Desktop

macOS/Linux:

bash
cd ~/Desktop

If you get an error like "No such file or directory" when trying to run your script, you're probably in the wrong folder. Use the cd command to navigate to where you saved your script.

To verify you're in the right location, you can list the files:

Windows:

bash
dir

macOS/Linux:

bash
ls

You should see hello.py in the list.

Step 3: Run Your Script

Windows:

bash
python hello.py

macOS/Linux:

bash
python3 hello.py

You should see the output:

Hello, World!
Welcome to Python programming!

Congratulations! You've just created and run your first Python script.

1.4.5) Understanding Script Execution

When you run a Python script, here's what happens:

  1. You type the command to run your script
  2. Your operating system launches the Python interpreter
  3. The interpreter reads your entire script file
  4. It checks for syntax errors (mistakes in how you wrote the code)
  5. If there are errors, it displays an error message and stops
  6. If there are no errors, it executes your code line by line, from top to bottom
  7. Any output (from print() statements) is displayed
  8. When the script finishes, control returns to your command line

1.4.6) A More Complex Example

Let's create a slightly more complex script that demonstrates multiple concepts. First, let's add an intermediate example that introduces variables more gently:

python
# simple_variable.py
# Using a variable for the first time
 
message = "Hello, Python!"
print(message)

Output:

Hello, Python!

This bridges the gap between pure print statements and more complex examples. Now let's look at a script with multiple variables:

python
# student_info.py
# A script that uses variables and multiple print statements
 
name = "Alice"
age = 25
city = "New York"
 
print("Student Information")
print("-------------------")
print("Name:", name)
print("Age:", age)
print("City:", city)

Save this as student_info.py and run it:

Windows:

bash
python student_info.py

macOS/Linux:

bash
python3 student_info.py

Output:

Student Information
-------------------
Name: Alice
Age: 25
City: New York

This script demonstrates:

  • Creating variables (we'll learn more about variables in Chapter 3)
  • Using multiple print() statements
  • Printing both literal text and variable values

1.4.7) Script File Best Practices

Even at this early stage, it's good to develop some habits:

  1. Use Descriptive Filenames: Name your files based on what they do. student_info.py is better than test.py or program1.py because you'll remember what it does when you see it in a list of files six months from now.

  2. Keep Scripts Organized: Create a dedicated folder for your Python projects. Don't scatter scripts all over your computer. This makes it easier to find your work and keeps your files organized.

  3. Add Comments: Start each script with a comment explaining what it does. This helps you remember later and helps others understand your code.

  4. One Script, One Purpose: Each script should do one main thing. Don't try to cram multiple unrelated tasks into one file. This makes your code easier to understand and maintain.

  5. Test Frequently: Run your script often as you write it. Don't wait until you've written 100 lines to test—test after every few lines. This helps you catch errors early when they're easier to fix.

1.5) A First Look at Errors and Tracebacks

Errors are a natural part of programming. Every programmer, from beginners to experts, encounters errors regularly. Learning to read and understand error messages is a crucial skill that will help you fix problems quickly and become a more confident programmer.

1.5.1) Types of Errors

Python distinguishes between two main categories of errors:

Syntax Errors: Mistakes in how you've written the code—violations of Python's grammar rules. Python detects these before running your code. Think of syntax errors like grammar mistakes in writing—Python can't even understand what you're trying to say.

Exceptions: Errors that occur while your code is running. The syntax is correct, but something goes wrong during execution. Exceptions are like runtime problems—Python understands your instructions but can't carry them out.

Let's explore both types with examples.

1.5.2) Syntax Errors

A syntax error occurs when you write code that doesn't follow Python's rules. Python can't even begin to run your code because it doesn't understand what you've written.

Example 1: Missing Colon

Create a file called syntax_error1.py:

python
# syntax_error1.py
# This code has a syntax error
 
if 5 > 3
    print("Five is greater than three")

When you try to run this:

bash
python syntax_error1.py

You'll see:

  File "syntax_error1.py", line 4
    if 5 > 3
            ^
SyntaxError: expected ':'

Python is telling you several things:

  • Which file has the problem: syntax_error1.py
  • Which line has the problem: line 4
  • Where on that line the problem is: the ^ points to the location
  • What type of error: SyntaxError
  • A helpful description: expected ':'

The problem is that if statements in Python must end with a colon (:). The correct code is:

python
# syntax_error1_fixed.py
# Fixed version
 
if 5 > 3:
    print("Five is greater than three")

Output:

Five is greater than three

Example 2: Mismatched Quotes

python
# syntax_error2.py
# Another syntax error example
 
message = "Hello, World!'
print(message)

Running this produces:

  File "syntax_error2.py", line 4
    message = "Hello, World!'
              ^
SyntaxError: unterminated string literal (detected at line 4)

The problem is that the string starts with a double quote (") but ends with a single quote ('). Python requires matching quotes. Fix it by using matching quotes:

python
# syntax_error2_fixed.py
# Fixed version
 
message = "Hello, World!"
print(message)

Output:

Hello, World!

1.5.3) Runtime Exceptions

Runtime exceptions (or just "exceptions") occur when your code is syntactically correct, but something goes wrong during execution.

Example 1: NameError

python
# name_error.py
# This code will cause a NameError
 
print(greeting)

When you run this:

bash
python name_error.py

You'll see:

Traceback (most recent call last):
  File "name_error.py", line 4, in <module>
    print(greeting)
          ^^^^^^^^
NameError: name 'greeting' is not defined

This is called a traceback. Let's break it down:

  • "Traceback (most recent call last):" indicates that what follows is a traceback showing where the error occurred.
  • File and line information: File "name_error.py", line 4, in <module> tells you which file and line caused the error.
  • The problematic code: print(greeting) shows the exact line that failed.
  • Error type: NameError tells you what kind of error occurred.
  • Error description: name 'greeting' is not defined explains the problem—you're trying to use a variable that doesn't exist.

To fix this, you need to define the variable before using it:

python
# name_error_fixed.py
# Fixed version
 
greeting = "Hello!"
print(greeting)

Output:

Hello!

Example 2: TypeError

python
# type_error.py
# This code will cause a TypeError
 
number = 5
text = "The number is "
result = text + number
print(result)

Running this produces:

Traceback (most recent call last):
  File "type_error.py", line 6, in <module>
    result = text + number
             ~~~~~^~~~~~~~
TypeError: can only concatenate str (not "int") to str

The error message tells you that you can't add (concatenate) a string and an integer directly. Python doesn't know whether you want to do mathematical addition or string concatenation.

To fix this, convert the number to a string:

python
# type_error_fixed.py
# Fixed version
 
number = 5
text = "The number is "
result = text + str(number)
print(result)

Output:

The number is 5

Example 3: ZeroDivisionError

What happens if you try to divide by zero?

python
# zero_division.py
# This code will cause a ZeroDivisionError
 
result = 10 / 0
print(result)

Running this produces:

Traceback (most recent call last):
  File "zero_division.py", line 4, in <module>
    result = 10 / 0
             ~~~^~~
ZeroDivisionError: division by zero

This error is self-explanatory: you can't divide by zero. It's mathematically undefined, so Python raises an error.

1.5.4) Reading Tracebacks Effectively

When you encounter a traceback, read it from bottom to top. We read from bottom to top because the bottom line shows what went wrong (the error type and message), while the lines above show the sequence of function calls that led to the error. For simple programs like ours, the bottom line tells you everything you need to know.

  1. Start at the bottom: Look at the error type and message first.
  2. Understand the error: What is Python telling you went wrong?
  3. Find the location: Look at the file and line number where the error occurred.
  4. Examine the code: Look at that line in your file.
  5. Trace backwards if needed: Sometimes the problem is actually on a line before the one Python points to.

1.5.5) Common Beginner Errors

Here are some errors you'll likely encounter as you learn Python:

Indentation Errors:

Python uses indentation (spaces or tabs at the beginning of lines) to define code blocks. Incorrect indentation causes errors:

python
# indentation_error.py
# Incorrect indentation
 
print("First line")
    print("Second line")  # This line is incorrectly indented

Error:

  File "indentation_error.py", line 5
    print("Second line")
    ^
IndentationError: unexpected indent

Spelling Mistakes:

Python is case-sensitive. Print is not the same as print:

python
# spelling_error.py
# Incorrect capitalization
 
Print("Hello")  # Should be print, not Print

Error:

Traceback (most recent call last):
  File "spelling_error.py", line 4, in <module>
    Print("Hello")
    ^^^^^
NameError: name 'Print' is not defined

Missing Parentheses:

In Python 3, print requires parentheses:

python
# missing_parentheses.py
# Missing parentheses
 
print "Hello"  # Should be print("Hello")

Error:

  File "missing_parentheses.py", line 4
    print "Hello"
          ^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

Notice how helpful Python's error message is here—it even suggests the fix!

1.5.6) Strategies for Dealing with Errors

When you encounter an error:

  1. Don't Panic: Errors are normal. Every programmer sees them constantly.

  2. Read the Error Message Carefully: Python's error messages are usually helpful. They tell you what went wrong and where.

  3. Check the Line Number: Go to the line Python indicates and look for the problem.

  4. Look at Nearby Lines: Sometimes the error is actually on the line before the one Python points to.

  5. Check for Common Mistakes: Missing colons, mismatched quotes, incorrect indentation, and typos are very common.

  6. Test Small Changes: Fix one thing at a time and test after each change.

  7. Use the REPL: If you're unsure about something, test it in the REPL first.

  8. Search for the Error: If you don't understand an error message, search for it online. You'll often find explanations and solutions.

1.5.7) A Complete Example with Error and Fix

Let's look at a script with multiple errors and fix them step by step. This program is designed to display information about a student and calculate their age in 10 years:

Original (with errors):

python
# buggy_student.py
# This program has several errors
 
student_name = "Alice
student_age = 25
 
print("Name:", student_name)
print("Age:" student_age)
print("In 10 years, you will be", student_age + "10")

Running this produces multiple errors. Let's fix them one by one:

Error 1: Unterminated string

  File "buggy_student.py", line 4
    student_name = "Alice
                   ^
SyntaxError: unterminated string literal (detected at line 4)

Fix: Add the closing quote:

python
student_name = "Alice"

After fixing Error 1, we get Error 2: Missing comma

  File "buggy_student.py", line 8
    print("Age:" student_age)
                 ^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

Fix: Add a comma between the string and variable:

python
print("Age:", student_age)

After fixing Error 2, we get Error 3: Type error

Traceback (most recent call last):
  File "buggy_student.py", line 9, in <module>
    print("In 10 years, you will be", student_age + "10")
                                      ~~~~~~~~~~~~^~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Fix: Convert "10" to an integer:

python
print("In 10 years, you will be", student_age + 10)

Final corrected version:

python
# buggy_student_fixed.py
# Fixed version of the program
 
student_name = "Alice"
student_age = 25
 
print("Name:", student_name)
print("Age:", student_age)
print("In 10 years, you will be", student_age + 10)

Output:

Name: Alice
Age: 25
In 10 years, you will be 35

This example demonstrates that fixing errors is often an iterative process. You fix one error, run the code again, and discover the next error. This is completely normal.

1.6) When to Use the Interactive Shell vs Script Files

Now that you've learned about both the REPL and script files, you might wonder when to use each. Both are valuable tools, and experienced Python programmers use both regularly. Understanding when to use each will make you more efficient.

1.6.1) Use the Interactive Shell (REPL) When:

1. Learning New Concepts

When you're learning something new, the REPL provides immediate feedback:

python
>>> # Testing string methods
>>> text = "hello world"
>>> text.upper()
'HELLO WORLD'
>>> text.title()
'Hello World'
>>> text.capitalize()
'Hello world'

You can experiment with different methods and see results instantly without creating files.

2. Testing Small Code Snippets

Before adding code to your program, test it in the REPL:

python
>>> # Testing a calculation
>>> price = 19.99
>>> quantity = 3
>>> total = price * quantity
>>> total
59.97
>>> # Looks good, now I can add this to my script

3. Quick Calculations

The REPL is always available as a calculator:

python
>>> # How many seconds in a day?
>>> 24 * 60 * 60
86400
>>> # What's 15% of 250?
>>> 250 * 0.15
37.5

4. Debugging

When your script isn't working, use the REPL to test individual parts:

python
>>> # My script isn't working. Let me test this part:
>>> numbers = [1, 2, 3, 4, 5]
>>> sum(numbers) / len(numbers)
3.0
>>> # This works, so the problem must be elsewhere

Note: We'll learn about lists in Chapter 13. This example shows how the REPL helps test code snippets.

1.6.2) Use Script Files When:

1. Writing Programs You Want to Keep

Anything you want to save and run again should be in a script file:

python
# temperature_converter.py
# A program to convert Fahrenheit to Celsius
 
fahrenheit = 98.6
celsius = (fahrenheit - 32) * 5/9
print("Temperature:", fahrenheit, "°F is", round(celsius, 1), "°C")

Output:

Temperature: 98.6 °F is 37.0 °C

You can run this script whenever you need it, and you can modify it later.

2. Writing Multi-Line Programs

While you can write multi-line code in the REPL, it's awkward for anything substantial. Use a script file:

python
# grade_calculator.py
# Calculate final grade from multiple scores
 
homework = 85
midterm = 78
final = 92
 
# Calculate weighted average
final_grade = (homework * 0.3) + (midterm * 0.3) + (final * 0.4)
 
print("Final Grade:", final_grade)

Output:

Final Grade: 85.3

3. Sharing Code with Others

Script files can be easily shared, while REPL sessions cannot:

python
# greeting.py
# A simple greeting program
 
name = input("What is your name? ")
print("Hello,", name + "! Welcome to Python.")

Note: We'll learn about the input() function in Chapter 2. This example shows how scripts can be shared.

You can send this file to someone else, and they can run it on their computer.

4. Building Reusable Tools

If you're creating something you'll use repeatedly, make it a script:

python
# file_counter.py
# Count files in a directory
 
import os
 
directory = "."  # Current directory
files = [f for f in os.listdir(directory) if os.path.isfile(f)]
print("Number of files:", len(files))

Note: We'll learn about importing modules in Chapter 22 and list comprehensions in Chapter 34. This example shows how scripts can be reusable tools.

5. Developing Complex Logic

For anything with multiple functions, classes, or complex logic, use script files:

python
# password_checker.py
# Check password strength
 
def check_password_strength(password):
    """Check if a password meets basic requirements."""
    if len(password) < 8:
        return "Too short"
    if not any(c.isupper() for c in password):
        return "Needs uppercase letter"
    if not any(c.isdigit() for c in password):
        return "Needs number"
    return "Strong password"
 
# Test the function
test_password = "MyPass123"
result = check_password_strength(test_password)
print("Password '" + test_password + "':", result)

Output:

Password 'MyPass123': Strong password

Note: We'll learn about functions in Chapter 19. This example shows how scripts handle complex logic.

6. Automating Tasks

Scripts are perfect for automation:

python
# backup_reminder.py
# Remind user to backup files
 
import datetime
 
today = datetime.date.today()
day_of_week = today.strftime("%A")
 
if day_of_week == "Friday":
    print("Don't forget to backup your files!")
else:
    print("Backup reminder: Next backup on Friday")

Note: We'll learn about the datetime module in Chapter 39. This example shows how scripts can automate tasks.

1.6.3) A Practical Workflow

Professional Python programmers typically use both the REPL and script files in a complementary way:

Example Workflow:

  1. Explore in REPL: Try out a new concept or test a calculation
  2. Prototype in REPL: Build a small working version
  3. Move to Script: Once it works, put it in a script file
  4. Expand in Script: Add more features, error handling, etc.
  5. Debug with REPL: If something breaks, test parts in the REPL
  6. Finalize Script: Complete, test, and save your program

1.6.4) A Concrete Example

Let's see this workflow in action. Suppose you want to write a program that calculates the area of a circle.

Step 1: Explore in REPL

python
>>> # What's the formula? Area = π * r²
>>> # Let me use a simple approximation for π
>>> 3.14159 * 5 * 5
78.53975
>>> # Looks right!

Step 2: Create a Script

Now that you know it works, create circle_area.py:

python
# circle_area.py
# Calculate the area of a circle
 
radius = 5
pi = 3.14159
area = pi * radius * radius
 
print("Radius:", radius)
print("Area:", area)

Output:

Radius: 5
Area: 78.53975

Step 3: Enhance the Script

Make it work with different radii:

python
# circle_area_enhanced.py
# Calculate area for multiple circles
 
radii = [3, 5, 7, 10]
pi = 3.14159
 
for radius in radii:
    area = pi * radius * radius
    print("Circle with radius", radius, "has area", round(area, 2))

Output:

Circle with radius 3 has area 28.27
Circle with radius 5 has area 78.54
Circle with radius 7 has area 153.94
Circle with radius 10 has area 314.16

Note: We'll learn about for loops in Chapter 11. In Chapter 2, we'll learn how to make this interactive by getting input from the user.

This workflow—experiment in REPL, then formalize in a script—is how many Python programs are developed.

1.6.5) Key Takeaways

REPL Strengths:

  • Immediate feedback
  • Great for learning
  • Perfect for quick tests
  • Excellent for exploration
  • No file management needed

REPL Limitations:

  • Code is not saved
  • Awkward for multi-line code
  • Can't be shared easily
  • Not suitable for complex programs

Script File Strengths:

  • Code is saved permanently
  • Easy to edit and modify
  • Can be shared with others
  • Suitable for complex programs
  • Can be run repeatedly
  • Can be automated

Script File Limitations:

  • Requires creating and managing files
  • Need to run to see results
  • More overhead for quick tests

The best approach is to use both: the REPL for learning, testing, and exploration, and script files for anything you want to keep, share, or run repeatedly.

1.7) Which Python Version This Book Uses (and Why It Matters)

Python has evolved significantly over the years, and different versions can behave differently. Understanding Python versions will help you avoid confusion and ensure your code works as expected.

You might wonder why we're spending time on Python versions. The reason is simple: you'll encounter Python code online, in tutorials, and in documentation. Understanding versions helps you recognize when code is outdated and avoid confusion when something doesn't work as expected.

1.7.1) Python 2 vs Python 3

The most significant divide in Python's history is between Python 2 and Python 3.

Python 2 was released in 2000 and was the dominant version for many years. However, it had some design issues that couldn't be fixed without breaking existing code.

Python 3 was released in 2008 as a major redesign that fixed these issues. However, it was not backward compatible with Python 2, meaning code written for Python 2 often wouldn't run in Python 3 without modifications.

For many years, both versions coexisted. However, Python 2 reached end-of-life on January 1, 2020. This means:

  • No more updates or security patches for Python 2
  • All new Python development uses Python 3
  • All major libraries have moved to Python 3
  • Learning Python 2 today is not recommended

This book uses Python 3 exclusively. All code examples are written for Python 3 and may not work in Python 2.

1.7.2) Python 3 Minor Versions

Within Python 3, there are minor versions (3.6, 3.7, 3.8, 3.9, 3.10, 3.11, 3.12, etc.). Each minor version adds new features and improvements while maintaining backward compatibility with previous Python 3 versions.

This book is written for Python 3.11 and later, but most examples will work on Python 3.8 and above.

To check your Python version:

bash
python --version  # Windows
python3 --version  # macOS/Linux

You should see something like:

Python 3.11.5

If you see:

Python 2.7.18

You're running Python 2, which is outdated. Install Python 3 following the instructions in Section 1.2.

1.7.3) Key Differences You Might Encounter

If you're reading older Python tutorials or code online (especially in older tutorials and Stack Overflow answers from before 2020), you might see syntax that doesn't work in Python 3. Here are the most common differences:

1. The print Statement vs Function

Python 2:

python
print "Hello, World!"  # No parentheses

Python 3:

python
print("Hello, World!")  # Parentheses required

In Python 3, print is a function and requires parentheses. This is the most visible difference.

2. Division Behavior

These changes were made to make Python more consistent and safer. For example, making print a function allows it to be used like any other function, and making / always do float division eliminates a common source of bugs.

Python 2:

python
>>> 5 / 2
2  # Integer division
>>> 5.0 / 2
2.5  # Float division

Python 3:

python
>>> 5 / 2
2.5  # Always float division
>>> 5 // 2
2  # Integer division (floor division)

In Python 3, / always performs float division. Use // for integer division.

3. input() Function

Python 2:

python
name = raw_input("Enter your name: ")  # Returns string
age = input("Enter your age: ")  # Evaluates input as Python code (dangerous!)

Python 3:

python
name = input("Enter your name: ")  # Always returns string
age = int(input("Enter your age: "))  # Convert to int if needed

In Python 3, input() always returns a string, which is safer and more consistent.

4. String and Unicode

Python 3 handles text (Unicode) much better than Python 2. All strings in Python 3 are Unicode by default, making international text handling much easier.

1.7.4) Features by Python 3 Version

Different Python 3 versions introduced different features. Here's what you need to know:

Python 3.6 (December 2016):

  • f-strings for string formatting (we'll use these extensively)
python
# f_string_example.py
name = "Alice"
print("Hello, " + name + "!")

Output:

Hello, Alice!

Note: We'll learn about f-strings in Chapter 6. For now, we're using simple string concatenation with +.

Python 3.8 (October 2019):

  • The walrus operator (:=) for assignment expressions (we'll cover this in Chapter 40)

Python 3.10 (October 2021):

  • Structural pattern matching with match and case (we'll cover this in Chapter 12)

Python 3.11 (October 2022):

  • Significantly improved error messages
  • Better performance
  • Enhanced exception handling

Python 3.12 (October 2023):

  • Further performance improvements
  • New type annotation features
  • Improved f-string syntax

1.7.5) Which Version Should You Use?

Recommendation: Use Python 3.11 or later if possible. Here's why:

  1. Better Error Messages: Python 3.11 has significantly improved error messages that are more helpful for beginners.

  2. Better Performance: Python 3.11 is faster than earlier versions.

  3. Modern Features: You'll have access to all the latest Python features.

  4. Future-Proof: Code written for Python 3.11 will work in future versions.

However, any Python 3.8 or later will work fine for learning from this book. The core concepts remain the same.

1.7.6) Checking Feature Availability

If you're using an older Python version and encounter code that doesn't work, you can check which version introduced a feature.

For example, if you're using Python 3.5 or earlier, you might need to use older string formatting:

python
# format_example.py
# Works in all Python 3 versions
name = "Alice"
print("Hello, {}!".format(name))

Output:

Hello, Alice!

1.7.7) Staying Current

Python releases a new minor version approximately once a year. While you don't need to upgrade immediately, it's good to stay reasonably current:

  • Check for updates every few months
  • Read release notes to learn about new features
  • Upgrade when convenient, especially for security updates
  • Test your code after upgrading to ensure compatibility

You can find Python releases and documentation at https://www.python.org/.

1.7.8) Version Compatibility in This Book

Throughout this book:

  • All code examples work in Python 3.11+
  • Most examples work in Python 3.8+
  • Version-specific features are clearly noted (e.g., "This requires Python 3.10+")
  • Alternative approaches are provided when appropriate for older versions

When you see code in this book, you can confidently type it into Python 3.11 or later and expect it to work exactly as shown.

1.7.9) A Note on Python 2 Code You Might Find Online

If you're searching for Python help online, you might encounter Python 2 code. Here's how to recognize it:

Signs of Python 2 Code:

  • print without parentheses: print "Hello"
  • raw_input() function
  • Division that produces integers: 5 / 2 equals 2
  • Older string formatting: "Hello %s" % name
  • Comments saying "Python 2" or mentioning version 2.x

What to Do:

  • Look for Python 3 alternatives
  • Add "python 3" to your searches
  • Check the date—anything before 2020 might be Python 2
  • Use official Python 3 documentation: https://docs.python.org/3/

Congratulations! You've completed Chapter 1 and taken your first steps with Python. You now know:

  • What Python is and how it works
  • How to install Python and run the interpreter
  • How to use the Python interactive shell (REPL) for experimentation
  • How to create and run Python script files
  • How to read and understand error messages and tracebacks
  • When to use the REPL versus script files
  • Which Python version to use and why it matters

You're now ready to move on to Chapter 2, where you'll write your first complete Python programs, learn about the print() function in detail, and start working with user input. The foundation you've built in this chapter will support everything you learn going forward.

© 2025. Primesoft Co., Ltd.
support@primesoft.ai