Your first program¶
Goal: write a Python program, save it as a file, and run it from the terminal.
The tradition¶
Programmers have a tradition: the first program you write in a new language prints the words Hello, World! on the screen. Let's keep the tradition alive.
Step 1: Create a file¶
- Make a folder somewhere easy to find, for example
python-coursein your Documents. - Open that folder in Visual Studio Code (File → Open Folder).
- Create a new file called
hello.py. The.pyending tells everyone this is a Python file.
Step 2: Type the program¶
Type this into the file exactly as shown, then save it:
That is the whole program. One line.
Step 3: Run it¶
Open a terminal inside the folder. In Visual Studio Code, use Terminal → New Terminal. Then type:
On macOS or Linux, use python3 hello.py. You should see:
Congratulations. You are now a programmer.
What just happened?¶
Let's read the line piece by piece.
printis a function. A function is a named action Python knows how to do.printshows text on the screen.- The parentheses
( )mean "run this function". Whatever is inside them is what the function works on. "Hello, World!"is a string: a piece of text. The quotation marks tell Python where the text starts and ends. The quotes themselves are not printed.
Try it¶
Change the message and run the file again. Then try printing more than one line:
Each print produces one line of output, in order from top to bottom.
Common mistakes¶
SyntaxError: unterminated string literal
You forgot a closing quotation mark. Every opening " needs a matching closing ".
NameError: name 'Print' is not defined
Python is case-sensitive. Print and print are different words, and only the lowercase one exists.
python: can't open file 'hello.py'
Your terminal is in a different folder than your file. Use cd to move into the folder where you saved it.
Exercises¶
- Introduce yourself. Write a program that prints three lines: your name, your city, and one thing you want to build with Python.
-
Make a shape. Print a triangle using asterisks, like this:
-
Fix the bug. This program has two mistakes. Find and fix them without running it first, then run it to check.
Solution 1
Solution 3
The two mistakes were a capital P in Print, and a missing closing quotation mark.
Summary¶
- A Python program is a plain text file ending in
.py. - You run it from the terminal with
python filename.py. print("text")shows text on the screen.- Python is case-sensitive, and every quote needs a partner.