Write Your First Python Program
Now that you have installed Python, it’s time to write your first program! Don't worry; it’s very simple, and we'll explain every step so you can understand what’s happening.
Step 1: Open Python
To start, open Python on your system. Here's how you can do it:
- Windows: Open the Command Prompt and type
python
, then press Enter. - macOS/Linux: Open the Terminal and type
python3
, then press Enter. - You’ll see something like this:
Python 3.x.x ... Type "help", "copyright", "credits" or "license" for more information. >>>
Step 2: Write the Program
Type the following line of code into the Python interactive shell (where you see >>>
):
print("Hello, World!")
Press Enter, and you will see this output:
Hello, World!
Step 3: What Does This Program Do?
Let’s break it down to understand what’s happening:
- print: This is a built-in function in Python. It tells Python to display something on the screen.
- "Hello, World!": The text inside the quotation marks is called a string. Strings are sequences of characters enclosed in quotes.
- print("Hello, World!"): This command prints the given string to the screen.
- Output: When you run the program, Python shows
Hello, World!
on the screen. This is the result of theprint
function.
Step 4: Save and Run the Program from a File
Instead of typing code directly into the Python shell, you can write your program in a file and run it. Follow these steps:
- Open any text editor (like Notepad, VS Code, or PyCharm).
- Type the following line of code:
print("Hello, World!")
. - Save the file with a .py extension. For example, save it as hello.py.
- Run the program:
- Windows: Open Command Prompt, navigate to the file's location, and type:
python hello.py
(If this doesn't work, trypython3 hello.py
.) - macOS/Linux: Open Terminal, navigate to the file's location, and type:
python3 hello.py
(If Python 3 is the default, you can usepython hello.py
.)
- Windows: Open Command Prompt, navigate to the file's location, and type:
- You’ll see the output
Hello, World!
on the screen.
Why "Hello, World!"?
The phrase "Hello, World!" is a tradition in programming. It is often the first program beginners write when they learn a new programming language. It’s a simple way to confirm that everything is set up correctly and working as expected.
Congratulations!
You’ve just written and run your first Python program! This is your first step into the world of programming. From here, you can explore more complex tasks and learn new concepts. Keep experimenting and practicing to become a Python pro!