Python Example
First Python Program
1. Writing the Code
Create a file called hello_world.py
(the.py
extension designates it as a Python file).
# This is a comment. Python doesn't look at comments, but they explain your code so nicely.
# Prints a message on the console as well.
print("Hello, World!")
2. Explanation of Code
1. Comments (# This is a comment)
:
- Comments are not read by Python.
- Use comments to explain what your code does. They start with a #.
2. The print()
function:
print()
is a native Python built-in function that prints outputs to your screen.- The text that you want to print is in double quotes or single quotes (
"
or'
).
3. The Message ("Hello, World!")
:
"Hello, World!"
is a string-that is, a sequence of characters written between quotes.- This is the output of a program.
3. Running the Code
Once you have written the code, follow these steps to execute it:
On Your Computer
- Open terminal or command prompt.
- Change to the directory where your Python file is saved.
- Type the following command and then press ENTER:
python hello_world.py
Or if you are using Python 3:
python3 hello_world.py
Output:
You must be seeing the following on your computer screen:
Hello, World!
4. Key Concepts for Extreme Beginners
Syntax:
- The syntax of Python is very simple, and human-readable, so it becomes easy to learn for beginners.
Indentation:
- Python uses identation (spaces or tabs) to define blocks of code.
Error messages:
- If anywhere goes wrong (for example, a single quotation misses), the respective error message will be shown by Python and it can help you to debug.
5. Experimentation
Go ahead and modify it in the following way:
- Change the message:
print("Welcome to Python!")
- Add another line:
print("Learning Python is fun!")