Read the first chapter
The whole of chapter one, free. About 12 min. Turn the pages with the arrows, your keyboard, or a swipe.
Chapter 1
Python Setup and First Programs
Getting Python Ready to Run
A blank terminal becomes useful the moment it prints a Python prompt. From there, you can test an idea in seconds, save a complete program in a file, and run that program whenever you need it. Setting up this small working environment is the first practical step toward writing Python with confidence.
You will install Python, choose an editor for writing code, learn the difference between the interactive interpreter and a script, and see how Python starts executing instructions. These choices matter because a clear setup makes errors easier to understand. They also connect the ideas from earlier discussions of instructions and programs to something you can run on your own computer.
Learning Objectives
• Install and check a current version of Python.
• Choose an editor and create a Python script.
• Use the interactive interpreter and explain how a script begins running.
The tools used here are free: Python from python.org, the built-in IDLE editor, or an editor such as Visual Studio Code. By the end, you should be able to type one line, save several lines, and recognize whether Python is waiting for an instruction or running a saved file.
Python, Editors, Scripts, and the Interpreter
Python - a programming language and the program that reads and runs Python instructions. When people say “install Python,” they usually mean installing the Python interpreter along with useful tools.
Interpreter - a program that reads Python code and carries out its instructions. Python normally processes a program from top to bottom, beginning with the first instruction that can run.
Editor - a program used to write and save text, including Python code. A programming editor can color keywords, show matching brackets, and point out some mistakes.
Script - a file containing Python instructions, usually saved with the.py file ending. For example, temperature.py is a Python script.
Interactive interpreter - a mode where you type one instruction, press Enter, and immediately see the result. It is also called the Python shell or the REPL. REPL means “Read-Evaluate-Print Loop”: Python reads your input, evaluates it, prints a result when appropriate, and waits again.
Download Python from the official Python website, python.org. Choose the current stable release for your operating system. On Windows, the installer includes an important option named “Add Python to PATH.” Select it before choosing the installation button. PATH is a list of folders that tells your operating system where to find commands. If Python is added to PATH, you can type python in a terminal and start it directly.
On macOS or Linux, Python 3 is often available as the command python3. The number 3 matters because Python 2, an older version, is no longer the normal choice for new programs. After installation, open a terminal and check the version:
python --version If that command does not work on macOS or Linux, try:
python3 --version A successful response might look like Python 3.12.4. The exact minor version may differ. The important result is that the first number is 3.
An editor should make code easy to read and save. IDLE is installed with many Python distributions and is suitable for simple practice. Visual Studio Code is another popular choice; after installing it, add its official Python extension. Avoid writing Python in a word processor because word processors may insert hidden formatting and curly quotation marks. A plain text editor can work, but an editor made for code usually provides better help.
The interactive interpreter is useful for small experiments:
>>> 4 + 6 10 >>> print("Python is running") Python is running The three greater-than signs, >>>, are the prompt. They are not part of the instruction you type. After Python displays 10, it shows another prompt and waits. The expression 4 + 6 produces a value, so the interpreter displays it. The print() instruction displays text explicitly.
A script behaves differently because its instructions are saved first. Create a file named first_program.py with this content:
print("Python is running from a file.") print("The second instruction comes next.") Save it, then run it from the folder containing the file. On Windows, use:
python first_program.py On macOS or Linux, use:
python3 first_program.py Python reads the first print() instruction, displays its message, then reads and runs the second. When it reaches the end of the file, the program stops. There is no >>> prompt inside a script because the file is not waiting for one instruction at a time.
This difference is worth checking: the interpreter is a workbench for quick tests, while a script is a saved set of instructions. You might test 12 * 8 interactively, then save a useful calculation in weekly_total.py so it can be run again.
Indentation also affects how Python begins and groups instructions. For now, keep the first programs left-aligned:
print("First") print("Second") A line beginning with an unexpected space can cause an IndentationError. Later, indentation will show which instructions belong inside a decision or loop. At this stage, it is enough to notice that spaces at the start of a line can have meaning.
If Python reports SyntaxError, it could not understand the structure of an instruction. If it reports that a file cannot be found, the terminal is probably looking in a different folder from the one containing your script. Read the message carefully, check the file name, and run the version command again if you are unsure which Python installation is active.
The practical takeaway is simple: use the interpreter to ask small questions, use an editor to save programs, and use the terminal to run those programs deliberately.
A First Program from File to Output
Suppose the goal is to create a short program that reports the number of items in a stock box. The program should display a label and calculate the final count from two known numbers. This example shows the complete path from editing to execution.
• Decide on the data. The box contains 18 small items and 7 larger items. The expected total is 25.
• Open IDLE, Visual Studio Code, or another code editor. Create a new file named stock_count.py. The.py ending tells you and your tools that the file contains Python code.
• Type the instructions exactly as shown:
small_items = 18 large_items = 7 total_items = small_items + large_items
print("Stock count") print(total_items) • Read the program before running it. The first line stores 18 under the name small_items. The second stores 7 under large_items. The third adds those two stored values and places the result in total_items.
• Notice the blank line. It does not perform an action, but it separates the calculation from the output and makes the program easier to scan.
• Save the file. If the editor asks for a file type, choose a normal text file or Python file, not a rich-text document. Confirm that the name ends in.py, not.py.txt.
• Open a terminal in the folder containing stock_count.py. Run the appropriate command:
python stock_count.py or:
python3 stock_count.py • Compare the output with the expected result. Python first creates the three names and then runs the two print() instructions. The screen should show:
Stock count 25 Final result: the program reports a total of 25 items.
• Test one part interactively. Start Python and enter:
>>> 18 + 7 25 This confirms the arithmetic separately from the saved program. The interactive test does not change the script; it is simply a quick check.
• Change large_items = 7 to large_items = 9, save the file, and run it again. The new output should end with 27. This shows why saving a script is useful: you can change one value and repeat the complete process.
The order matters. Python does not calculate total_items before it has values for small_items and large_items. If you moved the third line to the top, Python would not know what those names meant yet. Programs begin at the first runnable line and normally proceed downward, so the arrangement of instructions affects the result.
Ask yourself what would happen if the final two lines were placed before the calculation. The answer is that Python would try to print total_items before creating it, producing a NameError. That message means Python found a name it does not recognize at that point.
The practical takeaway is that running a program is a chain: create a correctly named file, write instructions in a workable order, save it in a known folder, run the matching command, and compare the output with a reasoned prediction.
Practice and Answer Key
• Which command would you try first to check Python on Windows, and which alternative is common on macOS or Linux?
Hint: The command includes the word version, and macOS or Linux often distinguishes Python 3 with a number.
• What is the difference between entering 5 5 in the interactive interpreter and saving print(5 5) in a script?
Hint: One responds immediately to a single entry; the other can be saved and run again.
• A file named greeting.py contains print("Good morning"). What should appear when you run it successfully?
Hint: print() displays the text between its quotation marks.
• Why must total = first + second come after instructions that give values to first and second?
Hint: Python normally begins at the top and cannot use an unknown name.
• You run python report.py and receive a message saying the file cannot be found. What should you check?
Hint: Check the spelling,.py ending, and terminal folder.
Answer Key: For question 1, use python --version; python3 --version is a common alternative. For question 2, the interpreter gives an immediate response, while the script stores instructions for repeated execution. For question 3, the output is Good morning. For question 4, the names must have values before Python can add them. For question 5, check that the terminal is in the folder containing the correctly named file.
A working Python setup is more than an installation check. It gives you two ways to think: experiment briefly at the prompt, then save a clear sequence in a script. Once you can move comfortably between those two places, your programs have a reliable starting point.
What "continue to intermediate and advanced Python" covers and why it matters
You’ll build on the basics you’ve already practiced - running scripts, using the interpreter, and organizing simple calculations - and move toward the patterns and tools that make real projects manageable. That means learning how to structure code so it’s readable and reusable, using Python features that handle complexity for you, and choosing small, reliable libraries that avoid reinventing the wheel. These skills matter because projects that start small often grow: knowing how to scale from a few lines to dozens or hundreds of lines without chaos is what separates one-off scripts from maintainable programs. Keep a practical mindset: you’ll apply each concept to concrete code you can run and test, and you’ll learn to spot when a technique will actually save time.
Learning Objectives
• Understand intermediate features: modular code, exceptions, and useful built-ins.
• Use advanced patterns: generators, context managers, and basic decorators.
• Apply a small standard library toolset (pathlib, itertools, collections) to real tasks.
You’ve got this - these are the tools you’ll reach for when the next step feels messy, and the payoff is code that’s easier to change or hand off.
Core intermediate and advanced concepts, defined and demonstrated
Modular code - splitting a program into functions and modules so parts can be tested and reused. For example, put a stock-counting function in stock.py and import it from different scripts.
Exception handling - a way to catch and respond to runtime problems without crashing. Using try/except lets you try to open a file and give a friendly message if it’s missing.
Generator - a function that yields values one at a time, useful when working with large sequences. A generator that yields lines from a huge log file avoids loading everything into memory.
Context manager - a protocol that ensures setup and teardown happen together, most commonly used via with. For example, with open('data.csv') as f: ensures the file is closed even if something fails.
Decorator - a callable that wraps another function to extend behavior. A timing decorator can measure how long a function takes without changing its code.
Pathlib - a modern way to work with filesystem paths as objects (Path('reports') / '2026.csv'). It reduces string manipulation mistakes.
itertools and collections - small, high-value modules; itertools.chain can join iterables efficiently, and collections.Counter quickly tallies occurrences.
Concrete example snippet (explain): a function that reads numeric lines, ignores invalid entries with exceptions, and yields valid integers using a generator. That pairs try/except with yield to make a resilient, memory-light pipeline.
Step-by-step worked example: a resilient log processor that sums values
• Goal: sum integer values found in a large log file while skipping bad lines and keeping memory use low. You want a robust tool you can reuse across files.
• Decide structure: one module with a generator to yield valid ints, a function to sum them, and exception handling for file errors.
• Key steps you’d write and test:
• Use pathlib to get the file path: path = Path('logs') / 'today.log'.
• Open the file with a context manager: with path.open('r', encoding='utf-8') as fh:.
• For each line, try to convert to int inside a try/except block; on ValueError, continue to the next line.
• Yield valid integers from a generator function so the caller can decide whether to sum, average, or stream elsewhere.
• In the summing function, call sum(generator(path)) so only one line is in memory at a time.
• Add top-level error handling: if the file isn’t found, catch FileNotFoundError and return 0 with a friendly message.
• Running this on a 2 GB log will keep memory small, skip corrupted lines, and still produce the total you expect.
Final result: the program returns the correct integer sum while tolerating missing or malformed lines - robust, memory-efficient, and reusable. Nice work - you’ve built a small tool that scales.
Practice questions and answer key
• Write a generator that yields only even integers from a text file, skipping non-integer lines. Hint: use try/except around int(line) and check value % 2 == 0.
• Explain when to use a context manager instead of open(...) without with. Hint: think about exceptions and ensuring cleanup (like closing files).
• Create a simple decorator that logs function entry and exit times to the console. Hint: wrap the function, call it, and print before and after.
• When would collections.Counter be faster or simpler than a plain dict for counting words? Hint: Counter gives one-liners for most tally tasks.
Answer Key: 1) The generator uses with Path(...).open() and yields int values when parse succeeds and value % 2 == 0. 2) Use a context manager whenever resources must be reliably released; with handles cleanup even on errors. 3) The decorator returns an inner function that prints before calling the wrapped function and after, preserving args/kwargs. 4) Counter supplies direct tallying methods and simplifies common patterns, avoiding boilerplate checks for key existence.
You’re moving from writing working scripts to building reliable tools. Practice the patterns above on small real files - each time you’ll make future code easier to read, test, and extend. You’ve got this.
End of chapter one. 4 more chapters and about 8,460 words in the full book.
Swipe or use the arrows to turn the page
What's inside: 5 chapters
- 1. Python Setup and First Programs
- 2. Variables, Types, and Expressions
- 3. Conditionals and Loops
- 4. Functions and Data Collections
- 5. Files, Errors, and Object-Oriented Python
About this book
"Python From The Ground Up" is a education book by Its Me with 5 chapters and approximately 8,460 words. Foundational Python programming concepts and practical coding knowledge.
This book was created using Inkfluence AI, an AI-powered book generation platform that helps authors write, design, and publish complete books. It was made with the AI Lesson Plan Generator.
Frequently Asked Questions
What is "Python From The Ground Up" about?
Foundational Python programming concepts and practical coding knowledge
How many chapters are in "Python From The Ground Up"?
The book contains 5 chapters and approximately 8,460 words. Topics covered include Python Setup and First Programs, Variables, Types, and Expressions, Conditionals and Loops, Functions and Data Collections, and more.
Who wrote "Python From The Ground Up"?
This book was written by Its Me and created using Inkfluence AI, an AI book generation platform that helps authors write, design, and publish books.
How can I create a similar education book?
You can create your own education book using Inkfluence AI. Describe your idea, choose your style, and the AI writes the full book for you. It's free to start.
Write your own education book with AI
Describe your idea and Inkfluence writes the whole thing. Free to start.
Start writingCreated with Inkfluence AI