Ad – 728Γ—90
🌱 Beginner

Hello World in Python – Your First Program

Every programmer's journey starts with the same two words: Hello, World! In Python, this milestone takes exactly one line of code. This lesson walks you through writing and running your first Python program, understanding the print() function, working with the IDLE editor, and writing clean, commented code from day one.

⏱️ 18 min read 🎯 Beginner πŸ“… Updated 2026

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:

Python
print("Hello, World!")
β–Ά Output
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.

πŸ’‘
Python 2 vs Python 3

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

Python
# 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)
β–Ά Output
Hello, World! 42 3.14 True Name: Alice Age: 25 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).

Python
# 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...
β–Ά Output
Python is awesome Python-is-awesome Pythonisawesome 2024/12/25 Hello World 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

Bash
# 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
⚠️
File Naming Rules

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 .py files. 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.

πŸ’‘
IDLE Keyboard Shortcuts

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.

Ad – 336Γ—280

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.

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).

Python
# 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!
β–Ά Output
Hello, Alice!
πŸ’‘
Good Comments vs Bad Comments

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.

Beyond basic printing, Python gives you several powerful ways to format your output. These become essential as your programs grow.

Python
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 {}
β–Ά Output
Name: Alice, Age: 25 Name: Alice, Age: 25 Name: Alice, Age: 25 Name: Alice, Age: 25 Score: 98.77 Age next year: 26

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 \.

Python
# \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")
β–Ά Output
Line 1 Line 2 Line 3 Name: Alice Age: 25 C:\Users\Alice\Documents She said "Hello!" It's a great day! 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.

Python
# 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)
🚨
Most Common First Error

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.

Python
# 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)
β–Ά Output
============================== PERSONAL PROFILE ============================== Name : Alice Age : 25 City : New York ==============================
Python
# 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}")
β–Ά Output
Coffee $3.50 Muffin $2.75 ---------------------- Total $6.25

πŸ‹οΈ Practical Exercise

Write a Python program that prints a formatted greeting card. Your program should:

  1. Print a decorative border using * characters (at least 30 wide).
  2. Print a centered greeting like "Happy Birthday, [Name]!" inside the border.
  3. Print a message on the next line using an escape character for a new line within a single print call.
  4. Print a second decorative border to close the card.
  5. 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 print in Python 2 and Python 3?
  • What are the sep and end parameters of print()? 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 r prefix before a string literal do (raw string)?
  • What is a TypeError and when does it happen with print()?
  • 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 accepts sep and end keyword arguments.
  • Python scripts are saved as .py files and run with python3 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 +.

Frequently Asked Questions

Why do I need parentheses with print() in Python 3? +

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.

Can I print without a newline at the end? +

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=" ").

What is the difference between a string in single quotes and double quotes? +

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'.

How do I print a variable and text together? +

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.

What is IDLE and do I need to use it? +

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.