Your First Python Program
The tradition of writing a "Hello, World!" program dates back to 1972 when Brian Kernighan used it in a tutorial on the B programming language. It has since become the universal first step for learning any new programming language.
In Python 3, the entire program is a single line:
print("Hello, World!")
That's it. One function call, one string, one line. Contrast this with Java or C++, where the same program requires 5β10 lines of boilerplate code. This simplicity is one of the biggest reasons Python is the top choice for beginners.
In Python 2 (now obsolete), print was a statement: print "Hello". In Python 3, it is a function and requires parentheses: print("Hello"). Always use Python 3.
Understanding the print() Function
The print() function is one of Python's most-used built-in functions. It sends output to the console (your screen). Understanding all of its capabilities will make your programs much more readable and useful.
Basic print() Usage
# Printing different types of data
print("Hello, World!") # string
print(42) # integer
print(3.14) # float
print(True) # boolean
# Printing nothing (blank line)
print()
# Printing multiple items separated by a space
print("Name:", "Alice")
print("Age:", 25)
print("Score:", 98.5)
The sep and end Parameters
The print() function has two optional parameters that control how output is formatted: sep (separator between items) and end (what to print at the end of the line).
# sep: changes the separator between values (default is a space)
print("Python", "is", "awesome") # Python is awesome
print("Python", "is", "awesome", sep="-") # Python-is-awesome
print("Python", "is", "awesome", sep="") # Pythonisawesome
print(2024, 12, 25, sep="/") # 2024/12/25
# end: changes what is printed at the end (default is newline \n)
print("Hello", end=" ")
print("World") # Hello World (on one line)
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".") # Loading...
Running Python Scripts
There are three main ways to run Python code. Each has its use case, and professional developers use all three depending on the situation.
| Method | Best For | How To |
|---|---|---|
| Interactive Shell (REPL) | Quick experiments, testing snippets | Type python3 in terminal, then write code |
| Script File (.py) | Real programs, saving your work | Save file as hello.py, run with python3 hello.py |
| IDLE Editor | Beginners, simple editing | Open IDLE, write code, press F5 to run |
| VS Code / PyCharm | Full projects, professional work | Open project folder, use built-in terminal |
Running from the Command Line
# Step 1: Create a file named hello.py
# Step 2: Add your code to the file
# Step 3: Run it from the terminal
python3 hello.py
# On Windows, you might use:
python hello.py
Python script files must end with .py. Avoid spaces in filenames β use underscores instead: hello_world.py not hello world.py. Never name a file the same as a built-in module (e.g., don't name your file math.py or random.py).
Using Python IDLE
IDLE (Integrated Development and Learning Environment) is Python's built-in editor. It comes with every Python installation and is a great tool for beginners.
IDLE has two modes:
- Shell mode: The interactive window where you can type and run code one line at a time. Great for testing.
- Editor mode: A full text editor where you write scripts and save them as
.pyfiles. Use File β New File to open one.
To run a script in IDLE: open the editor, write your code, save it (Ctrl+S), then press F5 or go to Run β Run Module.
F5 β Run the current script. Alt+P / Alt+N β Navigate previous/next commands in the shell. Ctrl+Z β Undo. Ctrl+] / Ctrl+[ β Indent / dedent selected lines.
Python Comments
Comments are lines in your code that Python ignores. They exist for humans β to explain what the code does, why a decision was made, or to temporarily disable code. Writing good comments is a core programming skill.
Single-Line Comments
Use the # symbol. Everything after # on that line is ignored by Python.
# This is a full-line comment
print("Hello, World!") # This is an inline comment
# You can use comments to explain complex logic:
# Multiply speed by time to get distance
distance = 60 * 2.5 # speed=60 km/h, time=2.5 hours
print(distance) # 150.0
# Use comments to temporarily disable code during debugging:
# print("This line won't run")
print("This line will run")
Multi-Line Comments and Docstrings
Python doesn't have a true multi-line comment syntax. The common practice is to use multiple # lines. However, you can also use triple-quoted strings (which become docstrings when placed at the start of a function or file).
# Method 1: Multiple single-line comments
# This program calculates the area of a rectangle
# Author: Alice
# Date: 2024-01-15
# Method 2: Triple-quoted string (used as a block comment)
"""
This program demonstrates basic Python output.
It uses the print() function to display messages.
Triple quotes can span multiple lines.
"""
# Docstring at the start of a function:
def greet(name):
"""Return a greeting message for the given name."""
return f"Hello, {name}!"
print(greet("Alice")) # Hello, Alice!
A bad comment just repeats the code: # add 1 to x above x += 1. A good comment explains the why: # compensate for zero-based index above x += 1. Write comments that add value.
Formatting Print Output
Beyond basic printing, Python gives you several powerful ways to format your output. These become essential as your programs grow.
name = "Alice"
age = 25
score = 98.765
# Method 1: Concatenation (joining strings with +)
print("Name: " + name + ", Age: " + str(age))
# Method 2: % formatting (older style)
print("Name: %s, Age: %d" % (name, age))
# Method 3: str.format() method
print("Name: {}, Age: {}".format(name, age))
# Method 4: f-strings (RECOMMENDED β modern and readable)
print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.2f}") # limit to 2 decimal places β 98.77
print(f"Age next year: {age + 1}") # expressions work inside {}
Escape Characters in Strings
Sometimes you need to include special characters inside a string β a newline, a tab, or a quote character itself. Use escape sequences starting with a backslash \.
# \n = newline
print("Line 1\nLine 2\nLine 3")
# \t = tab
print("Name:\tAlice")
print("Age:\t25")
# \\ = literal backslash
print("C:\\Users\\Alice\\Documents")
# \" and \' = quotes inside strings
print("She said \"Hello!\"")
print('It\'s a great day!')
# Raw strings (r prefix) β backslashes are literal
print(r"C:\Users\Alice\no_escape_here")
Common Beginner Errors
When you first start writing Python, you'll encounter a few errors repeatedly. Knowing what they mean helps you fix them fast.
# SyntaxError: Missing parentheses
# print "Hello" β Python 2 style, fails in Python 3
# SyntaxError: Missing closing quote
# print("Hello) β string not closed
# NameError: Calling a function with wrong capitalization
# Print("Hello") β Python is case-sensitive; it's print(), not Print()
# TypeError: Mixing string and number without conversion
# print("Age: " + 25) β Cannot concatenate str and int
# β
Fix for TypeError:
print("Age: " + str(25)) # convert int to string first
print(f"Age: {25}") # or use f-string (handles it automatically)
Trying to concatenate a string and a number with + causes a TypeError: can only concatenate str (not "int") to str. Always use f-strings or convert with str().
Building on Hello World
Let's write a few slightly more complex programs to solidify the concepts from this lesson.
# Program 1: Personal introduction
name = "Alice"
age = 25
city = "New York"
print("=" * 30)
print(" PERSONAL PROFILE")
print("=" * 30)
print(f" Name : {name}")
print(f" Age : {age}")
print(f" City : {city}")
print("=" * 30)
# Program 2: Simple receipt
item1_name = "Coffee"
item1_price = 3.50
item2_name = "Muffin"
item2_price = 2.75
total = item1_price + item2_price
print(f"{item1_name:<15} ${item1_price:.2f}")
print(f"{item2_name:<15} ${item2_price:.2f}")
print("-" * 22)
print(f"{'Total':<15} ${total:.2f}")
ποΈ Practical Exercise
Write a Python program that prints a formatted greeting card. Your program should:
- Print a decorative border using
*characters (at least 30 wide). - Print a centered greeting like "Happy Birthday, [Name]!" inside the border.
- Print a message on the next line using an escape character for a new line within a single print call.
- Print a second decorative border to close the card.
- Use a comment to explain what each section does.
π₯ Challenge Exercise
Create a Python program that acts as a simple "receipt printer". Define at least 4 variables for product names and prices. Print a formatted receipt with aligned columns (product name left-aligned, price right-aligned). Calculate and print a subtotal, a 10% tax amount, and a final total. Use only print(), variables, and arithmetic β no functions or loops yet.
Interview Questions on Hello World and print()
- What is the difference between
printin Python 2 and Python 3? - What are the
sepandendparameters ofprint()? Give examples. - What is the difference between a comment and a docstring in Python?
- Name three ways to format a string for printing in Python. Which is preferred?
- What does the
rprefix before a string literal do (raw string)? - What is a
TypeErrorand when does it happen withprint()? - How do you print output on the same line using multiple
print()calls? - What are the common escape characters and what do they do?
π Summary
- Python's Hello World is a single line:
print("Hello, World!"). - The
print()function outputs values to the console and acceptssepandendkeyword arguments. - Python scripts are saved as
.pyfiles and run withpython3 filename.py. - IDLE is Python's built-in editor β press F5 to run scripts.
- Comments use
#and are ignored by Python; they explain your code to humans. - F-strings (
f"...") are the modern, recommended way to format output in Python 3.6+. - Escape characters like
\n(newline) and\t(tab) add special formatting to strings. - Common beginner errors: missing parentheses, wrong capitalization, mixing string + number with
+.
Related Topics
Frequently Asked Questions
In Python 3, print is a regular built-in function, not a special statement. All function calls in Python require parentheses. In Python 2, print was a statement (like return or if) and worked without them, but Python 2 is no longer supported.
Yes. By default, print() adds a newline (\n) at the end. Pass end="" to suppress it: print("Hello", end=""). You can replace the newline with any string, such as a space: print("Hello", end=" ").
In Python, there is no difference. 'Hello' and "Hello" are identical. The convention is to be consistent within a project. Double quotes are slightly more common because they allow apostrophes without escaping: "it's fine" vs 'it\'s fine'.
The best modern approach is f-strings: print(f"Hello, {name}!"). You can also pass multiple arguments to print separated by commas: print("Hello,", name, "!") β print adds a space between each argument by default.
IDLE is the editor bundled with Python. It's great for absolute beginners because it requires no setup. However, most developers quickly move to more powerful editors like VS Code or PyCharm, which offer better features like auto-completion, debugging, and Git integration. Use whatever works best for you.