Your First Program!
This is it. You have installed Python and set up your smart notebook (VS Code). Now it is time to write your first line of code and give your computer its first instruction.
1. Create a Python File
- In VS Code, look at your
Python_Learningfolder on the left side. - Click the New File icon (it looks like a piece of paper with a
+symbol). - Name your file
hello.pyand press Enter.
Why the
.py? The.pyat the end is very important! Just like a photo ends in.jpgand music ends in.mp3, putting.pytells your computer: "Hey, this is a Python file!"
2. Write Your Code
Click inside your empty hello.py file and type exactly this:
print("Hello, World!")
What does this line mean?
The print() instruction tells the computer to take whatever is inside the quotation marks "" and show it on the screen. It is your way of making the computer talk to you!
3. Run Your Code
Now we need to tell Python to read our file and run our instruction.
- At the very top of VS Code, click Terminal -> New Terminal. A small black box will appear at the bottom of your screen.
- Click inside that black box, type this command exactly, and press Enter:
python hello.py
🎉 CONGRATULATIONS! 🎉
Look at the black box (terminal) at the bottom. Did it print Hello, World!?
If yes, you just successfully wrote and executed your first piece of software. You are officially a programmer!
Common Mistakes
If it did not work, don't panic! Making mistakes is 90% of a programmer's job. Check for these common beginner errors:
Did you use a capital P?
Python is very sensitive! Print("Hello") with a capital P will fail. It must be a lowercase print.
Did you forget the quotation marks?
print(Hello, World!) will fail. You must wrap the text in quotes "" so Python knows it is text.
Did you forget to save the file?
If you see a white dot next to your file name hello.py at the top of VS Code, it means you forgot to save! Press Ctrl + S (or Cmd + S on Mac) to save the file, then try running the command again.
4. Notes for Yourself (Comments)
As you start writing more code, you might want to leave notes for yourself or other programmers explaining what the code does. You can do this using Comments.
In Python, anything that comes after a hash symbol # is completely ignored by the computer. It is just text for humans to read!
# This is a comment. The computer will ignore this line.
print("Hello!") # You can also put comments at the end of a line
Practice Exercises
Try changing the code in your file to complete these small tasks. Don't forget to save (Ctrl + S) and run the python hello.py command in the terminal to see your changes!
# Task 1: Make the computer print your own name
print("My name is Rahul")
# Task 2: Print a math calculation! (Notice there are no quotes for math)
print(10 + 5)
What's Next?
Now that you know how to give the computer basic instructions, let's learn how to make the computer remember things using Variables in the next module!