Chapter 1. Python Basics
Many books and online tutorials about Python show you how to execute code in the Python shell. To run Python code in this way, you’ll open a Command Prompt window (in Windows) or a Terminal window (in macOS) and type “python” to get a Python prompt (which looks like >>>). Then simply type your commands one at a time; Python will execute them.
Here are two typical examples:
>>> 4 + 5
9
>>> print("I'm excited to learn Python.")
I'm excited to learn Python.
This method of executing code is fast and fun, but it doesn’t scale well as the number of lines of code grows. When what you want to accomplish requires many lines of code, it is easier to write all of the code in a text file as a Python script, and then run the script. The following section shows you how to create a Python script.
How to Create a Python Script
To create a Python script:
-
Open the Spyder IDE or a text editor (e.g., Notepad, Notepad++, or Sublime Text on Windows; TextMate, TextWrangler, or Sublime Text on macOS).
-
Write the following two lines of code in the text file:
#!/usr/bin/env python3print("Output #1: I'm excited to learn Python.")The first line is a special line called the shebang, which you should always include as the very first line in your Python scripts. Notice that the first character is the pound or hash character (
#). The#precedes a single-line comment, so the line of code isn’t read or executed on a Windows computer. However, Unix computers use the line to find ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access